Brunobkr/llama.cpp_AlgMor24_github
ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.
03.1k
1'use strict';2 3Object.defineProperty(exports, '__esModule', { value: true });4 5var prettierPluginBabel = require('prettier/plugins/babel');6var prettier = require('prettier');7var compiler = require('svelte/compiler');8 9function _interopNamespace(e) {10 if (e && e.__esModule) return e;11 var n = Object.create(null);12 if (e) {13 Object.keys(e).forEach(function (k) {14 if (k !== 'default') {15 var d = Object.getOwnPropertyDescriptor(e, k);16 Object.defineProperty(n, k, d.get ? d : {17 enumerable: true,18 get: function () {19 return e[k];20 }21 });22 }23 });24 }25 n['default'] = e;26 return Object.freeze(n);27}28 29/******************************************************************************30Copyright (c) Microsoft Corporation.31 32Permission to use, copy, modify, and/or distribute this software for any33purpose with or without fee is hereby granted.34 35THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH36REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY37AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,38INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM39LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR40OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR41PERFORMANCE OF THIS SOFTWARE.42***************************************************************************** */43 44function __awaiter(thisArg, _arguments, P, generator) {45 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }46 return new (P || (P = Promise))(function (resolve, reject) {47 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }48 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }49 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }50 step((generator = generator.apply(thisArg, _arguments || [])).next());51 });52}53 54var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {55 var e = new Error(message);56 return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;57};58 59// @see http://xahlee.info/js/html5_non-closing_tag.html60const selfClosingTags = [61 'area',62 'base',63 'br',64 'col',65 'embed',66 'hr',67 'img',68 'input',69 'link',70 'meta',71 'param',72 'source',73 'track',74 'wbr',75];76// https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements#Elements77const blockElements = [78 'address',79 'article',80 'aside',81 'blockquote',82 'details',83 'dialog',84 'dd',85 'div',86 'dl',87 'dt',88 'fieldset',89 'figcaption',90 'figure',91 'footer',92 'form',93 'h1',94 'h2',95 'h3',96 'h4',97 'h5',98 'h6',99 'header',100 'hgroup',101 'hr',102 'li',103 'main',104 'nav',105 'ol',106 'p',107 'pre',108 'section',109 'table',110 'ul',111];112/**113 * HTML attributes that we may safely reformat (trim whitespace, add or remove newlines)114 */115const formattableAttributes = [116// None at the moment117// Prettier HTML does not format attributes at all118// and to be consistent we leave this array empty for now119];120 121// Base64 string encoding and decoding module.122// Uses Buffer for Node.js and btoa/atob for browser environments.123// We use TextEncoder/TextDecoder for browser environments because124// they can handle non-ASCII characters, unlike btoa/atob.125const stringToBase64 = typeof Buffer !== 'undefined'126 ? (str) => Buffer.from(str).toString('base64')127 : (str) => btoa(new TextEncoder()128 .encode(str)129 .reduce((acc, byte) => acc + String.fromCharCode(byte), ''));130const base64ToString = typeof Buffer !== 'undefined'131 ? (str) => Buffer.from(str, 'base64').toString()132 : (str) => new TextDecoder().decode(Uint8Array.from(atob(str), (c) => c.charCodeAt(0)));133 134const snippedTagContentAttribute = '✂prettier:content✂';135const scriptRegex = /<!--[^]*?-->|<script((?:\s+[^=>'"\/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"\/\s]+)*\s*)>([^]*?)<\/script>/g;136const styleRegex = /<!--[^]*?-->|<style((?:\s+[^=>'"\/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"\/\s]+)*\s*)>([^]*?)<\/style>/g;137const langTsRegex = /\slang=["']?ts["']?/;138function snipScriptAndStyleTagContent(source) {139 let scriptMatchSpans = getMatchIndexes('script');140 let styleMatchSpans = getMatchIndexes('style');141 let isTypescript = false;142 const text = snipTagContent(snipTagContent(source, 'script', '{}', styleMatchSpans), 'style', '', scriptMatchSpans);143 return { text, isTypescript };144 function getMatchIndexes(tagName) {145 const regex = getRegexp(tagName);146 const indexes = [];147 let match = null;148 while ((match = regex.exec(source)) != null) {149 if (source.slice(match.index, match.index + 4) !== '<!--') {150 indexes.push([match.index, regex.lastIndex]);151 }152 }153 return indexes;154 }155 function snipTagContent(_source, tagName, placeholder, otherSpans) {156 const regex = getRegexp(tagName);157 let newScriptMatchSpans = scriptMatchSpans;158 let newStyleMatchSpans = styleMatchSpans;159 // Replace valid matches160 const newSource = _source.replace(regex, (match, attributes, content, index) => {161 if (match.startsWith('<!--') || withinOtherSpan(index)) {162 return match;163 }164 if (langTsRegex.test(attributes)) {165 isTypescript = true;166 }167 const encodedContent = stringToBase64(content);168 const newContent = `<${tagName}${attributes} ${snippedTagContentAttribute}="${encodedContent}">${placeholder}</${tagName}>`;169 // Adjust the spans because the source now has a different content length170 const lengthDiff = match.length - newContent.length;171 newScriptMatchSpans = adjustSpans(scriptMatchSpans, newScriptMatchSpans);172 newStyleMatchSpans = adjustSpans(styleMatchSpans, newStyleMatchSpans);173 function adjustSpans(oldSpans, newSpans) {174 return oldSpans.map((oldSpan, idx) => {175 const newSpan = newSpans[idx];176 // Do the check using the old spans because the replace function works177 // on the old spans. Replace oldSpans with newSpans afterwards.178 if (oldSpan[0] > index) {179 // span is after the match -> adjust start and end180 return [newSpan[0] - lengthDiff, newSpan[1] - lengthDiff];181 }182 else if (oldSpan[0] === index) {183 // span is the match -> adjust end only184 return [newSpan[0], newSpan[1] - lengthDiff];185 }186 else {187 // span is before the match -> nothing to adjust188 return newSpan;189 }190 });191 }192 return newContent;193 });194 // Now that the replacement function ran, we can adjust the spans for the next run195 scriptMatchSpans = newScriptMatchSpans;196 styleMatchSpans = newStyleMatchSpans;197 return newSource;198 function withinOtherSpan(idx) {199 return otherSpans.some((otherSpan) => idx > otherSpan[0] && idx < otherSpan[1]);200 }201 }202 function getRegexp(tagName) {203 return tagName === 'script' ? scriptRegex : styleRegex;204 }205}206function hasSnippedContent(text) {207 return text.includes(snippedTagContentAttribute);208}209const regex = /(<\w+.*?)\s*✂prettier:content✂="(.*?)">.*?(?=<\/)/gi;210function unsnipContent(text) {211 return text.replace(regex, (_, start, encodedContent) => {212 const content = base64ToString(encodedContent);213 return `${start}>${content}`;214 });215}216 217function makeChoice(choice) {218 return { value: choice, description: choice };219}220const options = {221 svelte5CompilerPath: {222 category: 'Svelte',223 type: 'string',224 default: '',225 description: "Path to the Svelte compiler. You normally don't need to set this.",226 },227 svelteSortOrder: {228 category: 'Svelte',229 type: 'choice',230 default: 'options-scripts-markup-styles',231 description: 'Sort order for scripts, markup, and styles',232 choices: [233 makeChoice('options-scripts-markup-styles'),234 makeChoice('options-scripts-styles-markup'),235 makeChoice('options-markup-styles-scripts'),236 makeChoice('options-markup-scripts-styles'),237 makeChoice('options-styles-markup-scripts'),238 makeChoice('options-styles-scripts-markup'),239 makeChoice('scripts-options-markup-styles'),240 makeChoice('scripts-options-styles-markup'),241 makeChoice('markup-options-styles-scripts'),242 makeChoice('markup-options-scripts-styles'),243 makeChoice('styles-options-markup-scripts'),244 makeChoice('styles-options-scripts-markup'),245 makeChoice('scripts-markup-options-styles'),246 makeChoice('scripts-styles-options-markup'),247 makeChoice('markup-styles-options-scripts'),248 makeChoice('markup-scripts-options-styles'),249 makeChoice('styles-markup-options-scripts'),250 makeChoice('styles-scripts-options-markup'),251 makeChoice('scripts-markup-styles-options'),252 makeChoice('scripts-styles-markup-options'),253 makeChoice('markup-styles-scripts-options'),254 makeChoice('markup-scripts-styles-options'),255 makeChoice('styles-markup-scripts-options'),256 makeChoice('styles-scripts-markup-options'),257 makeChoice('none'),258 ],259 },260 svelteAllowShorthand: {261 category: 'Svelte',262 type: 'boolean',263 default: true,264 description: 'Option to enable/disable component attribute shorthand if attribute name and expressions are same',265 },266 svelteIndentScriptAndStyle: {267 category: 'Svelte',268 type: 'boolean',269 default: true,270 description: 'Whether or not to indent the code inside <script> and <style> tags in Svelte files',271 },272};273const sortOrderSeparator = '-';274function parseSortOrder(sortOrder = 'options-scripts-markup-styles') {275 if (sortOrder === 'none') {276 return [];277 }278 const order = sortOrder.split(sortOrderSeparator);279 if (!order.includes('options')) {280 throw new Error('svelteSortOrder is missing option `options`');281 }282 return order;283}284function isBracketSameLine(options) {285 return options.bracketSameLine != null ? options.bracketSameLine : false;286}287 288/**289 * Determines whether or not given node290 * is the root of the Svelte AST.291 */292function isASTNode(n) {293 return n && n.__isRoot;294}295function isPreTagContent(path) {296 const stack = path.stack;297 return stack.some((node) => (node.type === 'RegularElement' && node.name.toLowerCase() === 'pre') ||298 (node.type === 'Attribute' && !formattableAttributes.includes(node.name)));299}300function flatten(arrays) {301 return [].concat.apply([], arrays);302}303function findLastIndex(isMatch, items) {304 for (let i = items.length - 1; i >= 0; i--) {305 if (isMatch(items[i], i)) {306 return i;307 }308 }309 return -1;310}311function replaceEndOfLineWith(text, replacement) {312 const parts = [];313 for (const part of text.split('\n')) {314 if (parts.length > 0) {315 parts.push(replacement);316 }317 if (part.endsWith('\r')) {318 parts.push(part.slice(0, -1));319 }320 else {321 parts.push(part);322 }323 }324 return parts;325}326function getAttributeLine(node, options) {327 const { hardline, line } = prettier.doc.builders;328 const hasThisBinding = ((node.type === 'Component' || node.type === 'SvelteComponent') &&329 !!node.expression) ||330 (node.type === 'SvelteElement' && !!node.tag);331 const attributes = node.attributes.filter((attribute) => attribute.name !== snippedTagContentAttribute);332 return options.singleAttributePerLine &&333 (attributes.length > 1 || (attributes.length && hasThisBinding))334 ? hardline335 : line;336}337function printWithPrependedAttributeLine(node, options, print) {338 return (path) => path.getNode().name !== snippedTagContentAttribute339 ? [getAttributeLine(node, options), path.call(print)]340 : '';341}342 343/**344 * Check if doc is a hardline.345 * We can't just rely on a simple equality check because the doc could be created with another346 * runtime version of prettier than what we import, making a reference check fail.347 */348function isHardline(docToCheck) {349 return docToCheck === prettier.doc.builders.hardline || deepEqual(docToCheck, prettier.doc.builders.hardline);350}351/**352 * Simple deep equal function which suits our needs. Only works properly on POJOs without cyclic deps.353 */354function deepEqual(x, y) {355 if (x === y) {356 return true;357 }358 else if (typeof x == 'object' && x != null && typeof y == 'object' && y != null) {359 if (Object.keys(x).length != Object.keys(y).length)360 return false;361 for (var prop in x) {362 if (y.hasOwnProperty(prop)) {363 if (!deepEqual(x[prop], y[prop]))364 return false;365 }366 else {367 return false;368 }369 }370 return true;371 }372 else {373 return false;374 }375}376function isDocCommand(doc) {377 return typeof doc === 'object' && doc !== null;378}379function isLine(docToCheck) {380 return (isHardline(docToCheck) ||381 (isDocCommand(docToCheck) && docToCheck.type === 'line') ||382 (Array.isArray(docToCheck) && docToCheck.every(isLine)));383}384/**385 * Check if the doc is empty, i.e. consists of nothing more than empty strings (possibly nested).386 */387function isEmptyDoc(doc) {388 if (typeof doc === 'string') {389 return doc.length === 0;390 }391 if (isDocCommand(doc) && doc.type === 'line') {392 return !doc.keepIfLonely;393 }394 if (Array.isArray(doc)) {395 return doc.length === 0;396 }397 const { contents } = doc;398 if (contents) {399 return isEmptyDoc(contents);400 }401 const { parts } = doc;402 if (parts) {403 return isEmptyGroup(parts);404 }405 return false;406}407function isEmptyGroup(group) {408 return !group.find((doc) => !isEmptyDoc(doc));409}410/**411 * Trims both leading and trailing nodes matching `isWhitespace` independent of nesting level412 * (though all trimmed adjacent nodes need to be a the same level). Modifies the `docs` array.413 */414function trim(docs, isWhitespace) {415 trimLeft(docs, isWhitespace);416 trimRight(docs, isWhitespace);417 return docs;418}419/**420 * Trims the leading nodes matching `isWhitespace` independent of nesting level (though all nodes need to be a the same level).421 * If there are empty docs before the first whitespace, they are removed, too.422 */423function trimLeft(group, isWhitespace) {424 let firstNonWhitespace = group.findIndex((doc) => !isEmptyDoc(doc) && !isWhitespace(doc));425 if (firstNonWhitespace < 0 && group.length) {426 firstNonWhitespace = group.length;427 }428 if (firstNonWhitespace > 0) {429 const removed = group.splice(0, firstNonWhitespace);430 if (removed.every(isEmptyDoc)) {431 return trimLeft(group, isWhitespace);432 }433 }434 else {435 const parts = getParts(group[0]);436 if (parts) {437 return trimLeft(parts, isWhitespace);438 }439 }440}441/**442 * Trims the trailing nodes matching `isWhitespace` independent of nesting level (though all nodes need to be a the same level).443 * If there are empty docs after the last whitespace, they are removed, too.444 */445function trimRight(group, isWhitespace) {446 let lastNonWhitespace = group.length447 ? findLastIndex((doc) => !isEmptyDoc(doc) && !isWhitespace(doc), group)448 : 0;449 if (lastNonWhitespace < group.length - 1) {450 const removed = group.splice(lastNonWhitespace + 1);451 if (removed.every(isEmptyDoc)) {452 return trimRight(group, isWhitespace);453 }454 }455 else {456 const parts = getParts(group[group.length - 1]);457 if (parts) {458 return trimRight(parts, isWhitespace);459 }460 }461}462function getParts(doc) {463 if (typeof doc === 'object') {464 if (Array.isArray(doc)) {465 return doc;466 }467 if (doc.type === 'fill') {468 return doc.parts;469 }470 if (doc.type === 'group') {471 return getParts(doc.contents);472 }473 }474}475/**476 * `(foo = bar)` => `foo = bar`477 * Also handles leading comments and line breaks before "(".478 */479function removeParentheses(doc) {480 if (!Array.isArray(doc))481 return trim([doc], (_doc) => _doc === '(' || _doc === ')')[0];482 const transformed = [];483 let i = 0;484 let opened = false;485 for (; i < doc.length; i++) {486 const part = doc[i];487 if (typeof part === 'string' && part.startsWith('//')) {488 transformed.push(part);489 }490 else if (typeof part === 'string' && part.startsWith('/*')) {491 transformed.push(part);492 opened = true;493 }494 else if (opened) {495 transformed.push(part);496 opened = typeof part !== 'string' || !part.trim().endsWith('*/');497 }498 else if (transformed.length > 0 && isLine(part)) {499 transformed.push(part);500 i++;501 const next = doc[i];502 if (typeof next !== 'string' && !Array.isArray(next) && next.type === 'break-parent') {503 transformed.push(next);504 i++;505 }506 break;507 }508 else {509 break;510 }511 }512 transformed.push(...trim(doc.slice(i), (_doc) => _doc === '(' || _doc === ')'));513 return transformed;514}515 516const unsupportedLanguages = ['coffee', 'coffeescript', 'styl', 'stylus', 'sass'];517/**518 * Characters treated as interchangeable/collapsible HTML whitespace for layout.519 * Excludes NBSP (U+00A0) and other Unicode separators — see prettier/prettier#5796.520 */521const ONLY_HTML_COLLAPSE_WHITESPACE_RE = /^[\t\n\f\r ]*$/;522const STARTS_WITH_HTML_COLLAPSE_WHITESPACE_RE = /^[\t\n\f\r ]/;523const ENDS_WITH_HTML_COLLAPSE_WHITESPACE_RE = /[\t\n\f\r ]$/;524const LEADING_HTML_COLLAPSE_WHITESPACE_RE = /^[\t\n\f\r ]+/;525const TRAILING_HTML_COLLAPSE_WHITESPACE_RE = /[\t\n\f\r ]+$/;526function isOnlyHtmlCollapseWhitespace(text) {527 return ONLY_HTML_COLLAPSE_WHITESPACE_RE.test(text);528}529function isInlineElement(path, options, node) {530 return (node &&531 node.type === 'RegularElement' &&532 !isBlockElement(node, options) &&533 !isPreTagContent(path));534}535function isBlockElement(node, options) {536 return (node &&537 node.type === 'RegularElement' &&538 options.htmlWhitespaceSensitivity !== 'strict' &&539 (options.htmlWhitespaceSensitivity === 'ignore' ||540 blockElements.includes(node.name)));541}542function isNodeWithChildren(node) {543 return !!getMaybeChildren(node);544}545function getMaybeChildren(_node) {546 if (_node.type === 'Fragment')547 return _node.nodes;548 for (const key of Object.keys(_node)) {549 const value = _node[key];550 if (typeof value === 'object' && value != null && value.type === 'Fragment') {551 return value.nodes;552 }553 }554}555function getChildren(_node) {556 return getMaybeChildren(_node) || [];557}558/**559 * Returns siblings, that is, the children of the parent.560 */561function getSiblings(path) {562 let parent = path.getParentNode();563 if (isASTNode(parent)) {564 parent = parent.fragment;565 }566 return parent.nodes;567}568/**569 * Returns the comment that is above the current node.570 */571function getLeadingComment(path) {572 const siblings = getSiblings(path);573 let node = path.getNode();574 let prev = siblings.find((child) => child.end === node.start);575 while (prev) {576 if (prev.type === 'Comment' &&577 !isIgnoreStartDirective(prev) &&578 !isIgnoreEndDirective(prev)) {579 return prev;580 }581 else if (isEmptyTextNode(prev)) {582 node = prev;583 prev = siblings.find((child) => child.end === node.start);584 }585 else {586 return undefined;587 }588 }589}590function isNodeTopLevelHTML(node, path) {591 const root = path.stack[0];592 return !!root.fragment && !!root.fragment.nodes && root.fragment.nodes.includes(node);593}594function isEmptyTextNode(node) {595 return !!node && node.type === 'Text' && isOnlyHtmlCollapseWhitespace(getUnencodedText(node));596}597function isIgnoreDirective(node) {598 return !!node && node.type === 'Comment' && node.data.trim() === 'prettier-ignore';599}600function isIgnoreStartDirective(node) {601 return !!node && node.type === 'Comment' && node.data.trim() === 'prettier-ignore-start';602}603function isIgnoreEndDirective(node) {604 return !!node && node.type === 'Comment' && node.data.trim() === 'prettier-ignore-end';605}606function printRaw(node, originalText, stripLeadingAndTrailingNewline = false) {607 const children = getChildren(node);608 if (children.length === 0) {609 return '';610 }611 const firstChild = children[0];612 const lastChild = children[children.length - 1];613 let raw = originalText.substring(firstChild.start, lastChild.end);614 if (!stripLeadingAndTrailingNewline) {615 return raw;616 }617 if (startsWithLinebreak(raw)) {618 raw = raw.substring(raw.indexOf('\n') + 1);619 }620 if (endsWithLinebreak(raw)) {621 raw = raw.substring(0, raw.lastIndexOf('\n'));622 if (raw.charAt(raw.length - 1) === '\r') {623 raw = raw.substring(0, raw.length - 1);624 }625 }626 return raw;627}628function isTextNode(node) {629 return node.type === 'Text';630}631function getAttributeValue(attributeName, node) {632 var _a;633 const attributes = ((_a = node.attributes) !== null && _a !== void 0 ? _a : []);634 const langAttribute = attributes.find((attribute) => attribute.name === attributeName);635 return langAttribute && langAttribute.value;636}637function getAttributeTextValue(attributeName, node) {638 const value = getAttributeValue(attributeName, node);639 if (value != null && typeof value === 'object') {640 const value_nodes = Array.isArray(value) ? value : [value];641 const textValue = value_nodes.find(isTextNode);642 if (textValue) {643 return textValue.data;644 }645 }646 return null;647}648function getLangAttribute(node) {649 const value = getAttributeTextValue('lang', node) || getAttributeTextValue('type', node);650 if (value != null) {651 return value.replace(/^text\//, '');652 }653 else {654 return null;655 }656}657/**658 * Checks whether the node contains a `lang` or `type` attribute with a value corresponding to659 * a language we cannot format. This might for example be `<template lang="pug">`.660 * If the node does not contain a `lang` attribute, the result is true.661 */662function isNodeSupportedLanguage(node) {663 const lang = getLangAttribute(node);664 return !(lang && unsupportedLanguages.includes(lang));665}666/**667 * Checks whether the node contains a `lang` or `type` attribute which indicates that668 * the script contents are written in TypeScript. Note that the absence of the tag669 * does not mean it's not TypeScript, because the user could have set the default670 * to TypeScript in his settings.671 */672function isTypeScript(node) {673 const lang = getLangAttribute(node) || '';674 return ['typescript', 'ts'].includes(lang);675}676function isJSON(node) {677 const lang = getLangAttribute(node) || '';678 // todo: check if this is still necessary679 // https://github.com/prettier/prettier/pull/6293680 return lang.endsWith('json') || lang.endsWith('importmap');681}682function isLess(node) {683 const lang = getLangAttribute(node) || '';684 return ['less'].includes(lang);685}686function isScss(node) {687 const lang = getLangAttribute(node) || '';688 return ['sass', 'scss'].includes(lang);689}690function isPugTemplate(node) {691 return (node.type === 'RegularElement' &&692 node.name === 'template' &&693 getLangAttribute(node) === 'pug');694}695function isLoneMustacheTag(node) {696 if (node === true || node == null) {697 return false;698 }699 if (Array.isArray(node)) {700 return node.length === 1 && node[0].type === 'ExpressionTag';701 }702 return node.type === 'ExpressionTag';703}704/**705 * True if node is of type `{a}` or `a={a}`706 */707function isOrCanBeConvertedToShorthand(node) {708 if (isLoneMustacheTag(node.value)) {709 const value_node = Array.isArray(node.value) ? node.value[0] : node.value;710 const expression = value_node.type === 'ExpressionTag' ? value_node.expression : null;711 if (!expression) {712 return false;713 }714 return expression.type === 'Identifier' && expression.name === node.name;715 }716 return false;717}718function getUnencodedText(node) {719 // `raw` will contain HTML entities in unencoded form720 return node.raw || node.data;721}722function isTextNodeStartingWithLinebreak(node, nrLines = 1) {723 return node.type === 'Text' && startsWithLinebreak(getUnencodedText(node), nrLines);724}725function startsWithLinebreak(text, nrLines = 1) {726 return new RegExp(`^([\\t\\f\\r ]*\\n){${nrLines}}`).test(text);727}728function isTextNodeEndingWithLinebreak(node, nrLines = 1) {729 return node.type === 'Text' && endsWithLinebreak(getUnencodedText(node), nrLines);730}731function endsWithLinebreak(text, nrLines = 1) {732 return new RegExp(`(\\n[\\t\\f\\r ]*){${nrLines}}$`).test(text);733}734function isTextNodeStartingWithWhitespace(node) {735 return (node.type === 'Text' && STARTS_WITH_HTML_COLLAPSE_WHITESPACE_RE.test(getUnencodedText(node)));736}737function isTextNodeEndingWithWhitespace(node) {738 return (node.type === 'Text' && ENDS_WITH_HTML_COLLAPSE_WHITESPACE_RE.test(getUnencodedText(node)));739}740function trimTextNodeRight(node) {741 node.raw = node.raw && node.raw.replace(TRAILING_HTML_COLLAPSE_WHITESPACE_RE, '');742 node.data = node.data && node.data.replace(TRAILING_HTML_COLLAPSE_WHITESPACE_RE, '');743}744function trimTextNodeLeft(node) {745 node.raw = node.raw && node.raw.replace(LEADING_HTML_COLLAPSE_WHITESPACE_RE, '');746 node.data = node.data && node.data.replace(LEADING_HTML_COLLAPSE_WHITESPACE_RE, '');747}748/**749 * Remove all leading whitespace up until the first non-empty text node,750 * and all trailing whitespace from the last non-empty text node onwards.751 */752function trimChildren(children) {753 let firstNonEmptyNode = children.findIndex((n) => !isEmptyTextNode(n));754 firstNonEmptyNode = firstNonEmptyNode === -1 ? children.length - 1 : firstNonEmptyNode;755 let lastNonEmptyNode = findLastIndex((n) => !isEmptyTextNode(n), children);756 lastNonEmptyNode = lastNonEmptyNode === -1 ? 0 : lastNonEmptyNode;757 for (let i = 0; i <= firstNonEmptyNode; i++) {758 const n = children[i];759 if (n.type === 'Text') {760 trimTextNodeLeft(n);761 }762 }763 for (let i = children.length - 1; i >= lastNonEmptyNode; i--) {764 const n = children[i];765 if (n.type === 'Text') {766 trimTextNodeRight(n);767 }768 }769}770/**771 * Check if given node's start tag should hug its first child. This is the case for inline elements when there's772 * no whitespace between the `>` and the first child.773 */774function shouldHugStart(node, isSupportedLanguage, options) {775 if (!isSupportedLanguage) {776 return true;777 }778 if (node.type === 'SvelteBoundary') {779 return false;780 }781 if (isBlockElement(node, options)) {782 return false;783 }784 if (!isNodeWithChildren(node)) {785 return false;786 }787 const children = getChildren(node);788 if (children.length === 0) {789 return true;790 }791 if (options.htmlWhitespaceSensitivity === 'ignore') {792 return false;793 }794 const firstChild = children[0];795 return !isTextNodeStartingWithWhitespace(firstChild);796}797/**798 * Check if given node's end tag should hug its last child. This is the case for inline elements when there's799 * no whitespace between the last child and the `</`.800 */801function shouldHugEnd(node, isSupportedLanguage, options) {802 if (!isSupportedLanguage) {803 return true;804 }805 if (node.type === 'SvelteBoundary') {806 return false;807 }808 if (isBlockElement(node, options)) {809 return false;810 }811 if (!isNodeWithChildren(node)) {812 return false;813 }814 const children = getChildren(node);815 if (children.length === 0) {816 return true;817 }818 if (options.htmlWhitespaceSensitivity === 'ignore') {819 return false;820 }821 const lastChild = children[children.length - 1];822 return !isTextNodeEndingWithWhitespace(lastChild);823}824/**825 * Check for a svelte block if there's whitespace at the start and if it's a space or a line.826 */827function checkWhitespaceAtStartOfSvelteBlock(node, options) {828 if (!isNodeWithChildren(node)) {829 return 'none';830 }831 const children = node.nodes;832 if (children.length === 0) {833 return 'none';834 }835 const firstChild = children[0];836 if (isTextNodeStartingWithLinebreak(firstChild)) {837 return 'line';838 }839 else if (isTextNodeStartingWithWhitespace(firstChild)) {840 return 'space';841 }842 // This extra check is necessary because the Svelte AST might swallow whitespace between843 // the block's starting end and its first child.844 const parentOpeningEnd = options.originalText.lastIndexOf('}', firstChild.start);845 if (parentOpeningEnd > 0 && firstChild.start > parentOpeningEnd + 1) {846 const textBetween = options.originalText.substring(parentOpeningEnd + 1, firstChild.start);847 if (ONLY_HTML_COLLAPSE_WHITESPACE_RE.test(textBetween)) {848 return startsWithLinebreak(textBetween) ? 'line' : 'space';849 }850 }851 return 'none';852}853/**854 * Check for a svelte block if there's whitespace at the end and if it's a space or a line.855 */856function checkWhitespaceAtEndOfSvelteBlock(node, options) {857 if (!isNodeWithChildren(node)) {858 return 'none';859 }860 const children = node.nodes;861 if (children.length === 0) {862 return 'none';863 }864 const lastChild = children[children.length - 1];865 if (isTextNodeEndingWithLinebreak(lastChild)) {866 return 'line';867 }868 else if (isTextNodeEndingWithWhitespace(lastChild)) {869 return 'space';870 }871 // This extra check is necessary because the Svelte AST might swallow whitespace between872 // the last child and the block's ending start.873 const parentClosingStart = options.originalText.indexOf('{', lastChild.end);874 if (parentClosingStart > 0 && lastChild.end < parentClosingStart) {875 const textBetween = options.originalText.substring(lastChild.end, parentClosingStart);876 if (ONLY_HTML_COLLAPSE_WHITESPACE_RE.test(textBetween)) {877 return endsWithLinebreak(textBetween) ? 'line' : 'space';878 }879 }880 return 'none';881}882function isInsideQuotedAttribute(path, options) {883 const stack = path.stack;884 return stack.some((node) => (node.type === 'Attribute' || node.type === 'StyleDirective') &&885 !isLoneMustacheTag(node.value));886}887/**888 * Returns true if the softline between `</tagName` and `>` can be omitted.889 */890function canOmitSoftlineBeforeClosingTag(node, path, options) {891 return (isBracketSameLine(options) &&892 (!hugsStartOfNextNode(node, options) || isLastChildWithinParentBlockElement(path, options)));893}894/**895 * Return true if given node does not hug the next node, meaning there's whitespace896 * or the end of the doc afterwards.897 */898function hugsStartOfNextNode(node, options) {899 if (node.end === options.originalText.length) {900 // end of document901 return false;902 }903 return !STARTS_WITH_HTML_COLLAPSE_WHITESPACE_RE.test(options.originalText.substring(node.end));904}905function isLastChildWithinParentBlockElement(path, options) {906 const fragment = path.getParentNode();907 const parent = path.getParentNode(1);908 if (!fragment || !parent || !isBlockElement(parent, options)) {909 return false;910 }911 const children = fragment.nodes.filter((child) => !isEmptyTextNode(child));912 const lastChild = children[children.length - 1];913 return lastChild === path.getNode();914}915function assignCommentsToNodes(ast) {916 if (ast.module) {917 ast.module.comments = removeAndGetLeadingComments(ast, ast.module);918 }919 if (ast.instance) {920 ast.instance.comments = removeAndGetLeadingComments(ast, ast.instance);921 }922 if (ast.css) {923 ast.css.comments = removeAndGetLeadingComments(ast, ast.css);924 }925}926/**927 * Returns the comments that are above the current node and deletes them from the html ast.928 */929function removeAndGetLeadingComments(ast, current) {930 const siblings = ast.fragment.nodes;931 const comments = [];932 const newlines = [];933 if (!siblings.length) {934 return [];935 }936 let node = current;937 let prev = siblings.find((child) => child.end === node.start);938 while (prev) {939 if (prev.type === 'Comment' &&940 !isIgnoreStartDirective(prev) &&941 !isIgnoreEndDirective(prev)) {942 comments.push(prev);943 if (comments.length !== newlines.length) {944 newlines.push({ type: 'Text', data: '', raw: '', start: -1, end: -1 });945 }946 }947 else if (isEmptyTextNode(prev)) {948 newlines.push(prev);949 }950 else {951 break;952 }953 node = prev;954 prev = siblings.find((child) => child.end === node.start);955 }956 newlines.length = comments.length; // could be one more if first comment is preceeded by empty text node957 for (const comment of comments) {958 siblings.splice(siblings.indexOf(comment), 1);959 }960 for (const text of newlines) {961 siblings.splice(siblings.indexOf(text), 1);962 }963 return comments964 .map((comment, i) => ({965 comment,966 emptyLineAfter: getUnencodedText(newlines[i]).split('\n').length > 2,967 }))968 .reverse();969}970 971const { join, line, group, indent, dedent, softline, hardline, fill, breakParent, literalline } = prettier.doc.builders;972function hasPragma(text) {973 return /^\s*<!--\s*@(format|prettier)\W/.test(text);974}975let ignoreNext = false;976let ignoreRange = false;977function print(path, options, print) {978 var _a, _b, _c, _d, _e, _f;979 const bracketSameLine = isBracketSameLine(options);980 const n = path.node;981 if (!n) {982 return '';983 }984 if (isASTNode(n)) {985 return printTopLevelParts(n, options, path, print);986 }987 const [open, close] = ['{', '}'];988 const printJsExpression = () => [open, printJS(path, print, 'expression'), close];989 const node = n;990 if ((ignoreNext || (ignoreRange && !isIgnoreEndDirective(node))) &&991 (node.type !== 'Text' || !isEmptyTextNode(node))) {992 if (ignoreNext) {993 ignoreNext = false;994 }995 return flatten(options.originalText996 .slice(options.locStart(node), options.locEnd(node))997 .split('\n')998 .map((o, i) => (i == 0 ? [o] : [literalline, o])));999 }1000 switch (node.type) {1001 case 'Fragment':1002 const children = node.nodes;1003 if (children.length === 0 || children.every(isEmptyTextNode)) {1004 return '';1005 }1006 if (!isPreTagContent(path)) {1007 trimChildren(children);1008 const output = trim([printChildren(path, print, options)], (n) => isLine(n) ||1009 (typeof n === 'string' && isOnlyHtmlCollapseWhitespace(n)) ||1010 // Because printChildren may append this at the end and1011 // may hide other lines before it1012 n === breakParent);1013 if (output.every((doc) => isEmptyDoc(doc))) {1014 return '';1015 }1016 return group([...output, hardline]);1017 }1018 else {1019 return group(path.map(print, 'nodes'));1020 }1021 case 'Text':1022 if (!isPreTagContent(path)) {1023 if (isEmptyTextNode(node)) {1024 return printWhitespace(getUnencodedText(node));1025 }1026 /**1027 * For non-empty text nodes each sequence of non-whitespace characters (effectively,1028 * each "word") is joined by a single `line`, which will be rendered as a single space1029 * until this node's current line is out of room, at which `fill` will break at the1030 * most convenient instance of `line`.1031 */1032 return fill(splitTextToDocs(node));1033 }1034 else {1035 let rawText = getUnencodedText(node);1036 const parent = path.getParentNode();1037 if (parent.type === 'Attribute') {1038 // Direct child of attribute value -> add literallines at end of lines1039 // so that other things don't break in unexpected places1040 if (parent.name === 'class' &&1041 path.getParentNode(1).type === 'RegularElement') {1042 // Special treatment for class attribute on html elements. Prettier1043 // will force everything into one line, we deviate from that and preserve lines.1044 rawText = rawText.replace(/([^ \t\n])(([ \t]+$)|([ \t]+(\r?\n))|[ \t]+)/g, 1045 // Remove trailing whitespace in lines with non-whitespace characters1046 // except at the end of the string1047 (match, characterBeforeWhitespace, _, isEndOfString, isEndOfLine, endOfLine) => isEndOfString1048 ? match1049 : characterBeforeWhitespace + (isEndOfLine ? endOfLine : ' '));1050 // Shrink trailing whitespace in case it's followed by a mustache tag1051 // and remove it completely if it's at the end of the string, but not1052 // if it's on its own line1053 rawText = rawText.replace(/([^ \t\n])[ \t]+$/, parent.value.indexOf(node) === parent.value.length - 1 ? '$1' : '$1 ');1054 }1055 return replaceEndOfLineWith(rawText, literalline);1056 }1057 return rawText;1058 }1059 case 'RegularElement':1060 case 'Component':1061 case 'SvelteComponent':1062 case 'SvelteSelf':1063 case 'SlotElement':1064 case 'SvelteFragment':1065 case 'SvelteWindow':1066 case 'SvelteHead':1067 case 'SvelteBody':1068 case 'SvelteDocument':1069 case 'SvelteElement':1070 case 'SvelteBoundary':1071 case 'TitleElement': {1072 const isSupportedLanguage = !(node.name === 'template' && !isNodeSupportedLanguage(node));1073 const element_children = getChildren(node);1074 const isEmpty = element_children.every((child) => isEmptyTextNode(child));1075 const isDoctypeTag = node.name.toUpperCase() === '!DOCTYPE';1076 const didSelfClose = options.originalText[node.end - 2] === '/';1077 const isSelfClosingTag = isEmpty &&1078 (((node.type === 'RegularElement' ||1079 node.type === 'SvelteHead' ||1080 node.type === 'Component' ||1081 node.type === 'SvelteComponent' ||1082 node.type === 'SvelteSelf' ||1083 node.type === 'SlotElement' ||1084 node.type === 'SvelteFragment' ||1085 node.type === 'SvelteBoundary' ||1086 node.type === 'TitleElement' ||1087 node.type === 'SvelteBody' ||1088 node.type === 'SvelteDocument' ||1089 node.type === 'SvelteElement') &&1090 didSelfClose) ||1091 node.type === 'SvelteWindow' ||1092 selfClosingTags.indexOf(node.name) !== -1 ||1093 isDoctypeTag);1094 // Order important: print attributes first1095 const attributes = path.map(printWithPrependedAttributeLine(node, options, print), 'attributes');1096 const attributeLine = getAttributeLine(node, options);1097 const possibleThisBinding = node.type === 'SvelteComponent' && node.expression1098 ? [attributeLine, 'this=', ...printJsExpression()]1099 : node.type === 'SvelteElement' && node.tag1100 ? [1101 attributeLine,1102 'this=',1103 ...(() => {1104 var _a;1105 if (typeof node.tag === 'string') {1106 return [`"${node.tag}"`];1107 }1108 if (((_a = node.tag) === null || _a === void 0 ? void 0 : _a.type) === 'Literal' &&1109 typeof node.tag.value === 'string') {1110 const literal_value = node.tag.value;1111 const tag_start = node.tag.start;1112 const expression_wrapped = typeof tag_start === 'number' &&1113 options.originalText[tag_start - 1] === '{';1114 // Preserve <svelte:element this={"literal"}>1115 // because in Svelte 6 this="literal" will be invalid1116 if (expression_wrapped) {1117 return [open, `"${literal_value}"`, close];1118 }1119 return [`"${literal_value}"`];1120 }1121 return [open, printJS(path, print, 'tag'), close];1122 })(),1123 ]1124 : '';1125 if (isSelfClosingTag) {1126 return group([1127 '<',1128 node.name,1129 indent(group([1130 possibleThisBinding,1131 ...attributes,1132 bracketSameLine || isDoctypeTag ? '' : dedent(line),1133 ])),1134 ...[bracketSameLine && !isDoctypeTag ? ' ' : '', `${isDoctypeTag ? '' : '/'}>`],1135 ]);1136 }1137 const children = element_children;1138 const firstChild = children[0];1139 const lastChild = children[children.length - 1];1140 // Is a function which is invoked later because printChildren will manipulate child nodes1141 // which would wrongfully change the other checks about hugging etc done beforehand1142 let body;1143 const hugStart = shouldHugStart(node, isSupportedLanguage, options);1144 const hugEnd = shouldHugEnd(node, isSupportedLanguage, options);1145 if (isEmpty) {1146 body =1147 isInlineElement(path, options, node) &&1148 children.length &&1149 isTextNodeStartingWithWhitespace(children[0]) &&1150 !isPreTagContent(path)1151 ? () => line1152 : () => (bracketSameLine ? softline : '');1153 }1154 else if (isPreTagContent(path)) {1155 body = () => path.call((fragment_path) => printPre(options.originalText, fragment_path, print), 'fragment');1156 }1157 else if (!isSupportedLanguage) {1158 body = () => printRaw(node, options.originalText, true);1159 }1160 else if (isInlineElement(path, options, node) && !isPreTagContent(path)) {1161 body = () => path.call((fragment_path) => printChildren(fragment_path, print, options), 'fragment');1162 }1163 else {1164 body = () => path.call((fragment_path) => printChildren(fragment_path, print, options), 'fragment');1165 }1166 const openingTag = [1167 '<',1168 node.name,1169 indent(group([1170 possibleThisBinding,1171 ...attributes,1172 hugStart && !isEmpty1173 ? ''1174 : !bracketSameLine && !isPreTagContent(path)1175 ? dedent(softline)1176 : '',1177 ])),1178 ];1179 if (!isSupportedLanguage && !isEmpty) {1180 // Format template tags so that there's a hardline but no indention.1181 // That way the `lang="X"` and the closing `>` of the start tag stay in one line1182 // which is the 99% use case.1183 return group([1184 ...openingTag,1185 '>',1186 group([hardline, body(), hardline]),1187 `</${node.name}>`,1188 ]);1189 }1190 if (hugStart && hugEnd) {1191 const huggedContent = [softline, group(['>', body(), `</${node.name}`])];1192 const omitSoftlineBeforeClosingTag = (isEmpty && !bracketSameLine) ||1193 canOmitSoftlineBeforeClosingTag(node, path, options);1194 return group([1195 ...openingTag,1196 isEmpty ? group(huggedContent) : group(indent(huggedContent)),1197 omitSoftlineBeforeClosingTag ? '' : softline,1198 '>',1199 ]);1200 }