UNPKG

prettier-plugin-svelte

Version:
2,747 lines • 109 kB
import { parsers as parsers$1 } from 'prettier/plugins/babel';
import { doc, util } from 'prettier/standalone';
import { parse } from 'svelte/compiler';

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  return new (P || (P = Promise))(function (resolve, reject) {
      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
      function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
      step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}

var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  var e = new Error(message);
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

// @see http://xahlee.info/js/html5_non-closing_tag.html
const selfClosingTags = [
    'area',
    'base',
    'br',
    'col',
    'embed',
    'hr',
    'img',
    'input',
    'link',
    'meta',
    'param',
    'source',
    'track',
    'wbr',
];
// https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements#Elements
const blockElements = [
    'address',
    'article',
    'aside',
    'blockquote',
    'details',
    'dialog',
    'dd',
    'div',
    'dl',
    'dt',
    'fieldset',
    'figcaption',
    'figure',
    'footer',
    'form',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'header',
    'hgroup',
    'hr',
    'li',
    'main',
    'menu',
    'nav',
    'ol',
    'p',
    'pre',
    'section',
    'table',
    'ul',
];
/**
 * HTML attributes that we may safely reformat (trim whitespace, add or remove newlines)
 */
const formattableAttributes = [
// None at the moment
// Prettier HTML does not format attributes at all
// and to be consistent we leave this array empty for now
];

// Base64 string encoding and decoding module.
// Uses Buffer for Node.js and btoa/atob for browser environments.
// We use TextEncoder/TextDecoder for browser environments because
// they can handle non-ASCII characters, unlike btoa/atob.
const stringToBase64 = typeof Buffer !== 'undefined'
    ? (str) => Buffer.from(str).toString('base64')
    : (str) => btoa(new TextEncoder()
        .encode(str)
        .reduce((acc, byte) => acc + String.fromCharCode(byte), ''));
const base64ToString = typeof Buffer !== 'undefined'
    ? (str) => Buffer.from(str, 'base64').toString()
    : (str) => new TextDecoder().decode(Uint8Array.from(atob(str), (c) => c.charCodeAt(0)));

const snippedTagContentAttribute = '✂prettier:content✂';
const scriptRegex = /<!--[^]*?-->|<script((?:\s+[^=>'"\/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"\/\s]+)*\s*)>([^]*?)<\/script\s*>/g;
const styleRegex = /<!--[^]*?-->|<style((?:\s+[^=>'"\/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"\/\s]+)*\s*)>([^]*?)<\/style\s*>/g;
const langTsRegex = /\slang=["']?ts["']?/;
function snipScriptAndStyleTagContent(source) {
    let scriptMatchSpans = getMatchIndexes('script');
    let styleMatchSpans = getMatchIndexes('style');
    let isTypescript = false;
    const text = snipTagContent(snipTagContent(source, 'script', '{}', styleMatchSpans), 'style', '', scriptMatchSpans);
    return { text, isTypescript };
    function getMatchIndexes(tagName) {
        const regex = getRegexp(tagName);
        const indexes = [];
        let match = null;
        while ((match = regex.exec(source)) != null) {
            if (source.slice(match.index, match.index + 4) !== '<!--') {
                indexes.push([match.index, regex.lastIndex]);
            }
        }
        return indexes;
    }
    function snipTagContent(_source, tagName, placeholder, otherSpans) {
        const regex = getRegexp(tagName);
        let newScriptMatchSpans = scriptMatchSpans;
        let newStyleMatchSpans = styleMatchSpans;
        // Replace valid matches
        const newSource = _source.replace(regex, (match, attributes, content, index) => {
            if (match.startsWith('<!--') || withinOtherSpan(index)) {
                return match;
            }
            if (langTsRegex.test(attributes)) {
                isTypescript = true;
            }
            const encodedContent = stringToBase64(content);
            const newContent = `<${tagName}${attributes} ${snippedTagContentAttribute}="${encodedContent}">${placeholder}</${tagName}>`;
            // Adjust the spans because the source now has a different content length
            const lengthDiff = match.length - newContent.length;
            newScriptMatchSpans = adjustSpans(scriptMatchSpans, newScriptMatchSpans);
            newStyleMatchSpans = adjustSpans(styleMatchSpans, newStyleMatchSpans);
            function adjustSpans(oldSpans, newSpans) {
                return oldSpans.map((oldSpan, idx) => {
                    const newSpan = newSpans[idx];
                    // Do the check using the old spans because the replace function works
                    // on the old spans. Replace oldSpans with newSpans afterwards.
                    if (oldSpan[0] > index) {
                        // span is after the match -> adjust start and end
                        return [newSpan[0] - lengthDiff, newSpan[1] - lengthDiff];
                    }
                    else if (oldSpan[0] === index) {
                        // span is the match -> adjust end only
                        return [newSpan[0], newSpan[1] - lengthDiff];
                    }
                    else {
                        // span is before the match -> nothing to adjust
                        return newSpan;
                    }
                });
            }
            return newContent;
        });
        // Now that the replacement function ran, we can adjust the spans for the next run
        scriptMatchSpans = newScriptMatchSpans;
        styleMatchSpans = newStyleMatchSpans;
        return newSource;
        function withinOtherSpan(idx) {
            return otherSpans.some((otherSpan) => idx > otherSpan[0] && idx < otherSpan[1]);
        }
    }
    function getRegexp(tagName) {
        return tagName === 'script' ? scriptRegex : styleRegex;
    }
}
function hasSnippedContent(text) {
    return text.includes(snippedTagContentAttribute);
}
const regex = /(<\w+.*?)\s*✂prettier:content✂="(.*?)">.*?(?=<\/)/gi;
function unsnipContent(text) {
    return text.replace(regex, (_, start, encodedContent) => {
        const content = base64ToString(encodedContent);
        return `${start}>${content}`;
    });
}

function makeChoice(choice) {
    return { value: choice, description: choice };
}
const options = {
    svelte5CompilerPath: {
        category: 'Svelte',
        type: 'string',
        default: '',
        description: "Path to the Svelte compiler. You normally don't need to set this.",
    },
    svelteSortOrder: {
        category: 'Svelte',
        type: 'choice',
        default: 'options-scripts-markup-styles',
        description: 'Sort order for scripts, markup, and styles',
        choices: [
            makeChoice('options-scripts-markup-styles'),
            makeChoice('options-scripts-styles-markup'),
            makeChoice('options-markup-styles-scripts'),
            makeChoice('options-markup-scripts-styles'),
            makeChoice('options-styles-markup-scripts'),
            makeChoice('options-styles-scripts-markup'),
            makeChoice('scripts-options-markup-styles'),
            makeChoice('scripts-options-styles-markup'),
            makeChoice('markup-options-styles-scripts'),
            makeChoice('markup-options-scripts-styles'),
            makeChoice('styles-options-markup-scripts'),
            makeChoice('styles-options-scripts-markup'),
            makeChoice('scripts-markup-options-styles'),
            makeChoice('scripts-styles-options-markup'),
            makeChoice('markup-styles-options-scripts'),
            makeChoice('markup-scripts-options-styles'),
            makeChoice('styles-markup-options-scripts'),
            makeChoice('styles-scripts-options-markup'),
            makeChoice('scripts-markup-styles-options'),
            makeChoice('scripts-styles-markup-options'),
            makeChoice('markup-styles-scripts-options'),
            makeChoice('markup-scripts-styles-options'),
            makeChoice('styles-markup-scripts-options'),
            makeChoice('styles-scripts-markup-options'),
            makeChoice('none'),
        ],
    },
    svelteAllowShorthand: {
        category: 'Svelte',
        type: 'boolean',
        default: true,
        description: 'Option to enable/disable component attribute shorthand if attribute name and expressions are same',
    },
    svelteIndentScriptAndStyle: {
        category: 'Svelte',
        type: 'boolean',
        default: true,
        description: 'Whether or not to indent the code inside <script> and <style> tags in Svelte files',
    },
};
const sortOrderSeparator = '-';
function parseSortOrder(sortOrder = 'options-scripts-markup-styles') {
    if (sortOrder === 'none') {
        return [];
    }
    const order = sortOrder.split(sortOrderSeparator);
    if (!order.includes('options')) {
        throw new Error('svelteSortOrder is missing option `options`');
    }
    return order;
}
function isBracketSameLine(options) {
    return options.bracketSameLine != null ? options.bracketSameLine : false;
}

/**
 * Determines whether or not given node
 * is the root of the Svelte AST.
 */
function isASTNode(n) {
    return n && n.__isRoot;
}
function isPreTagContent(path) {
    const stack = path.stack;
    return stack.some((node) => 
    // pre and textarea preserve whitespace
    (node.type === 'RegularElement' &&
        ['pre', 'textarea'].includes(node.name.toLowerCase())) ||
        (node.type === 'Attribute' && !formattableAttributes.includes(node.name)));
}
function flatten(arrays) {
    return [].concat.apply([], arrays);
}
function findLastIndex(isMatch, items) {
    for (let i = items.length - 1; i >= 0; i--) {
        if (isMatch(items[i], i)) {
            return i;
        }
    }
    return -1;
}
function replaceEndOfLineWith(text, replacement) {
    const parts = [];
    for (const part of text.split('\n')) {
        if (parts.length > 0) {
            parts.push(replacement);
        }
        if (part.endsWith('\r')) {
            parts.push(part.slice(0, -1));
        }
        else {
            parts.push(part);
        }
    }
    return parts;
}
function getAttributeLine(node, options) {
    const { hardline, line } = doc.builders;
    const hasThisBinding = ((node.type === 'Component' || node.type === 'SvelteComponent') &&
        !!node.expression) ||
        (node.type === 'SvelteElement' && !!node.tag);
    const attributes = node.attributes.filter((attribute) => attribute.name !== snippedTagContentAttribute);
    return options.singleAttributePerLine &&
        (attributes.length > 1 || (attributes.length && hasThisBinding))
        ? hardline
        : line;
}
function printWithPrependedAttributeLine(node, options, print) {
    return (path) => path.getNode().name !== snippedTagContentAttribute
        ? [getAttributeLine(node, options), path.call(print)]
        : '';
}
/**
 * Prints the comments of an opening tag that has no attributes they could be attached to,
 * e.g. `<div /* comment *\/>` (attached as dangling comments on the element in `embed`).
 */
function printDanglingTagComments(node) {
    var _a, _b;
    const { line, hardline, breakParent, dedent } = doc.builders;
    const comments = ((_a = node.comments) !== null && _a !== void 0 ? _a : []).filter((comment) => !comment.leading && !comment.trailing);
    const parts = [];
    const hasTrailingLineComment = ((_b = comments[comments.length - 1]) === null || _b === void 0 ? void 0 : _b.type) === 'Line';
    comments.forEach((comment) => {
        if (comment.type === 'Line') {
            parts.push(line, '//' + comment.value.replace(/\r$/, ''), breakParent);
        }
        else {
            parts.push(line, '/*' + comment.value + '*/');
        }
    });
    // Always terminate a final line comment, even when the tag hugs its content.
    // The element printer omits its normal separator when this supplies one.
    if (hasTrailingLineComment) {
        parts.push(dedent(hardline));
    }
    return { doc: parts, hasTrailingLineComment };
}

/**
 * Check if doc is a hardline.
 * We can't just rely on a simple equality check because the doc could be created with another
 * runtime version of prettier than what we import, making a reference check fail.
 */
function isHardline(docToCheck) {
    return docToCheck === doc.builders.hardline || deepEqual(docToCheck, doc.builders.hardline);
}
/**
 * Simple deep equal function which suits our needs. Only works properly on POJOs without cyclic deps.
 */
function deepEqual(x, y) {
    if (x === y) {
        return true;
    }
    else if (typeof x == 'object' && x != null && typeof y == 'object' && y != null) {
        if (Object.keys(x).length != Object.keys(y).length)
            return false;
        for (var prop in x) {
            if (y.hasOwnProperty(prop)) {
                if (!deepEqual(x[prop], y[prop]))
                    return false;
            }
            else {
                return false;
            }
        }
        return true;
    }
    else {
        return false;
    }
}
function isDocCommand(doc) {
    return typeof doc === 'object' && doc !== null;
}
function isLine(docToCheck) {
    return (isHardline(docToCheck) ||
        (isDocCommand(docToCheck) && docToCheck.type === 'line') ||
        (Array.isArray(docToCheck) && docToCheck.every(isLine)));
}
/**
 * Check if the doc is empty, i.e. consists of nothing more than empty strings (possibly nested).
 */
function isEmptyDoc(doc) {
    if (typeof doc === 'string') {
        return doc.length === 0;
    }
    if (isDocCommand(doc) && doc.type === 'line') {
        return !doc.keepIfLonely;
    }
    if (Array.isArray(doc)) {
        return doc.length === 0;
    }
    const { contents } = doc;
    if (contents) {
        return isEmptyDoc(contents);
    }
    const { parts } = doc;
    if (parts) {
        return isEmptyGroup(parts);
    }
    return false;
}
function isEmptyGroup(group) {
    return !group.find((doc) => !isEmptyDoc(doc));
}
/**
 * Trims both leading and trailing nodes matching `isWhitespace` independent of nesting level
 * (though all trimmed adjacent nodes need to be a the same level). Modifies the `docs` array.
 */
function trim(docs, isWhitespace) {
    trimLeft(docs, isWhitespace);
    trimRight(docs, isWhitespace);
    return docs;
}
/**
 * Trims the leading nodes matching `isWhitespace` independent of nesting level (though all nodes need to be a the same level).
 * If there are empty docs before the first whitespace, they are removed, too.
 */
function trimLeft(group, isWhitespace) {
    let firstNonWhitespace = group.findIndex((doc) => !isEmptyDoc(doc) && !isWhitespace(doc));
    if (firstNonWhitespace < 0 && group.length) {
        firstNonWhitespace = group.length;
    }
    if (firstNonWhitespace > 0) {
        const removed = group.splice(0, firstNonWhitespace);
        if (removed.every(isEmptyDoc)) {
            return trimLeft(group, isWhitespace);
        }
    }
    else {
        const parts = getParts(group[0]);
        if (parts) {
            return trimLeft(parts, isWhitespace);
        }
    }
}
/**
 * Trims the trailing nodes matching `isWhitespace` independent of nesting level (though all nodes need to be a the same level).
 * If there are empty docs after the last whitespace, they are removed, too.
 */
function trimRight(group, isWhitespace) {
    let lastNonWhitespace = group.length
        ? findLastIndex((doc) => !isEmptyDoc(doc) && !isWhitespace(doc), group)
        : 0;
    if (lastNonWhitespace < group.length - 1) {
        const removed = group.splice(lastNonWhitespace + 1);
        if (removed.every(isEmptyDoc)) {
            return trimRight(group, isWhitespace);
        }
    }
    else {
        const parts = getParts(group[group.length - 1]);
        if (parts) {
            return trimRight(parts, isWhitespace);
        }
    }
}
function getParts(doc) {
    if (typeof doc === 'object') {
        if (Array.isArray(doc)) {
            return doc;
        }
        if (doc.type === 'fill') {
            return doc.parts;
        }
        if (doc.type === 'group') {
            return getParts(doc.contents);
        }
    }
}
/**
 * `(foo = bar)` => `foo = bar`
 * Also handles leading comments and line breaks before "(".
 */
function removeParentheses(doc) {
    if (!Array.isArray(doc))
        return trim([doc], (_doc) => _doc === '(' || _doc === ')')[0];
    const transformed = [];
    let i = 0;
    let opened = false;
    for (; i < doc.length; i++) {
        const part = doc[i];
        if (typeof part === 'string' && part.startsWith('//')) {
            transformed.push(part);
        }
        else if (typeof part === 'string' && part.startsWith('/*')) {
            transformed.push(part);
            opened = true;
        }
        else if (opened) {
            transformed.push(part);
            opened = typeof part !== 'string' || !part.trim().endsWith('*/');
        }
        else if (transformed.length > 0 && isLine(part)) {
            transformed.push(part);
            i++;
            const next = doc[i];
            if (typeof next !== 'string' && !Array.isArray(next) && next.type === 'break-parent') {
                transformed.push(next);
                i++;
            }
            break;
        }
        else {
            break;
        }
    }
    transformed.push(...trim(doc.slice(i), (_doc) => _doc === '(' || _doc === ')'));
    return transformed;
}

const unsupportedLanguages = ['coffee', 'coffeescript', 'styl', 'stylus', 'sass'];
/**
 * Characters treated as interchangeable/collapsible HTML whitespace for layout.
 * Excludes NBSP (U+00A0) and other Unicode separators — see prettier/prettier#5796.
 */
const ONLY_HTML_COLLAPSE_WHITESPACE_RE = /^[\t\n\f\r ]*$/;
const STARTS_WITH_HTML_COLLAPSE_WHITESPACE_RE = /^[\t\n\f\r ]/;
const ENDS_WITH_HTML_COLLAPSE_WHITESPACE_RE = /[\t\n\f\r ]$/;
const LEADING_HTML_COLLAPSE_WHITESPACE_RE = /^[\t\n\f\r ]+/;
const TRAILING_HTML_COLLAPSE_WHITESPACE_RE = /[\t\n\f\r ]+$/;
function isOnlyHtmlCollapseWhitespace(text) {
    return ONLY_HTML_COLLAPSE_WHITESPACE_RE.test(text);
}
function isInlineElement(path, options, node) {
    return (node &&
        node.type === 'RegularElement' &&
        !isBlockElement(node, options) &&
        !isPreTagContent(path));
}
function isBlockElement(node, options) {
    return (node &&
        node.type === 'RegularElement' &&
        options.htmlWhitespaceSensitivity !== 'strict' &&
        (options.htmlWhitespaceSensitivity === 'ignore' ||
            blockElements.includes(node.name)));
}
function isNodeWithChildren(node) {
    return !!getMaybeChildren(node);
}
function getMaybeChildren(_node) {
    if (_node.type === 'Fragment')
        return _node.nodes;
    for (const key of Object.keys(_node)) {
        const value = _node[key];
        if (typeof value === 'object' && value != null && value.type === 'Fragment') {
            return value.nodes;
        }
    }
}
function getChildren(_node) {
    return getMaybeChildren(_node) || [];
}
/**
 * Returns siblings, that is, the children of the parent.
 */
function getSiblings(path) {
    let parent = path.getParentNode();
    if (isASTNode(parent)) {
        parent = parent.fragment;
    }
    return parent.nodes;
}
/**
 * Returns the comment that is above the current node.
 */
function getLeadingComment(path) {
    const siblings = getSiblings(path);
    let node = path.getNode();
    let prev = siblings.find((child) => child.end === node.start);
    while (prev) {
        if (prev.type === 'Comment' &&
            !isIgnoreStartDirective(prev) &&
            !isIgnoreEndDirective(prev)) {
            return prev;
        }
        else if (isEmptyTextNode(prev)) {
            node = prev;
            prev = siblings.find((child) => child.end === node.start);
        }
        else {
            return undefined;
        }
    }
}
function isNodeTopLevelHTML(node, path) {
    const root = path.stack[0];
    return !!root.fragment && !!root.fragment.nodes && root.fragment.nodes.includes(node);
}
function isEmptyTextNode(node) {
    return !!node && node.type === 'Text' && isOnlyHtmlCollapseWhitespace(getUnencodedText(node));
}
function isIgnoreDirective(node) {
    return !!node && node.type === 'Comment' && node.data.trim() === 'prettier-ignore';
}
function isIgnoreStartDirective(node) {
    return !!node && node.type === 'Comment' && node.data.trim() === 'prettier-ignore-start';
}
function isIgnoreEndDirective(node) {
    return !!node && node.type === 'Comment' && node.data.trim() === 'prettier-ignore-end';
}
function printRaw(node, originalText, stripLeadingAndTrailingNewline = false) {
    const children = getChildren(node);
    if (children.length === 0) {
        return '';
    }
    const firstChild = children[0];
    const lastChild = children[children.length - 1];
    let raw = originalText.substring(firstChild.start, lastChild.end);
    if (!stripLeadingAndTrailingNewline) {
        return raw;
    }
    if (startsWithLinebreak(raw)) {
        raw = raw.substring(raw.indexOf('\n') + 1);
    }
    if (endsWithLinebreak(raw)) {
        raw = raw.substring(0, raw.lastIndexOf('\n'));
        if (raw.charAt(raw.length - 1) === '\r') {
            raw = raw.substring(0, raw.length - 1);
        }
    }
    return raw;
}
function isTextNode(node) {
    return node.type === 'Text';
}
function getAttributeValue(attributeName, node) {
    var _a;
    const attributes = ((_a = node.attributes) !== null && _a !== void 0 ? _a : []);
    const langAttribute = attributes.find((attribute) => attribute.name === attributeName);
    return langAttribute && langAttribute.value;
}
function getAttributeTextValue(attributeName, node) {
    const value = getAttributeValue(attributeName, node);
    if (value != null && typeof value === 'object') {
        const value_nodes = Array.isArray(value) ? value : [value];
        const textValue = value_nodes.find(isTextNode);
        if (textValue) {
            return textValue.data;
        }
    }
    return null;
}
function getLangAttribute(node) {
    const value = getAttributeTextValue('lang', node) || getAttributeTextValue('type', node);
    if (value != null) {
        return value.replace(/^text\//, '');
    }
    else {
        return null;
    }
}
/**
 * Checks whether the node contains a `lang` or `type` attribute with a value corresponding to
 * a language we cannot format. This might for example be `<template lang="pug">`.
 * If the node does not contain a `lang` attribute, the result is true.
 */
function isNodeSupportedLanguage(node) {
    const lang = getLangAttribute(node);
    return !(lang && unsupportedLanguages.includes(lang));
}
/**
 * Checks whether the node contains a `lang` or `type` attribute which indicates that
 * the script contents are written in TypeScript. Note that the absence of the tag
 * does not mean it's not TypeScript, because the user could have set the default
 * to TypeScript in his settings.
 */
function isTypeScript(node) {
    const lang = getLangAttribute(node) || '';
    return ['typescript', 'ts'].includes(lang);
}
function isJSON(node) {
    const lang = getLangAttribute(node) || '';
    // todo: check if this is still necessary
    // https://github.com/prettier/prettier/pull/6293
    return lang.endsWith('json') || lang.endsWith('importmap');
}
function isLess(node) {
    const lang = getLangAttribute(node) || '';
    return ['less'].includes(lang);
}
function isScss(node) {
    const lang = getLangAttribute(node) || '';
    return ['sass', 'scss'].includes(lang);
}
function isPugTemplate(node) {
    return (node.type === 'RegularElement' &&
        node.name === 'template' &&
        getLangAttribute(node) === 'pug');
}
function isLoneMustacheTag(node) {
    if (node === true || node == null) {
        return false;
    }
    if (Array.isArray(node)) {
        return node.length === 1 && node[0].type === 'ExpressionTag';
    }
    return node.type === 'ExpressionTag';
}
/**
 * True if node is of type `{a}` or `a={a}`
 */
function isOrCanBeConvertedToShorthand(node) {
    if (isLoneMustacheTag(node.value)) {
        const value_node = Array.isArray(node.value) ? node.value[0] : node.value;
        const expression = value_node.type === 'ExpressionTag' ? value_node.expression : null;
        if (!expression) {
            return false;
        }
        return expression.type === 'Identifier' && expression.name === node.name;
    }
    return false;
}
function getUnencodedText(node) {
    // `raw` will contain HTML entities in unencoded form
    return node.raw || node.data;
}
function isTextNodeStartingWithLinebreak(node, nrLines = 1) {
    return node.type === 'Text' && startsWithLinebreak(getUnencodedText(node), nrLines);
}
function startsWithLinebreak(text, nrLines = 1) {
    return new RegExp(`^([\\t\\f\\r ]*\\n){${nrLines}}`).test(text);
}
function isTextNodeEndingWithLinebreak(node, nrLines = 1) {
    return node.type === 'Text' && endsWithLinebreak(getUnencodedText(node), nrLines);
}
function endsWithLinebreak(text, nrLines = 1) {
    return new RegExp(`(\\n[\\t\\f\\r ]*){${nrLines}}$`).test(text);
}
function isTextNodeStartingWithWhitespace(node) {
    return (node.type === 'Text' && STARTS_WITH_HTML_COLLAPSE_WHITESPACE_RE.test(getUnencodedText(node)));
}
function isTextNodeEndingWithWhitespace(node) {
    return (node.type === 'Text' && ENDS_WITH_HTML_COLLAPSE_WHITESPACE_RE.test(getUnencodedText(node)));
}
function trimTextNodeRight(node) {
    node.raw = node.raw && node.raw.replace(TRAILING_HTML_COLLAPSE_WHITESPACE_RE, '');
    node.data = node.data && node.data.replace(TRAILING_HTML_COLLAPSE_WHITESPACE_RE, '');
}
function trimTextNodeLeft(node) {
    node.raw = node.raw && node.raw.replace(LEADING_HTML_COLLAPSE_WHITESPACE_RE, '');
    node.data = node.data && node.data.replace(LEADING_HTML_COLLAPSE_WHITESPACE_RE, '');
}
/**
 * Remove all leading whitespace up until the first non-empty text node,
 * and all trailing whitespace from the last non-empty text node onwards.
 */
function trimChildren(children) {
    let firstNonEmptyNode = children.findIndex((n) => !isEmptyTextNode(n));
    firstNonEmptyNode = firstNonEmptyNode === -1 ? children.length - 1 : firstNonEmptyNode;
    let lastNonEmptyNode = findLastIndex((n) => !isEmptyTextNode(n), children);
    lastNonEmptyNode = lastNonEmptyNode === -1 ? 0 : lastNonEmptyNode;
    for (let i = 0; i <= firstNonEmptyNode; i++) {
        const n = children[i];
        if (n.type === 'Text') {
            trimTextNodeLeft(n);
        }
    }
    for (let i = children.length - 1; i >= lastNonEmptyNode; i--) {
        const n = children[i];
        if (n.type === 'Text') {
            trimTextNodeRight(n);
        }
    }
}
/**
 * Svelte trims element edges except in preformatted content, head titles, and components
 * with preserveWhitespace enabled. Strict sensitivity also keeps the previous hugging behavior.
 */
function canIgnoreElementEdgeWhitespace(node, options, path) {
    var _a;
    const root = path.stack[0];
    return (options.htmlWhitespaceSensitivity !== 'strict' &&
        !((_a = root.options) === null || _a === void 0 ? void 0 : _a.preserveWhitespace) &&
        node.type !== 'TitleElement' &&
        !isPreTagContent(path));
}
/**
 * Check whether whitespace sensitivity requires the opening tag to hug its first child.
 */
function shouldHugStart(node, isSupportedLanguage, options, path) {
    if (!isSupportedLanguage) {
        return true;
    }
    if (node.type === 'SvelteBoundary') {
        return false;
    }
    if (isBlockElement(node, options)) {
        return false;
    }
    if (!isNodeWithChildren(node)) {
        return false;
    }
    const children = getChildren(node);
    if (children.length === 0) {
        return true;
    }
    if (options.htmlWhitespaceSensitivity === 'ignore') {
        return false;
    }
    if (canIgnoreElementEdgeWhitespace(node, options, path)) {
        return false;
    }
    const firstChild = children[0];
    return !isTextNodeStartingWithWhitespace(firstChild);
}
/**
 * Check whether whitespace sensitivity requires the closing tag to hug its last child.
 */
function shouldHugEnd(node, isSupportedLanguage, options, path) {
    if (!isSupportedLanguage) {
        return true;
    }
    if (node.type === 'SvelteBoundary') {
        return false;
    }
    if (isBlockElement(node, options)) {
        return false;
    }
    if (!isNodeWithChildren(node)) {
        return false;
    }
    const children = getChildren(node);
    if (children.length === 0) {
        return true;
    }
    if (options.htmlWhitespaceSensitivity === 'ignore') {
        return false;
    }
    if (canIgnoreElementEdgeWhitespace(node, options, path)) {
        return false;
    }
    const lastChild = children[children.length - 1];
    return !isTextNodeEndingWithWhitespace(lastChild);
}
/**
 * Check for a svelte block if there's whitespace at the start and if it's a space or a line.
 */
function checkWhitespaceAtStartOfSvelteBlock(node, options) {
    if (!isNodeWithChildren(node)) {
        return 'none';
    }
    const children = node.nodes;
    if (children.length === 0) {
        return 'none';
    }
    const firstChild = children[0];
    if (isTextNodeStartingWithLinebreak(firstChild)) {
        return 'line';
    }
    else if (isTextNodeStartingWithWhitespace(firstChild)) {
        return 'space';
    }
    // This extra check is necessary because the Svelte AST might swallow whitespace between
    // the block's starting end and its first child.
    const parentOpeningEnd = options.originalText.lastIndexOf('}', firstChild.start);
    if (parentOpeningEnd > 0 && firstChild.start > parentOpeningEnd + 1) {
        const textBetween = options.originalText.substring(parentOpeningEnd + 1, firstChild.start);
        if (ONLY_HTML_COLLAPSE_WHITESPACE_RE.test(textBetween)) {
            return startsWithLinebreak(textBetween) ? 'line' : 'space';
        }
    }
    return 'none';
}
/**
 * Check for a svelte block if there's whitespace at the end and if it's a space or a line.
 */
function checkWhitespaceAtEndOfSvelteBlock(node, options) {
    if (!isNodeWithChildren(node)) {
        return 'none';
    }
    const children = node.nodes;
    if (children.length === 0) {
        return 'none';
    }
    const lastChild = children[children.length - 1];
    if (isTextNodeEndingWithLinebreak(lastChild)) {
        return 'line';
    }
    else if (isTextNodeEndingWithWhitespace(lastChild)) {
        return 'space';
    }
    // This extra check is necessary because the Svelte AST might swallow whitespace between
    // the last child and the block's ending start.
    const parentClosingStart = options.originalText.indexOf('{', lastChild.end);
    if (parentClosingStart > 0 && lastChild.end < parentClosingStart) {
        const textBetween = options.originalText.substring(lastChild.end, parentClosingStart);
        if (ONLY_HTML_COLLAPSE_WHITESPACE_RE.test(textBetween)) {
            return endsWithLinebreak(textBetween) ? 'line' : 'space';
        }
    }
    return 'none';
}
function isInsideQuotedAttribute(path, options) {
    const stack = path.stack;
    return stack.some((node) => (node.type === 'Attribute' || node.type === 'StyleDirective') &&
        !isLoneMustacheTag(node.value));
}
/**
 * Returns true if the softline between `</tagName` and `>` can be omitted.
 */
function canOmitSoftlineBeforeClosingTag(node, path, options) {
    return (isBracketSameLine(options) &&
        (!hugsStartOfNextNode(node, options) || isLastChildWithinParentBlockElement(path, options)));
}
/**
 * Return true if given node does not hug the next node, meaning there's whitespace
 * or the end of the doc afterwards.
 */
function hugsStartOfNextNode(node, options) {
    if (node.end === options.originalText.length) {
        // end of document
        return false;
    }
    return !STARTS_WITH_HTML_COLLAPSE_WHITESPACE_RE.test(options.originalText.substring(node.end));
}
function isLastChildWithinParentBlockElement(path, options) {
    const fragment = path.getParentNode();
    const parent = path.getParentNode(1);
    if (!fragment || !parent || !isBlockElement(parent, options)) {
        return false;
    }
    const children = fragment.nodes.filter((child) => !isEmptyTextNode(child));
    const lastChild = children[children.length - 1];
    return lastChild === path.getNode();
}
function assignCommentsToNodes(ast) {
    if (ast.module) {
        ast.module.comments = removeAndGetLeadingComments(ast, ast.module);
    }
    if (ast.instance) {
        ast.instance.comments = removeAndGetLeadingComments(ast, ast.instance);
    }
    if (ast.css) {
        ast.css.comments = removeAndGetLeadingComments(ast, ast.css);
    }
}
/**
 * Returns the comments that are above the current node and deletes them from the html ast.
 */
function removeAndGetLeadingComments(ast, current) {
    const siblings = ast.fragment.nodes;
    const comments = [];
    const newlines = [];
    if (!siblings.length) {
        return [];
    }
    let node = current;
    let prev = siblings.find((child) => child.end === node.start);
    while (prev) {
        if (prev.type === 'Comment' &&
            !isIgnoreStartDirective(prev) &&
            !isIgnoreEndDirective(prev)) {
            comments.push(prev);
            if (comments.length !== newlines.length) {
                newlines.push({ type: 'Text', data: '', raw: '', start: -1, end: -1 });
            }
        }
        else if (isEmptyTextNode(prev)) {
            newlines.push(prev);
        }
        else {
            break;
        }
        node = prev;
        prev = siblings.find((child) => child.end === node.start);
    }
    newlines.length = comments.length; // could be one more if first comment is preceeded by empty text node
    for (const comment of comments) {
        siblings.splice(siblings.indexOf(comment), 1);
    }
    for (const text of newlines) {
        // Placeholders for adjacent comments are not in the AST, and
        // splice(-1, 1) would remove the last node instead.
        const index = siblings.indexOf(text);
        if (index !== -1) {
            siblings.splice(index, 1);
        }
    }
    return comments
        .map((comment, i) => ({
        comment,
        emptyLineAfter: getUnencodedText(newlines[i]).split('\n').length > 2,
    }))
        .reverse();
}

const { join, line, group, indent, dedent, softline, hardline, fill, breakParent, literalline } = doc.builders;
function hasPragma(text) {
    return /^\s*<!--\s*@(format|prettier)\W/.test(text);
}
let ignoreNext = false;
let ignoreRange = false;
function print(path, options, print) {
    var _a, _b, _c, _d;
    const bracketSameLine = isBracketSameLine(options);
    const n = path.node;
    if (!n) {
        return '';
    }
    if (isASTNode(n)) {
        return printTopLevelParts(n, options, path, print);
    }
    const [open, close] = ['{', '}'];
    const printJsExpression = () => [open, printJS(path, print, 'expression'), close];
    const node = n;
    if ((ignoreNext || (ignoreRange && !isIgnoreEndDirective(node))) &&
        (node.type !== 'Text' || !isEmptyTextNode(node))) {
        if (ignoreNext) {
            ignoreNext = false;
        }
        return flatten(options.originalText
            .slice(options.locStart(node), options.locEnd(node))
            .split('\n')
            .map((o, i) => (i == 0 ? [o] : [literalline, o])));
    }
    switch (node.type) {
        case 'Fragment':
            const children = node.nodes;
            if (children.length === 0 || children.every(isEmptyTextNode)) {
                return '';
            }
            if (!isPreTagContent(path)) {
                trimChildren(children);
                const output = trim([printChildren(path, print, options)], (n) => isLine(n) ||
                    (typeof n === 'string' && isOnlyHtmlCollapseWhitespace(n)) ||
                    // Because printChildren may append this at the end and
                    // may hide other lines before it
                    n === breakParent);
                if (output.every((doc) => isEmptyDoc(doc))) {
                    return '';
                }
                return group([...output, hardline]);
            }
            else {
                return group(path.map(print, 'nodes'));
            }
        case 'Text':
            if (!isPreTagContent(path)) {
                if (isEmptyTextNode(node)) {
                    return printWhitespace(getUnencodedText(node));
                }
                /**
                 * For non-empty text nodes each sequence of non-whitespace characters (effectively,
                 * each "word") is joined by a single `line`, which will be rendered as a single space
                 * until this node's current line is out of room, at which `fill` will break at the
                 * most convenient instance of `line`.
                 */
                return fill(splitTextToDocs(node));
            }
            else {
                let rawText = getUnencodedText(node);
                const parent = path.getParentNode();
                if (parent.type === 'Attribute') {
                    // Direct child of attribute value -> add literallines at end of lines
                    // so that other things don't break in unexpected places
                    if (parent.name === 'class' &&
                        path.getParentNode(1).type === 'RegularElement') {
                        // Special treatment for class attribute on html elements. Prettier
                        // will force everything into one line, we deviate from that and preserve lines.
                        rawText = rawText.replace(/([^ \t\n])(([ \t]+$)|([ \t]+(\r?\n))|[ \t]+)/g, 
                        // Remove trailing whitespace in lines with non-whitespace characters
                        // except at the end of the string
                        (match, characterBeforeWhitespace, _, isEndOfString, isEndOfLine, endOfLine) => isEndOfString
                            ? match
                            : characterBeforeWhitespace + (isEndOfLine ? endOfLine : ' '));
                        // Shrink trailing whitespace in case it's followed by a mustache tag
                        // and remove it completely if it's at the end of the string, but not
                        // if it's on its own line
                        rawText = rawText.replace(/([^ \t\n])[ \t]+$/, parent.value.indexOf(node) === parent.value.length - 1 ? '$1' : '$1 ');
                    }
                    return replaceEndOfLineWith(rawText, literalline);
                }
                return rawText;
            }
        case 'RegularElement':
        case 'Component':
        case 'SvelteComponent':
        case 'SvelteSelf':
        case 'SlotElement':
        case 'SvelteFragment':
        case 'SvelteWindow':
        case 'SvelteHead':
        case 'SvelteBody':
        case 'SvelteDocument':
        case 'SvelteElement':
        case 'SvelteBoundary':
        case 'TitleElement': {
            const isSupportedLanguage = !(node.name === 'template' && !isNodeSupportedLanguage(node));
            const element_children = getChildren(node);
            const isEmpty = element_children.every((child) => isEmptyTextNode(child));
            const isDoctypeTag = node.name.toUpperCase() === '!DOCTYPE';
            const didSelfClose = options.originalText[node.end - 2] === '/';
            const isSelfClosingTag = isEmpty &&
                (((node.type === 'RegularElement' ||
                    node.type === 'SvelteHead' ||
                    node.type === 'Component' ||
                    node.type === 'SvelteComponent' ||
                    node.type === 'SvelteSelf' ||
                    node.type === 'SlotElement' ||
                    node.type === 'SvelteFragment' ||
                    node.type === 'SvelteBoundary' ||
                    node.type === 'TitleElement' ||
                    node.type === 'SvelteBody' ||
                    node.type === 'SvelteDocument' ||
                    node.type === 'SvelteElement') &&
                    didSelfClose) ||
                    node.type === 'SvelteWindow' ||
                    selfClosingTags.indexOf(node.name) !== -1 ||
                    isDoctypeTag);
            // Order important: print attributes first
            const attributes = path.map(printWithPrependedAttributeLine(node, options, print), 'attributes');
            const { doc: danglingComments, hasTrailingLineComment } = printDanglingTagComments(node);
            attributes.push(...danglingComments);
            const attributeLine = getAttributeLine(node, options);
            const possibleThisBinding = node.type === 'SvelteComponent' && node.expression
                ? [attributeLine, 'this=', ...printJsExpression()]
                : node.type === 'SvelteElement' && node.tag
                    ? [
                        attributeLine,
                        'this=',
                        ...(() => {
                            var _a;
                            if (typeof node.tag === 'string') {
                                return [`"${node.tag}"`];
                            }
                            if (((_a = node.tag) === null || _a === void 0 ? void 0 : _a.type) === 'Literal' &&
                                typeof node.tag.value === 'string') {
                                const literal_value = node.tag.value;
                                const tag_start = node.tag.start;
                                const expression_wrapped = typeof tag_start === 'number' &&
                                    options.originalText[tag_start - 1] === '{';
                                // Preserve <svelte:element this={"literal"}>
                                // because in Svelte 6 this="literal" will be invalid
                                if (expression_wrapped) {
                                    return [open, printJS(path, print, 'tag'), close];
                                }
                                return [`"${literal_value}"`];
                            }
                            return [open, printJS(path, print, 'tag'), close];
                        })(),
                    ]
                    : '';
            if (isSelfClosingTag) {
                return group([
                    '<',
                    node.name,
                    indent(group([
                        possibleThisBinding,
                        ...attributes,
                        bracketSameLine || isDoctypeTag || hasTrailingLineComment
                            ? ''
                            : dedent(line),
                    ])),
                    ...[
                        bracketSameLine && !isDoctypeTag && !hasTrailingLineComment ? ' ' : '',
                        `${isDoctypeTag ? '' : '/'}>`,
                    ],
                ]);
            }
            const children = element_children;
            const firstChild = children[0];
            const lastChild = children[children.length - 1];
            // Is a function which is invoked later because printChildren will manipulate child nodes
            // which would wrongfully change the other checks about hugging etc done beforehand
            let body;
            const hugStart = shouldHugStart(node, isSupportedLanguage, options, path);
            const hugEnd = shouldHugEnd(node, isSupportedLanguage, options, path);
            if (isEmpty) {
                body =
                    isInlineElement(path, options, node) &&
                        children.length &&
                        isTextNodeStartingWithWhitespace(children[0]) &&
                        !isPreTagContent(path)
                        ? () => line
                        : () => (bracketSameLine ? softline : '');
            }
            else if (isPreTagContent(path)) {
                body = () => path.call((fragment_path) => printPre(options.originalText, fragment_path, print), 'fragment');
            }
            else if (!isSupportedLanguage) {
                body = () => printRaw(node, options.originalText, true);
            }
            else if (isInlineElement(path, options, node) && !isPreTagContent(path)) {
                body = () => path.call((fragment_path) => printChildren(fragment_path, print, options), 'fragment');
            }
            else {
                body = () => path.call((fragment_path) => printChildren(fragment_path, print, options), 'fragment');
            }
            const openingTag = [
                '<',
                node.name,
                indent(group([
                    possibleThisBinding,
                    ...attributes,
                    hasTrailingLineComment || (hugStart && !isEmpty)
                        ? ''
                        : !bracketSameLine &&
                            !isPreTagContent(path) &&
                            (attributes.length > 0 || possibleThisBinding !== '')
                            ? dedent(softline)
                            : '',
                ])),
            ];
            if (!isSupportedLanguage && !isEmpty) {
                // Format template tags so that there's a hardline but no indention.
                // That way the `lang="X"` and the closing `>` of the start tag stay in one line
                // which is the 99% use case.
                return group([
                    ...openingTag,
                    '>',
                    group([hardline, body(), hardline]),
                    `</${node.name}>`,
                ]);
            }
            if (hugStart && hugEnd) {
                const huggedContent = [
                    hasTrailingLineComment ? '' : softline,
                    group(['>', body(), `</${node.name}`]),
                ];
                const omitSoftlineBeforeClosingTag = (isEmpty && !bracketSameLine) ||
                    canOmitSoftlineBeforeClosingTag(node, path, options);
                return group([
                    ...openingTag,
                    isEmpty ? group(huggedContent) : group(indent(huggedContent)),
                    omitSoftlineBeforeClosingTag ? '' : softline,
                    '>',
                ]);
            }
            // No hugging of content means it's either a block element and/or there's whitespace at the start/end
            let noHugSeparatorStart = softline;
            let noHugSeparatorEnd = softline;
            if (isPreTagContent(path)) {
                noHugSeparatorStart = '';
                noHugSeparatorEnd = '';
            }
            else {
                let didSetEndSeparator = false;
                if (!hugStart && firstChild && firstChild.type === 'Text') {
                    if (isTextNodeStartingWithLinebreak(firstChild) &&
                        firstChild !== lastChild &&
                        (!isInlineElement(path, options, node) ||
                            isTextNodeEndingWithWhitespace(lastChild))) {
                        noHugSeparatorStart = hardline;
                        noHugSeparatorEnd = hardline;
                        didSetEndSeparator = true;
                    }
                    else if (isInlineElement(path, options, node) &&
                        isTextNodeStartingWithWhitespace(firstChild)) {
                        noHugSeparatorStart = line;
                    }
                    trimTextNodeLeft(firstChild);
                }
                if (!hugEnd && lastChild && lastChild.type === 'Text') {
                    if (isInlineElement(path, options, node) &&
                        !didSetEndSeparator &&
                        isTextNodeEndingWithWhitespace(lastChild)) {
                        noHugSeparatorEnd = line;
                    }
                    trimTextNodeRight(lastChild);
                }
            }
            if (hugStart) {
                return group([
                    ...openingTag,
                    indent([hasTrailingLineComment ? '' : softline, group(['>', body()])]),
                    noHugSeparatorEnd,
                    `</${node.name}>`,
                ]);
            }
            if (hugEnd) {
                return group([
                    ...openingTag,
                    '>',
                    indent([noHugSeparatorStart, group([body(), `</${node.name}`])]),
                    canOmitSoftlineBeforeClosingTag(node, path, options) ? '' : softline,
                    '>',
                ]);
            }
            if (isEmpty) {
                return group([...openingTag, '>', body(), `</${node.name}>`]);
            }
            return group([
                ...openingTag,
                '>',
                indent([noHugSeparatorStart, body()]),
                noHugSeparatorEnd,
                `</${node.name}>`,
            ]);
        }
        case 'Options':
            if (options.svelteSortOrder !== 'none') {
                throw new Error('Options tags should have been handled by prepareChildren');
            }
            return group([
                '<',
                node.name,
                indent(group([
                    ...path.map(printWithPrependedAttributeLine(node, options, print), 'attributes'),
                    bracketSameLine ? '' : dedent(line),
                ])),
                ...[bracketSameLine ? ' ' : '', '/>'],
            ]);
        case 'Identifier':
            return node.name;
        case 'Literal':
            return JSON.stringify(node.value);
        case 'ConditionalExpression':
            return group([
                printJS(path, print, 'test'),
                indent([
                    line,
                    '? ',
                    printJS(path, print, 'consequent'),
                    line,
                    ': ',
                    printJS(path, print, 'alternate'),
                ]),
            ]);
        case 'VariableDeclarator':
            return [printJS(path, print, 'id'), ' = ', printJS(path, print, 'init')];
        case 'Attribute': {
            if (isOrCanBeConvertedToShorthand(node)) {
                if (options.svelteAllowShorthand) {
                    return ['{', node.name, '}'];
                }
                else {
                    return [node.name, `=${open}`, node.name, close];
                }
            }
            else {
                if (node.value === true) {
                    return [node.name];
                }
                const quotes = !isLoneMustacheTag(node.value);
                const attrNodeValue = printAttributeNodeValue(path, print, quotes, node);
                if (quotes) {
                    return [node.name, '=', '"', attrNodeValue, '"'];
                }
                else {
                    return [node.name, '=', attrNodeValue];
                }
            }
        }
        case 'ExpressionTag':
            return ['{', printJS(path, print, 'expression'), '}'];
        case 'IfBlock': {
            const def = [
                '{#if ',
                printJS(path, print, 'test'),
                '}',
                printBlockFragment(path, print, options, 'consequent'),
            ];
            if (node.alternate) {
                def.push(printIfBlockAlternate(path, print, options));
            }
            def.push('{/if}');
            return group([def, breakParent]);
        }
        case 'EachBlock': {
            const def = ['{#each ', printJS(path, print, 'expression')];
            if (node.context) {
                def.push(' as', expandNode(node.context, options.originalText));
            }
            if (node.index) {
                def.push(', ', node.index);
            }
            if (node.key) {
                def.push(' (', printJS(path, print, 'key'), ')');
            }
            def.push('}', printBlockFragment(path, print, options, 'body'));
            if (node.fallback) {
                def.push(printEachBlockFallback(path, print, options));
            }
            def.push('{/each}');
            return group([def, breakParent]);
        }
        case 'AwaitBlock': {
            const pending_children = (_b = (_a = node.pending) === null || _a === void 0 ? void 0 : _a.nodes) !== null && _b !== void 0 ? _b : [];
            const then_children = (_d = (_c = node.then) === null || _c === void 0 ? void 0 : _c.nodes) !== null && _d !== void 0 ? _d : [];
            const hasPendingBlock = pending_children.some((n) => !isEmptyTextNode(n));
            const hasThenBlock = then_children.some((n) => !isEmptyTextNode(n));
            // Keep an empty `{:catch}`: without one, Svelte rethrows the rejection
            const hasCatchBlock = !!node.catch;
            let block = [];
            if (!hasPendingBlock && hasThenBlock) {
                block.push(group([
                    '{#await ',
                    printJS(path, print, 'expression'),
                    ' then',
                    expandNode(node.value, options.originalText),
                    '}',
                ]), printBlockFragment(path, print, options, 'then'));
            }
            else if (!hasPendingBlock && hasCatchBlock) {
                block.push(group([
                    '{#await ',
                    printJS(path, print, 'expression'),
                    ' catch',
                    expandNode(node.error, options.originalText),
                    '}',
                ]), printBlockFragment(path, print, options, 'catch'));
            }
            else {
                block.push(group(['{#await ', printJS(path, print, 'expression'), '}']));
                if (hasPendingBlock) {
                    block.push(printBlockFragment(path, print, options, 'pending'));
                }
                if (hasThenBlock) {
                    block.push(group(['{:then', expandNode(node.value, options.originalText), '}']), printBlockFragment(path, print, options, 'then'));
                }
            }
            if ((hasPendingBlock || hasThenBlock) && hasCatchBlock) {
                block.push(group(['{:catch', expandNode(node.error, options.originalText), '}']), printBlockFragment(path, print, options, 'catch'));
            }
            block.push('{/await}');
            return group(block);
        }
        case 'KeyBlock': {
            const def = [
                '{#key ',
                printJS(path, print, 'expression'),
                '}',
                printBlockFragment(path, print, options, 'fragment'),
            ];
            def.push('{/key}');
            return group([def, breakParent]);
        }
        case 'SnippetBlock': {
            const snippet = ['{#snippet ', printJS(path, print, 'expression')];
            snippet.push('}', printBlockFragment(path, print, options, 'body'), '{/snippet}');
            return snippet;
        }
        case 'OnDirective':
            return [
                'on:',
                node.name,
                node.modifiers && node.modifiers.length ? ['|', join('|', node.modifiers)] : '',
                node.expression ? ['=', ...printJsExpression()] : '',
            ];
        case 'BindDirective':
            return [
                'bind:',
                node.name,
                node.expression.type === 'Identifier' &&
                    node.expression.name === node.name &&
                    options.svelteAllowShorthand
                    ? ''
                    : ['=', ...printJsExpression()],
            ];
        case 'ClassDirective':
            return [
                'class:',
                node.name,
                node.expression.type === 'Identifier' &&
                    node.expression.name === node.name &&
                    options.svelteAllowShorthand
                    ? ''
                    : ['=', ...printJsExpression()],
            ];
        case 'StyleDirective':
            const prefix = [
                'style:',
                node.name,
                node.modifiers && node.modifiers.length ? ['|', join('|', node.modifiers)] : '',
            ];
            if (isOrCanBeConvertedToShorthand(node) || node.value === true) {
                if (options.svelteAllowShorthand) {
                    return [...prefix];
                }
                else {
                    return [...prefix, `=${open}`, node.name, close];
                }
            }
            else {
                const quotes = !isLoneMustacheTag(node.value);
                const attrNodeValue = printAttributeNodeValue(path, print, quotes, node);
                if (quotes) {
                    return [...prefix, '=', '"', attrNodeValue, '"'];
                }
                else {
                    return [...prefix, '=', attrNodeValue];
                }
            }
        case 'LetDirective':
            return [
                'let:',
                node.name,
                // shorthand let directives have `null` expressions
                !node.expression ||
                    (node.expression.type === 'Identifier' && node.expression.name === node.name)
                    ? ''
                    : ['=', ...printJsExpression()],
            ];
        case 'DebugTag':
            return [
                '{@debug',
                node.identifiers.length > 0
                    ? [' ', join(', ', path.map(print, 'identifiers'))]
                    : '',
                '}',
            ];
        case 'Comment': {
            if (isIgnoreStartDirective(node) && isNodeTopLevelHTML(node, path)) {
                ignoreRange = true;
            }
            else if (isIgnoreEndDirective(node) && isNodeTopLevelHTML(node, path)) {
                ignoreRange = false;
            }
            else if (isIgnoreDirective(node)) {
                ignoreNext = true;
            }
            return printComment(node);
        }
        case 'TransitionDirective':
            const kind = node.intro && node.outro ? 'transition' : node.intro ? 'in' : 'out';
            return [
                kind,
                ':',
                node.name,
                node.modifiers && node.modifiers.length ? ['|', join('|', node.modifiers)] : '',
                node.expression ? ['=', ...printJsExpression()] : '',
            ];
        case 'UseDirective':
            return ['use:', node.name, node.expression ? ['=', ...printJsExpression()] : ''];
        case 'AnimateDirective':
            return ['animate:', node.name, node.expression ? ['=', ...printJsExpression()] : ''];
        case 'HtmlTag':
            return ['{@html ', printJS(path, print, 'expression'), '}'];
        case 'RenderTag':
            return ['{@render ', printJS(path, print, 'expression'), '}'];
        case 'AttachTag':
            return ['{@attach ', printJS(path, print, 'expression'), '}'];
        case 'SpreadAttribute':
            return ['{...', printJS(path, print, 'expression'), '}'];
        case 'ConstTag':
            return ['{@const ', printJS(path, print, 'declaration'), '}'];
        case 'DeclarationTag':
            return ['{', printJS(path, print, 'declaration'), '}'];
    }
    console.error(JSON.stringify(node, null, 4));
    throw new Error('unknown node type: ' + node.type);
}
/** When reordering top-level parts, remove the leading comment above `<svelte:options>` and print it */
function stripSvelteOptionsComment(n) {
    const rootOptions = n.options;
    if (!rootOptions) {
        return undefined;
    }
    let leadingCommentDoc;
    const nodes = n.fragment.nodes;
    for (let idx = 0; idx < nodes.length; idx++) {
        const node = nodes[idx];
        if (node.type !== 'Comment' || isIgnoreEndDirective(node) || isIgnoreStartDirective(node)) {
            continue;
        }
        if (node.end === rootOptions.start) {
            leadingCommentDoc = printComment(node);
            nodes.splice(idx, 1);
            break;
        }
        else {
            let k = idx + 1;
            if (k < nodes.length &&
                isEmptyTextNode(nodes[k]) &&
                nodes[k].end === rootOptions.start) {
                leadingCommentDoc = printComment(node);
                nodes.splice(idx, 2);
                break;
            }
        }
    }
    return leadingCommentDoc;
}
function hoistedEndsDescending(n) {
    const out = [];
    if (n.options) {
        out.push({ kind: 'options', end: n.options.end });
    }
    if (n.module) {
        out.push({ kind: 'module', end: n.module.end });
    }
    if (n.instance) {
        out.push({ kind: 'instance', end: n.instance.end });
    }
    if (n.css) {
        out.push({ kind: 'css', end: n.css.end });
    }
    out.sort((a, b) => b.end - a.end);
    return out;
}
/**
 * Hoisted roots (`options`, `module`, `instance`, `css`) are printed outside `fragment.nodes`, but the
 * next sibling may be `<!-- #endregion -->`. With `svelteSortOrder`, that comment must stay below the
 * printed block. Peel optional whitespace-only text nodes + the first HTML comment after `hoistedEnd`
 * only when it matches `#endregion` and there is no non-whitespace in `originalText` between positions.
 */
function extractRegionEndTrailAfterHoistedEnd(nodes, hoistedEnd) {
    const idx = nodes.findIndex((child) => child.start >= hoistedEnd);
    if (idx === -1) {
        return;
    }
    let whitespace;
    for (let i = idx; i < Math.min(idx + 2, nodes.length); i++) {
        const child = nodes[i];
        if (child.type === 'Text' && isOnlyHtmlCollapseWhitespace(getUnencodedText(child))) {
            whitespace = child;
            continue;
        }
        else if (child.type === 'Comment' && /#\s*endregion\b/i.test(child.data)) {
            nodes.splice(idx, i + 1 - idx);
            return { whitespace, comment: child };
        }
        return;
    }
}
function printRegionEndTrailDoc(trail) {
    const pieces = [];
    if (trail.whitespace) {
        const doc = printWhitespace(getUnencodedText(trail.whitespace).replace(/^\r?\n/, ''));
        pieces.push(...(Array.isArray(doc) ? doc : [doc]));
    }
    pieces.push(printComment(trail.comment));
    return group([...pieces, hardline]);
}
function mergeAdjacentTextNodesInFragment(nodes) {
    for (let i = 0; i < nodes.length - 1;) {
        const current = nodes[i];
        const next = nodes[i + 1];
        if (current.type === 'Text' && next.type === 'Text') {
            // Trim right side so that something like
            //
            // <div>hello</div>
            // <script>...</script>
            // <div>world</div>
            //
            // doesn't become
            //
            // <div>hello</div>
            //
            // <div>world</div>
            trimTextNodeRight(current);
            current.raw += next.raw;
            current.data += next.data;
            current.end = next.end;
            nodes.splice(i + 1, 1);
        }
        else {
            i++;
        }
    }
}
function printSvelteOptions(path, parserOptions, print, rootOptions, leadingCommentDoc) {
    const bracketSameLine = isBracketSameLine(parserOptions);
    const optsNode = {
        type: 'Options',
        name: 'svelte:options',
        start: rootOptions.start,
        end: rootOptions.end,
        attributes: rootOptions.attributes,
    };
    let doc = group([
        [
            '<',
            optsNode.name,
            indent(group([
                ...path.call((optionsPath) => optionsPath.map(printWithPrependedAttributeLine(optsNode, parserOptions, print), 'attributes'), 'options'),
                bracketSameLine ? '' : dedent(line),
            ])),
            ...[bracketSameLine ? ' ' : '', '/>'],
        ],
        hardline,
    ]);
    if (leadingCommentDoc) {
        doc = group([leadingCommentDoc, hardline, doc]);
    }
    return doc;
}
function printTopLevelParts(n, options, path, print) {
    if (options.svelteSortOrder === 'none') {
        if (n.options) {
            const nodes = n.fragment.nodes;
            const has_options_node = nodes.some((node) => node.type === 'Options');
            if (!has_options_node) {
                nodes.push({
                    type: 'Options',
                    name: 'svelte:options',
                    start: n.options.start,
                    end: n.options.end,
                    attributes: n.options.attributes,
                });
                nodes.sort((a, b) => a.start - b.start);
            }
        }
        const topLevelPartsByEnd = {};
        const topLevelPartsByStart = {};
        if (n.module) {
            topLevelPartsByEnd[n.module.end] = n.module;
            topLevelPartsByStart[n.module.start] = n.module;
        }
        if (n.instance) {
            topLevelPartsByEnd[n.instance.end] = n.instance;
            topLevelPartsByStart[n.instance.start] = n.instance;
        }
        if (n.css) {
            topLevelPartsByEnd[n.css.end] = n.css;
            topLevelPartsByStart[n.css.start] = n.css;
        }
        const children = n.fragment.nodes;
        for (let i = 0; i < children.length; i++) {
            const node = children[i];
            if (topLevelPartsByEnd[node.start]) {
                children.splice(i, 0, topLevelPartsByEnd[node.start]);
                delete topLevelPartsByEnd[node.start];
            }
            else if (i === children.length - 1 && topLevelPartsByStart[node.end]) {
                children.push(topLevelPartsByStart[node.end]);
            }
        }
        mergeAdjacentTextNodesInFragment(children);
        const result = path.call(print, 'fragment');
        if (options.insertPragma && !hasPragma(options.originalText)) {
            return [`<!-- @format -->`, hardline, result];
        }
        else {
            return result;
        }
    }
    const parts = {
        options: [],
        scripts: [],
        markup: [],
        styles: [],
    };
    const regionEndTrail = {};
    for (const { kind, end } of hoistedEndsDescending(n)) {
        const trail = extractRegionEndTrailAfterHoistedEnd(n.fragment.nodes, end);
        if (trail) {
            regionEndTrail[kind] = trail;
        }
    }
    // scripts
    if (n.module) {
        let doc = path.call(print, 'module');
        const trail = regionEndTrail.module;
        if (trail) {
            doc = group([doc, printRegionEndTrailDoc(trail)]);
        }
        parts.scripts.push(doc);
    }
    if (n.instance) {
        let doc = path.call(print, 'instance');
        const trail = regionEndTrail.instance;
        if (trail) {
            doc = group([doc, printRegionEndTrailDoc(trail)]);
        }
        parts.scripts.push(doc);
    }
    // styles
    if (n.css) {
        let doc = path.call(print, 'css');
        const trail = regionEndTrail.css;
        if (trail) {
            doc = group([doc, printRegionEndTrailDoc(trail)]);
        }
        parts.styles.push(doc);
    }
    // markup
    if (n.options) {
        let doc = printSvelteOptions(path, options, print, n.options, stripSvelteOptionsComment(n));
        const trail = regionEndTrail.options;
        if (trail) {
            doc = group([doc, printRegionEndTrailDoc(trail)]);
        }
        parts.options.push(doc);
    }
    mergeAdjacentTextNodesInFragment(n.fragment.nodes);
    const htmlDoc = path.call(print, 'fragment');
    if (htmlDoc) {
        parts.markup.push(htmlDoc);
    }
    const docs = flatten(parseSortOrder(options.svelteSortOrder).map((p) => parts[p]));
    // Need to reset these because they are global and could affect the next formatting run
    ignoreNext = false;
    ignoreRange = false;
    // If this is invoked as an embed of markdown, remove the last hardline.
    // The markdown parser tries this, too, but fails because it does not
    // recurse into concats. Doing this will prevent an empty line
    // at the end of the embedded code block.
    if (options.parentParser === 'markdown') {
        const lastDoc = docs[docs.length - 1];
        trimRight([lastDoc], isLine);
    }
    if (options.insertPragma && !hasPragma(options.originalText)) {
        return [`<!-- @format -->`, hardline, group(docs)];
    }
    else {
        return group([join(hardline, docs)]);
    }
}
function printAttributeNodeValue(path, print, quotes, node) {
    const valueDocs = Array.isArray(node.value)
        ? path.map((childPath) => childPath.call(print), 'value')
        : [path.call(print, 'value')];
    if (!quotes || !formattableAttributes.includes(node.name)) {
        return valueDocs;
    }
    else {
        return indent(group(trim(valueDocs, isLine)));
    }
}
function printSvelteBlockChildren(path, print, options) {
    var _a;
    const fragment = path.node;
    const children = (_a = fragment === null || fragment === void 0 ? void 0 : fragment.nodes) !== null && _a !== void 0 ? _a : [];
    if (children.length === 0) {
        return '';
    }
    const whitespaceAtStartOfBlock = checkWhitespaceAtStartOfSvelteBlock(fragment, options);
    const whitespaceAtEndOfBlock = checkWhitespaceAtEndOfSvelteBlock(fragment, options);
    const startline = whitespaceAtStartOfBlock === 'none'
        ? ''
        : whitespaceAtEndOfBlock === 'line' || whitespaceAtStartOfBlock === 'line'
            ? hardline
            : line;
    const endline = whitespaceAtEndOfBlock === 'none'
        ? ''
        : whitespaceAtEndOfBlock === 'line' || whitespaceAtStartOfBlock === 'line'
            ? hardline
            : line;
    const firstChild = children[0];
    const lastChild = children[children.length - 1];
    if (isTextNodeStartingWithWhitespace(firstChild)) {
        trimTextNodeLeft(firstChild);
    }
    if (isTextNodeEndingWithWhitespace(lastChild)) {
        trimTextNodeRight(lastChild);
    }
    return [indent([startline, group(printChildren(path, print, options))]), endline];
}
function printBlockFragment(path, print, options, to) {
    return path.call((fragment_path) => printSvelteBlockChildren(fragment_path, print, options), to);
}
function printIfBlockAlternate(path, print, options) {
    const node = path.node;
    const alternate = node.alternate;
    if (!alternate) {
        return '';
    }
    if (alternate.type === 'Fragment') {
        if (alternate.nodes.length === 1 &&
            alternate.nodes[0].type === 'IfBlock' &&
            alternate.nodes[0].elseif) {
            const def = [
                '{:else if ',
                path.call((if_path) => printJS(if_path, print, 'test'), 'alternate', 'nodes', 0),
                '}',
                path.call((if_path) => printBlockFragment(if_path, print, options, 'consequent'), 'alternate', 'nodes', 0),
            ];
            if (alternate.nodes[0].alternate) {
                def.push(path.call((if_path) => printIfBlockAlternate(if_path, print, options), 'alternate', 'nodes', 0));
            }
            return def;
        }
        return ['{:else}', printBlockFragment(path, print, options, 'alternate')];
    }
    return ['{:else}', printBlockFragment(path, print, options, 'alternate')];
}
function printEachBlockFallback(path, print, options) {
    const node = path.node;
    const fallback = node.fallback;
    if (!fallback) {
        return '';
    }
    return ['{:else}', printBlockFragment(path, print, options, 'fallback')];
}
function printPre(originalText, path, print) {
    var _a;
    const result = [];
    const fragment = path.node;
    const children = (_a = fragment === null || fragment === void 0 ? void 0 : fragment.nodes) !== null && _a !== void 0 ? _a : [];
    if (children.length === 0) {
        return '';
    }
    const length = children.length;
    for (let i = 0; i < length; i++) {
        const child = children[i];
        if (child.type === 'Text') {
            const lines = originalText.substring(child.start, child.end).split(/\r?\n/);
            lines.forEach((line, j) => {
                if (j > 0)
                    result.push(literalline);
                result.push(line);
            });
        }
        else {
            result.push(path.call(print, 'nodes', i));
        }
    }
    return result;
}
function printChildren(path, print, options) {
    var _a;
    const current_value = path.node;
    if (isPreTagContent(path)) {
        return path.map(print, 'nodes');
    }
    const original_children = (_a = current_value.nodes) !== null && _a !== void 0 ? _a : [];
    const prepared_children = prepareChildren(original_children);
    if (prepared_children.length === 0) {
        return '';
    }
    const childDocs = [];
    let handleWhitespaceOfPrevTextNode = false;
    for (let i = 0; i < prepared_children.length; i++) {
        const childNode = prepared_children[i].node;
        if (childNode.type === 'Text') {
            handleTextChild(i, childNode);
        }
        else if (isBlockElement(childNode, options)) {
            handleBlockChild(i);
        }
        else if (isInlineElement(path, options, childNode)) {
            handleInlineChild(i);
        }
        else {
            childDocs.push(printChild(i));
            handleWhitespaceOfPrevTextNode = false;
        }
    }
    // If there's at least one block element and more than one node, break content
    const forceBreakContent = prepared_children.length > 1 &&
        prepared_children.some((child) => isBlockElement(child.node, options));
    if (forceBreakContent) {
        childDocs.push(breakParent);
    }
    return childDocs;
    function printChild(idx) {
        return path.call(print, 'nodes', prepared_children[idx].index);
    }
    /**
     * Print inline child. Hug whitespace of previous text child if there was one.
     */
    function handleInlineChild(idx) {
        if (handleWhitespaceOfPrevTextNode) {
            childDocs.push(group([line, printChild(idx)]));
        }
        else {
            childDocs.push(printChild(idx));
        }
        handleWhitespaceOfPrevTextNode = false;
    }
    /**
     * Print block element. Add softlines around it if needed
     * so it breaks into a separate line if children are broken up.
     * Don't add lines at the start/end if it's the first/last child because this
     * kind of whitespace handling is done in the parent already.
     */
    function handleBlockChild(idx) {
        var _a, _b;
        const prevChild = (_a = prepared_children[idx - 1]) === null || _a === void 0 ? void 0 : _a.node;
        if (prevChild &&
            !isBlockElement(prevChild, options) &&
            (prevChild.type !== 'Text' ||
                handleWhitespaceOfPrevTextNode ||
                !isTextNodeEndingWithWhitespace(prevChild))) {
            childDocs.push(softline);
        }
        childDocs.push(printChild(idx));
        const nextChild = (_b = prepared_children[idx + 1]) === null || _b === void 0 ? void 0 : _b.node;
        if (nextChild &&
            (nextChild.type !== 'Text' ||
                // Only handle text which starts with a whitespace and has text afterwards,
                // or is empty but followed by an inline element. The latter is done
                // so that if the children break, the inline element afterwards is in a separate line.
                ((!isEmptyTextNode(nextChild) ||
                    (prepared_children[idx + 2] &&
                        isInlineElement(path, options, prepared_children[idx + 2].node))) &&
                    !isTextNodeStartingWithLinebreak(nextChild)))) {
            childDocs.push(softline);
        }
        handleWhitespaceOfPrevTextNode = false;
    }
    /**
     * Print text child. First/last child white space handling
     * is done in parent already. By definition of the Svelte AST,
     * a text node always is inbetween other tags. Add hardlines
     * if the users wants to have them inbetween.
     * If the text is trimmed right, toggle flag telling
     * subsequent (inline)block element to alter its printing logic
     * to check if they need to hug or print lines themselves.
     */
    function handleTextChild(idx, childNode) {
        handleWhitespaceOfPrevTextNode = false;
        if (idx === 0 || idx === prepared_children.length - 1) {
            childDocs.push(printChild(idx));
            return;
        }
        const prevNode = prepared_children[idx - 1].node;
        const nextNode = prepared_children[idx + 1].node;
        if (isTextNodeStartingWithWhitespace(childNode) &&
            // If node is empty, go straight through to checking the right end
            !isEmptyTextNode(childNode)) {
            if (isInlineElement(path, options, prevNode) &&
                !isTextNodeStartingWithLinebreak(childNode)) {
                trimTextNodeLeft(childNode);
                const lastChildDoc = childDocs.pop();
                childDocs.push(group([lastChildDoc, line]));
            }
            if (isBlockElement(prevNode, options) && !isTextNodeStartingWithLinebreak(childNode)) {
                trimTextNodeLeft(childNode);
            }
        }
        if (isTextNodeEndingWithWhitespace(childNode)) {
            if (isInlineElement(path, options, nextNode) &&
                !isTextNodeEndingWithLinebreak(childNode)) {
                handleWhitespaceOfPrevTextNode = !prevNode || !isBlockElement(prevNode, options);
                trimTextNodeRight(childNode);
            }
            if (isBlockElement(nextNode, options) && !isTextNodeEndingWithLinebreak(childNode, 2)) {
                handleWhitespaceOfPrevTextNode = !prevNode || !isBlockElement(prevNode, options);
                trimTextNodeRight(childNode);
            }
        }
        childDocs.push(printChild(idx));
    }
}
function prepareChildren(children, path) {
    const prepared = [];
    for (let idx = 0; idx < children.length; idx++) {
        const currentChild = children[idx];
        if (currentChild.type === 'Text' && getUnencodedText(currentChild) === '') {
            continue;
        }
        prepared.push({ node: currentChild, index: idx });
    }
    return prepared;
}
/**
 * Split the text into words separated by whitespace. Replace the whitespaces by lines,
 * collapsing multiple whitespaces into a single line.
 *
 * If the text starts or ends with multiple newlines, two of those should be kept.
 */
function splitTextToDocs(node) {
    const text = getUnencodedText(node);
    const lines = text.split(/[\t\n\f\r ]+/);
    let docs = join(line, lines).filter((doc) => doc !== '');
    if (startsWithLinebreak(text)) {
        docs[0] = hardline;
    }
    if (startsWithLinebreak(text, 2)) {
        docs = [hardline, ...docs];
    }
    if (endsWithLinebreak(text)) {
        docs[docs.length - 1] = hardline;
    }
    if (endsWithLinebreak(text, 2)) {
        docs = [...docs, hardline];
    }
    return docs;
}
function printJS(path, print, name) {
    return path.call(print, name);
}
function expandNode(node, original) {
    let str = _expandNode(node, original);
    if (node === null || node === void 0 ? void 0 : node.typeAnnotation) {
        str +=
            ': ' +
                original.slice(node.typeAnnotation.typeAnnotation.start, node.typeAnnotation.typeAnnotation.end);
    }
    return str;
}
function _expandNode(node, original, parent) {
    var _a, _b;
    if (node === null) {
        return '';
    }
    if (typeof node === 'string') {
        // pre-v3.20 AST
        return ' ' + node;
    }
    switch (node.type) {
        case 'ArrayExpression':
        case 'ArrayPattern':
            return (' [' +
                node.elements
                    // handle null specifically here; else it would become the empty string, but that would mean
                    // fewer elements in the array, which would change the meaning of the array
                    .map((el) => (el === null ? ' ' : _expandNode(el, original)))
                    .join(',')
                    .slice(1) +
                ']');
        case 'AssignmentPattern':
            return _expandNode(node.left, original) + ' =' + _expandNode(node.right, original);
        case 'Identifier':
            return ' ' + node.name;
        case 'Literal':
            return ' ' + node.raw;
        case 'ObjectExpression':
            return (' {' +
                node.properties.map((p) => _expandNode(p, original, node)).join(',') +
                ' }');
        case 'ObjectPattern':
            return (' {' + node.properties.map((p) => _expandNode(p, original)).join(',') + ' }');
        case 'Property': {
            let computedKeyInner = '';
            if (node.computed) {
                computedKeyInner =
                    typeof ((_a = node.key) === null || _a === void 0 ? void 0 : _a.start) === 'number' && typeof ((_b = node.key) === null || _b === void 0 ? void 0 : _b.end) === 'number'
                        ? original.slice(node.key.start, node.key.end)
                        : _expandNode(node.key, original).trim();
            }
            if (node.value.type === 'ObjectPattern' || node.value.type === 'ArrayPattern') {
                const keyStr = node.computed ? ' [' + computedKeyInner + ']' : ' ' + node.key.name;
                return keyStr + ':' + _expandNode(node.value, original);
            }
            else if ((node.value.type === 'Identifier' && node.key.name !== node.value.name) ||
                (parent && parent.type === 'ObjectExpression')) {
                const keyStr = node.computed
                    ? ' [' + computedKeyInner + ']'
                    : _expandNode(node.key, original);
                return keyStr + ':' + _expandNode(node.value, original);
            }
            else {
                return _expandNode(node.value, original);
            }
        }
        case 'RestElement':
            // argument may be a nested Array/ObjectPattern, not only an Identifier
            return ' ...' + _expandNode(node.argument, original).slice(1);
    }
    console.error(JSON.stringify(node, null, 4));
    throw new Error('unknown node type: ' + node.type);
}
function printComment(node) {
    let text = node.data;
    if (hasSnippedContent(text)) {
        text = unsnipContent(text);
    }
    return group(['<!--', text, '-->']);
}
function printWhitespace(text) {
    const hasWhiteSpace = text.length > 0;
    const hasOneOrMoreNewlines = /\n/.test(text);
    const hasTwoOrMoreNewlines = /\n\r?[\t\n\f\r ]*\n\r?/.test(text);
    if (hasTwoOrMoreNewlines) {
        return [hardline, hardline];
    }
    if (hasOneOrMoreNewlines) {
        return hardline;
    }
    if (hasWhiteSpace) {
        return line;
    }
    return '';
}

function getText(node, options, unsnip = false) {
    const leadingComments = node.leadingComments;
    const text = options.originalText.slice(options.locStart(
    // if there are comments before the node they are not included
    // in the `start` of the node itself
    (leadingComments && leadingComments[0]) || node), options.locEnd(node));
    if (!unsnip || !hasSnippedContent(text)) {
        return text;
    }
    return unsnipContent(text);
}

const { builders: { group: group$1, hardline: hardline$1, softline: softline$1, indent: indent$1, dedent: dedent$1, literalline: literalline$1 }, utils: { removeLines }, } = doc;
const leaveAlone = new Set([
    'Script',
    'StyleSheet',
    'Identifier',
    'MemberExpression',
    'CallExpression',
    'ArrowFunctionExpression',
]);
const dontTraverse = new Set(['start', 'end', 'type']);
function getVisitorKeys(node, nonTraversableKeys) {
    return Object.keys(node).filter((key) => {
        return !nonTraversableKeys.has(key) && !leaveAlone.has(node.type) && !dontTraverse.has(key);
    });
}
// Embed works like this in Prettier v3:
// - do depth first traversal of all node properties
// - deepest property is calling embed first
// - if embed returns a function, it will be called after the traversal in a second pass, in the same order (deepest first)
// For performance reasons we try to only return functions when we're sure we need to transform something.
function embed(path, _options) {
    var _a, _b, _c, _d, _e, _f, _g;
    const node = path.getNode();
    const options = _options;
    if (!options.locStart || !options.locEnd || !options.originalText) {
        throw new Error('Missing required options');
    }
    if (isASTNode(node)) {
        assignCommentsToNodes(node);
        attachAttributeComments(node, options.originalText);
        return null;
    }
    // embed does depth first traversal with deepest node called first, therefore we need to
    // check the parent to see if we are inside an expression that should be embedded.
    const parent = path.getParentNode();
    const printJsExpression = () => parent.expression ? printJS$1(parent, 'expression', {}) : undefined;
    const printSvelteBlockJS = (name) => printJS$1(parent, name, { forceSingleLine: true });
    switch (parent.type) {
        case 'IfBlock':
            printSvelteBlockJS('test');
            break;
        case 'AwaitBlock':
        case 'KeyBlock':
            printSvelteBlockJS('expression');
            break;
        case 'EachBlock':
            printSvelteBlockJS('expression');
            printSvelteBlockJS('key');
            break;
        case 'SnippetBlock':
            // We merge the two parts into one expression to then treat it like a function
            if (node === parent.expression) {
                parent.expression.end =
                    options.originalText.indexOf(')', (_g = (_d = (_c = (_b = (_a = parent.parameters) === null || _a === void 0 ? void 0 : _a[parent.parameters.length - 1]) === null || _b === void 0 ? void 0 : _b.typeAnnotation) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : (_f = (_e = parent.parameters) === null || _e === void 0 ? void 0 : _e[parent.parameters.length - 1]) === null || _f === void 0 ? void 0 : _f.end) !== null && _g !== void 0 ? _g : parent.expression.end) + 1;
                parent.parameters = null;
                node.isJS = true;
                node.asFunction = true;
            }
            break;
        case 'RegularElement':
        case 'SvelteElement':
            printJS$1(parent, 'tag', {});
            break;
        case 'ExpressionTag':
            printJS$1(parent, 'expression', {
                forceSingleQuote: isInsideQuotedAttribute(path),
            });
            break;
        case 'HtmlTag':
            printJS$1(parent, 'expression', {});
            break;
        case 'SpreadAttribute':
            printJS$1(parent, 'expression', {});
            break;
        case 'AttachTag':
            printJS$1(parent, 'expression', {});
            break;
        case 'VariableDeclarator': {
            const declaration = path.getParentNode(1);
            const constTag = path.getParentNode(2);
            if ((declaration === null || declaration === void 0 ? void 0 : declaration.type) === 'VariableDeclaration' && (constTag === null || constTag === void 0 ? void 0 : constTag.type) === 'ConstTag') {
                constTag.declaration = parent;
                printJS$1(constTag, 'declaration', { removeParentheses: true });
            }
            break;
        }
        case 'BindDirective':
            printJS$1(parent, 'expression', {
                removeParentheses: parent.expression.type === 'SequenceExpression',
                surroundWithSoftline: true,
            });
            break;
        case 'RenderTag':
            if (node === parent.expression) {
                printJS$1(parent, 'expression', {});
            }
            break;
        case 'DeclarationTag':
            if (node === parent.declaration) {
                printJS$1(parent, 'declaration', { asStatement: true });
            }
            break;
        case 'OnDirective':
        case 'BindDirective':
        case 'ClassDirective':
        case 'LetDirective':
        case 'TransitionDirective':
        case 'UseDirective':
        case 'AnimateDirective':
        case 'SvelteComponent':
            printJsExpression();
            break;
    }
    if (node.isJS) {
        return (textToDoc) => __awaiter(this, void 0, void 0, function* () {
            try {
                const embeddedOptions = {
                    // Prettier only allows string references as parsers from v3 onwards,
                    // so we need to have another public parser and defer to that
                    parser: node.asStatement
                        ? options._svelte_ts
                            ? 'svelteTSStatementParser'
                            : 'svelteStatementParser'
                        : options._svelte_ts
                            ? 'svelteTSExpressionParser'
                            : 'svelteExpressionParser',
                    singleQuote: node.forceSingleQuote ? true : options.singleQuote,
                    _svelte_asFunction: node.asFunction,
                };
                // If we have snipped content, it was done wrongly and we need to unsnip it.
                // This happens for example for {@html `<script>{foo}</script>`}
                const text = getText(node, options, true);
                let docs = yield textToDoc(node.asStatement
                    ? text
                    : node.asFunction
                        ? forceIntoFunction(text)
                        : forceIntoExpression(text), embeddedOptions);
                if (node.asStatement) {
                    trimRight([docs], (d) => d === ';');
                }
                if (node.forceSingleLine) {
                    docs = removeLines(docs);
                }
                if (node.removeParentheses) {
                    docs = removeParentheses(docs);
                }
                if (node.asFunction) {
                    if (Array.isArray(docs) && typeof docs[0] === 'string') {
                        docs[0] = docs[0].replace('function ', '');
                        docs.splice(-1, 1);
                    }
                    else {
                        throw new Error('Prettier AST changed, asFunction logic needs to change');
                    }
                }
                if (node.surroundWithSoftline) {
                    docs = group$1(indent$1([softline$1, group$1(docs), dedent$1(softline$1)]));
                }
                return docs;
            }
            catch (e) {
                return getText(node, options, true);
            }
        });
    }
    const embedType = (tag, parser, isTopLevel) => {
        return (textToDoc, print) => __awaiter(this, void 0, void 0, function* () {
            return embedTag(tag, options.originalText, path, (content) => formatBodyContent(content, parser, textToDoc, options), print, isTopLevel, options);
        });
    };
    const embedScript = (isTopLevel) => embedType('script', 
    // Use babel-ts as fallback because the absence does not mean the content is not TS,
    // the user could have set the default language. babel-ts will format things a little
    // bit different though, especially preserving parentheses around dot notation which
    // fixes https://github.com/sveltejs/prettier-plugin-svelte/issues/218
    isTypeScript(node) ? 'typescript' : isJSON(node) ? 'json' : 'babel-ts', isTopLevel);
    const embedStyle = (isTopLevel) => embedType('style', isLess(node) ? 'less' : isScss(node) ? 'scss' : 'css', isTopLevel);
    const embedPug = () => embedType('template', 'pug', false);
    switch (node.type) {
        case 'Script':
            return embedScript(true);
        case 'StyleSheet':
            return embedStyle(true);
        case 'RegularElement': {
            if (node.name === 'script') {
                return embedScript(false);
            }
            else if (node.name === 'style') {
                return embedStyle(false);
            }
            else if (isPugTemplate(node)) {
                return embedPug();
            }
        }
    }
    return null;
}
function forceIntoExpression(statement) {
    // note the trailing newline: if the statement ends in a // comment,
    // we can't add the closing bracket right afterwards
    return `(${statement}\n)`;
}
function forceIntoFunction(statement) {
    return `function ${statement} {}`;
}
function preformattedBody(str) {
    if (!str) {
        return '';
    }
    const firstNewline = /^[\t\f\r ]*\n/;
    const lastNewline = /\n[\t\f\r ]*$/;
    // If we do not start with a new line prettier might try to break the opening tag
    // to keep it together with the string. Use a literal line to skip indentation.
    return [literalline$1, str.replace(firstNewline, '').replace(lastNewline, ''), hardline$1];
}
function getSnippedContent(node) {
    const encodedContent = getAttributeTextValue(snippedTagContentAttribute, node);
    if (encodedContent) {
        return base64ToString(encodedContent);
    }
    else {
        return '';
    }
}
function formatBodyContent(content, parser, textToDoc, options) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const body = yield textToDoc(content, { parser });
            if (parser === 'pug' && typeof body === 'string') {
                // Pug returns no docs but a final string.
                // Therefore prepend the line offsets
                const whitespace = options.useTabs
                    ? '\t'
                    : ' '.repeat(options.pugTabWidth && options.pugTabWidth > 0
                        ? options.pugTabWidth
                        : options.tabWidth);
                const pugBody = body
                    .split('\n')
                    .map((line) => (line ? whitespace + line : line))
                    .join('\n');
                return [hardline$1, pugBody];
            }
            const indentIfDesired = (doc) => options.svelteIndentScriptAndStyle ? indent$1(doc) : doc;
            trimRight([body], isLine);
            return [indentIfDesired([hardline$1, body]), hardline$1];
        }
        catch (error) {
            if (process.env.PRETTIER_DEBUG) {
                throw error;
            }
            // We will wind up here if there is a syntax error in the embedded code. If we throw an error,
            // prettier will try to print the node with the printer. That will fail with a hard-to-interpret
            // error message (e.g. "Unsupported node type", referring to `<script>`).
            // Therefore, fall back on just returning the unformatted text.
            console.error(error);
            return preformattedBody(content);
        }
    });
}
function embedTag(tag, text, path, formatBodyContent, print, isTopLevel, options) {
    var _a, _b;
    return __awaiter(this, void 0, void 0, function* () {
        const node = path.getNode();
        const content = tag === 'template' ? printRaw(node, text) : getSnippedContent(node);
        const previousComments = node.type === 'Script' || node.type === 'StyleSheet'
            ? ((_a = node.comments) !== null && _a !== void 0 ? _a : [])
            : [getLeadingComment(path)]
                .filter(Boolean)
                .map((comment) => ({ comment: comment, emptyLineAfter: false }));
        const canFormat = isNodeSupportedLanguage(node) &&
            !isIgnoreDirective((_b = previousComments[previousComments.length - 1]) === null || _b === void 0 ? void 0 : _b.comment) &&
            (tag !== 'template' ||
                options.plugins.some((plugin) => typeof plugin !== 'string' &&
                    !(plugin instanceof URL) &&
                    // @ts-expect-error Prettier's type definitions don't include name anymore for some reason
                    plugin.name === 'prettier-plugin-svelte' &&
                    plugin.parsers &&
                    plugin.parsers.pug));
        const body = canFormat
            ? content.trim() !== ''
                ? yield formatBodyContent(content)
                : content === ''
                    ? ''
                    : hardline$1
            : preformattedBody(content);
        const openingTag = group$1([
            '<',
            tag,
            indent$1(group$1([
                ...path.map(printWithPrependedAttributeLine(node, options, print), 'attributes'),
                isBracketSameLine(options) ? '' : dedent$1(softline$1),
            ])),
            '>',
        ]);
        let result = group$1([openingTag, body, '</', tag, '>']);
        const comments = [];
        for (const comment of previousComments) {
            comments.push('<!--', comment.comment.data, '-->');
            comments.push(hardline$1);
            if (comment.emptyLineAfter) {
                comments.push(hardline$1);
            }
        }
        if (isTopLevel && options.svelteSortOrder !== 'none') {
            // top level embedded nodes have been moved from their normal position in the
            // node tree. if there is a comment referring to it, it must be recreated at
            // the new position.
            return [...comments, result, hardline$1];
        }
        else {
            // Only comments at the top level get the special "move comment" treatment.
            return isTopLevel && comments.length ? [...comments, result] : result;
        }
    });
}
function printJS$1(node, name, options) {
    const part = node[name];
    if (!part || typeof part !== 'object') {
        return;
    }
    part.isJS = true;
    part.forceSingleQuote = options.forceSingleQuote;
    part.forceSingleLine = options.forceSingleLine;
    part.removeParentheses = options.removeParentheses;
    part.surroundWithSoftline = options.surroundWithSoftline;
    part.asStatement = options.asStatement;
}
/**
 * Walk the AST and use `_comments` (stashed by the parser) to attach
 * attribute-level comments to their neighbouring attribute nodes via
 * Prettier's `util.addLeadingComment` / `util.addTrailingComment`.
 */
function attachAttributeComments(ast, original_text) {
    const comments = ast._comments;
    if (!comments || comments.length === 0)
        return;
    // Index comments by start position for fast lookup
    const commentsByStart = new Map();
    for (const c of comments) {
        commentsByStart.set(c.start, c);
    }
    walkAndAttach(ast.fragment, commentsByStart, original_text);
}
function walkAndAttach(node, commentsByStart, original_text) {
    var _a;
    if (!node || typeof node !== 'object')
        return;
    if ('attributes' in node && Array.isArray(node.attributes) && node.attributes.length > 0) {
        const attrs = node.attributes;
        // Check gap before first attribute (between tag name and first attr)
        const tagNameEnd = node.start + 2;
        attachCommentsInRange(tagNameEnd, attrs[0].start, null, attrs[0], commentsByStart);
        // Check gaps between consecutive attributes
        for (let i = 0; i < attrs.length - 1; i++) {
            attachCommentsInRange(attrs[i].end, attrs[i + 1].start, attrs[i], attrs[i + 1], commentsByStart);
        }
        const last_attr = attrs[attrs.length - 1];
        const opening_tag_end = findOpeningTagEnd(original_text, last_attr.end, node.end, commentsByStart);
        if (opening_tag_end >= 0) {
            attachCommentsInRange(last_attr.end, opening_tag_end, last_attr, null, commentsByStart);
        }
    }
    else if ('attributes' in node &&
        Array.isArray(node.attributes) &&
        typeof node.name === 'string') {
        // No attributes: comments between the tag name and `>` have nothing to attach to,
        // so keep them on the element itself and let the element printer print them.
        // Start after `this={...}` of <svelte:element>/<svelte:component>, whose comments
        // are printed along with that expression.
        const this_expression = (_a = node.tag) !== null && _a !== void 0 ? _a : node.expression;
        const tag_name_end = Math.max(node.start + 1 + node.name.length, typeof (this_expression === null || this_expression === void 0 ? void 0 : this_expression.end) === 'number' ? this_expression.end : 0);
        const opening_tag_end = findOpeningTagEnd(original_text, tag_name_end, node.end, commentsByStart);
        if (opening_tag_end >= 0) {
            for (const [start, comment] of commentsByStart) {
                if (start >= tag_name_end && comment.end <= opening_tag_end) {
                    util.addDanglingComment(node, comment, undefined);
                    commentsByStart.delete(start);
                }
            }
        }
    }
    // Recurse into children and block branches
    // Some of these have multiple fragment nodes so we need to recurse them separately
    if (node.type === 'IfBlock') {
        if (node.consequent) {
            walkAndAttach(node.consequent, commentsByStart, original_text);
        }
        if (node.alternate) {
            walkAndAttach(node.alternate, commentsByStart, original_text);
        }
    }
    else if (node.type === 'EachBlock') {
        if (node.body) {
            walkAndAttach(node.body, commentsByStart, original_text);
        }
        if (node.fallback) {
            walkAndAttach(node.fallback, commentsByStart, original_text);
        }
    }
    else if (node.type === 'AwaitBlock') {
        if (node.pending)
            walkAndAttach(node.pending, commentsByStart, original_text);
        if (node.then)
            walkAndAttach(node.then, commentsByStart, original_text);
        if (node.catch)
            walkAndAttach(node.catch, commentsByStart, original_text);
    }
    else {
        for (const child of getChildren(node)) {
            walkAndAttach(child, commentsByStart, original_text);
        }
    }
}
function attachCommentsInRange(rangeStart, rangeEnd, precedingAttr, followingAttr, commentsByStart) {
    for (const [start, comment] of commentsByStart) {
        if (start >= rangeStart && comment.end <= rangeEnd) {
            if (followingAttr) {
                util.addLeadingComment(followingAttr, comment);
            }
            else if (precedingAttr) {
                util.addTrailingComment(precedingAttr, comment);
            }
            commentsByStart.delete(start);
        }
    }
}
/**
 * Returns the position of the `>` that ends an opening tag, starting the search at `from`
 * (which must be past the last attribute). Skips over comments, so that a `>` inside a
 * comment isn't mistaken for the end of the tag. Returns -1 if not found.
 */
function findOpeningTagEnd(original_text, from, limit, commentsByStart) {
    if (!original_text || typeof limit !== 'number')
        return -1;
    let pos = from;
    while (pos < limit) {
        const comment = commentsByStart.get(pos);
        if (comment) {
            pos = comment.end;
        }
        else if (original_text[pos] === '>') {
            return pos;
        }
        else {
            pos++;
        }
    }
    return -1;
}

const babelParser = parsers$1.babel;
const typescriptParser = parsers$1['babel-ts']; // TODO use TypeScript parser in next major?
function locStart(node) {
    return node.start;
}
function locEnd(node) {
    return node.end;
}
const languages = [
    {
        name: 'svelte',
        parsers: ['svelte'],
        extensions: ['.svelte'],
        vscodeLanguageIds: ['svelte'],
    },
];
const parsers = {
    svelte: {
        hasPragma,
        parse: (text, options) => __awaiter(void 0, void 0, void 0, function* () {
            try {
                let _parse = parse;
                if (options.svelte5CompilerPath) {
                    try {
                        _parse = (yield import(options.svelte5CompilerPath)).parse;
                    }
                    catch (e) {
                        console.warn(`Failed to load Svelte 5 compiler from ${options.svelte5CompilerPath}`);
                        console.warn(e);
                        options.svelte5CompilerPath = undefined;
                    }
                }
                const root = _parse(text, { modern: true });
                root.__isRoot = true;
                // Prettier does a sanity check on ast.comments after printing
                // to verify all comments were printed. Since the comments array
                // includes script/style comments already handled by embedded
                // parsers, we stash the full array on _comments and remove
                // comments so Prettier doesn't try to process them itself.
                // We then manually attach attribute comments in embed().
                root._comments = root.comments;
                delete root.comments;
                return root;
            }
            catch (err) {
                if (err.start != null && err.end != null) {
                    // Prettier expects error objects to have loc.start and loc.end fields.
                    // Svelte uses start and end directly on the error.
                    err.loc = {
                        start: err.start,
                        end: err.end,
                    };
                }
                throw err;
            }
        }),
        preprocess: (text, options) => {
            const result = snipScriptAndStyleTagContent(text);
            text = result.text.trim();
            // Prettier sets the preprocessed text as the originalText in case
            // the Svelte formatter is called directly. In case it's called
            // as an embedded parser (for example when there's a Svelte code block
            // inside markdown), the originalText is not updated after preprocessing.
            // Therefore we do it ourselves here.
            options.originalText = text;
            options._svelte_ts = result.isTypescript;
            return text;
        },
        locStart,
        locEnd,
        astFormat: 'svelte-ast',
    },
    svelteExpressionParser: Object.assign(Object.assign({}, babelParser), { parse: (text, options) => {
            const ast = babelParser.parse(text, options);
            let program = ast.program.body[0];
            if (!options._svelte_asFunction) {
                program = program.expression;
            }
            return Object.assign(Object.assign({}, ast), { program });
        } }),
    svelteStatementParser: Object.assign(Object.assign({}, babelParser), { parse: (text, options) => {
            const ast = babelParser.parse(text, options);
            return Object.assign(Object.assign({}, ast), { program: ast.program.body[0] });
        } }),
    svelteTSExpressionParser: Object.assign(Object.assign({}, typescriptParser), { parse: (text, options) => {
            const ast = typescriptParser.parse(text, options);
            let program = ast.program.body[0];
            if (!options._svelte_asFunction) {
                program = program.expression;
            }
            return Object.assign(Object.assign({}, ast), { program });
        } }),
    svelteTSStatementParser: Object.assign(Object.assign({}, typescriptParser), { parse: (text, options) => {
            const ast = typescriptParser.parse(text, options);
            return Object.assign(Object.assign({}, ast), { program: ast.program.body[0] });
        } }),
};
const printers = {
    'svelte-ast': {
        print,
        embed,
        getVisitorKeys,
        isBlockComment(comment) {
            return comment.type === 'Block';
        },
        printComment(commentPath) {
            const comment = commentPath.getValue();
            if (comment.type === 'Line') {
                return '//' + comment.value.replace(/\r$/, '');
            }
            return '/*' + comment.value + '*/';
        },
    },
};

export { languages, options, parsers, printers };