You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2248 lines
69 KiB

4 years ago
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = global || self, factory(global.doc = {}));
  5. }(this, (function (exports) { 'use strict';
  6. /**
  7. * @param {Doc[]} parts
  8. * @returns Doc
  9. */
  10. function concat(parts) {
  11. // access the internals of a document directly.
  12. // if(parts.length === 1) {
  13. // // If it's a single document, no need to concat it.
  14. // return parts[0];
  15. // }
  16. return {
  17. type: "concat",
  18. parts: parts
  19. };
  20. }
  21. /**
  22. * @param {Doc} contents
  23. * @returns Doc
  24. */
  25. function indent(contents) {
  26. return {
  27. type: "indent",
  28. contents: contents
  29. };
  30. }
  31. /**
  32. * @param {number} n
  33. * @param {Doc} contents
  34. * @returns Doc
  35. */
  36. function align(n, contents) {
  37. return {
  38. type: "align",
  39. contents: contents,
  40. n: n
  41. };
  42. }
  43. /**
  44. * @param {Doc} contents
  45. * @param {object} [opts] - TBD ???
  46. * @returns Doc
  47. */
  48. function group(contents, opts) {
  49. opts = opts || {};
  50. return {
  51. type: "group",
  52. id: opts.id,
  53. contents: contents,
  54. break: !!opts.shouldBreak,
  55. expandedStates: opts.expandedStates
  56. };
  57. }
  58. /**
  59. * @param {Doc} contents
  60. * @returns Doc
  61. */
  62. function dedentToRoot(contents) {
  63. return align(-Infinity, contents);
  64. }
  65. /**
  66. * @param {Doc} contents
  67. * @returns Doc
  68. */
  69. function markAsRoot(contents) {
  70. // @ts-ignore - TBD ???:
  71. return align({
  72. type: "root"
  73. }, contents);
  74. }
  75. /**
  76. * @param {Doc} contents
  77. * @returns Doc
  78. */
  79. function dedent(contents) {
  80. return align(-1, contents);
  81. }
  82. /**
  83. * @param {Doc[]} states
  84. * @param {object} [opts] - TBD ???
  85. * @returns Doc
  86. */
  87. function conditionalGroup(states, opts) {
  88. return group(states[0], Object.assign(opts || {}, {
  89. expandedStates: states
  90. }));
  91. }
  92. /**
  93. * @param {Doc[]} parts
  94. * @returns Doc
  95. */
  96. function fill(parts) {
  97. return {
  98. type: "fill",
  99. parts: parts
  100. };
  101. }
  102. /**
  103. * @param {Doc} [breakContents]
  104. * @param {Doc} [flatContents]
  105. * @param {object} [opts] - TBD ???
  106. * @returns Doc
  107. */
  108. function ifBreak(breakContents, flatContents, opts) {
  109. opts = opts || {};
  110. return {
  111. type: "if-break",
  112. breakContents: breakContents,
  113. flatContents: flatContents,
  114. groupId: opts.groupId
  115. };
  116. }
  117. /**
  118. * @param {Doc} contents
  119. * @returns Doc
  120. */
  121. function lineSuffix(contents) {
  122. return {
  123. type: "line-suffix",
  124. contents: contents
  125. };
  126. }
  127. var lineSuffixBoundary = {
  128. type: "line-suffix-boundary"
  129. };
  130. var breakParent = {
  131. type: "break-parent"
  132. };
  133. var trim = {
  134. type: "trim"
  135. };
  136. var line = {
  137. type: "line"
  138. };
  139. var softline = {
  140. type: "line",
  141. soft: true
  142. };
  143. var hardline = concat([{
  144. type: "line",
  145. hard: true
  146. }, breakParent]);
  147. var literalline = concat([{
  148. type: "line",
  149. hard: true,
  150. literal: true
  151. }, breakParent]);
  152. var cursor = {
  153. type: "cursor",
  154. placeholder: Symbol("cursor")
  155. };
  156. /**
  157. * @param {Doc} sep
  158. * @param {Doc[]} arr
  159. * @returns Doc
  160. */
  161. function join(sep, arr) {
  162. var res = [];
  163. for (var i = 0; i < arr.length; i++) {
  164. if (i !== 0) {
  165. res.push(sep);
  166. }
  167. res.push(arr[i]);
  168. }
  169. return concat(res);
  170. }
  171. /**
  172. * @param {Doc} doc
  173. * @param {number} size
  174. * @param {number} tabWidth
  175. */
  176. function addAlignmentToDoc(doc, size, tabWidth) {
  177. var aligned = doc;
  178. if (size > 0) {
  179. // Use indent to add tabs for all the levels of tabs we need
  180. for (var i = 0; i < Math.floor(size / tabWidth); ++i) {
  181. aligned = indent(aligned);
  182. } // Use align for all the spaces that are needed
  183. aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
  184. // indentation, so we use -Infinity to reset the indentation to 0
  185. aligned = align(-Infinity, aligned);
  186. }
  187. return aligned;
  188. }
  189. var docBuilders = {
  190. concat: concat,
  191. join: join,
  192. line: line,
  193. softline: softline,
  194. hardline: hardline,
  195. literalline: literalline,
  196. group: group,
  197. conditionalGroup: conditionalGroup,
  198. fill: fill,
  199. lineSuffix: lineSuffix,
  200. lineSuffixBoundary: lineSuffixBoundary,
  201. cursor: cursor,
  202. breakParent: breakParent,
  203. ifBreak: ifBreak,
  204. trim: trim,
  205. indent: indent,
  206. align: align,
  207. addAlignmentToDoc: addAlignmentToDoc,
  208. markAsRoot: markAsRoot,
  209. dedentToRoot: dedentToRoot,
  210. dedent: dedent
  211. };
  212. var ansiRegex = function ansiRegex(options) {
  213. options = Object.assign({
  214. onlyFirst: false
  215. }, options);
  216. var pattern = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
  217. return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
  218. };
  219. var stripAnsi = function stripAnsi(string) {
  220. return typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
  221. };
  222. var stripAnsi_1 = stripAnsi;
  223. var default_1 = stripAnsi;
  224. stripAnsi_1.default = default_1;
  225. /* eslint-disable yoda */
  226. var isFullwidthCodePoint = function isFullwidthCodePoint(codePoint) {
  227. if (Number.isNaN(codePoint)) {
  228. return false;
  229. } // Code points are derived from:
  230. // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
  231. if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
  232. codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
  233. codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
  234. // CJK Radicals Supplement .. Enclosed CJK Letters and Months
  235. 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
  236. 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
  237. 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
  238. 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
  239. 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
  240. 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
  241. 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
  242. 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
  243. 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
  244. 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
  245. 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
  246. 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
  247. return true;
  248. }
  249. return false;
  250. };
  251. var isFullwidthCodePoint_1 = isFullwidthCodePoint;
  252. var default_1$1 = isFullwidthCodePoint;
  253. isFullwidthCodePoint_1.default = default_1$1;
  254. var emojiRegex = function emojiRegex() {
  255. // https://mths.be/emoji
  256. return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200
  257. };
  258. var stringWidth = function stringWidth(string) {
  259. string = string.replace(emojiRegex(), ' ');
  260. if (typeof string !== 'string' || string.length === 0) {
  261. return 0;
  262. }
  263. string = stripAnsi_1(string);
  264. var width = 0;
  265. for (var i = 0; i < string.length; i++) {
  266. var code = string.codePointAt(i); // Ignore control characters
  267. if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
  268. continue;
  269. } // Ignore combining characters
  270. if (code >= 0x300 && code <= 0x36F) {
  271. continue;
  272. } // Surrogates
  273. if (code > 0xFFFF) {
  274. i++;
  275. }
  276. width += isFullwidthCodePoint_1(code) ? 2 : 1;
  277. }
  278. return width;
  279. };
  280. var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
  281. var default_1$2 = stringWidth;
  282. stringWidth_1.default = default_1$2;
  283. var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
  284. var escapeStringRegexp = function escapeStringRegexp(str) {
  285. if (typeof str !== 'string') {
  286. throw new TypeError('Expected a string');
  287. }
  288. return str.replace(matchOperatorsRe, '\\$&');
  289. };
  290. var getLast = function getLast(arr) {
  291. return arr.length > 0 ? arr[arr.length - 1] : null;
  292. };
  293. var notAsciiRegex = /[^\x20-\x7F]/;
  294. function isExportDeclaration(node) {
  295. if (node) {
  296. switch (node.type) {
  297. case "ExportDefaultDeclaration":
  298. case "ExportDefaultSpecifier":
  299. case "DeclareExportDeclaration":
  300. case "ExportNamedDeclaration":
  301. case "ExportAllDeclaration":
  302. return true;
  303. }
  304. }
  305. return false;
  306. }
  307. function getParentExportDeclaration(path) {
  308. var parentNode = path.getParentNode();
  309. if (path.getName() === "declaration" && isExportDeclaration(parentNode)) {
  310. return parentNode;
  311. }
  312. return null;
  313. }
  314. function getPenultimate(arr) {
  315. if (arr.length > 1) {
  316. return arr[arr.length - 2];
  317. }
  318. return null;
  319. }
  320. /**
  321. * @typedef {{backwards?: boolean}} SkipOptions
  322. */
  323. /**
  324. * @param {string | RegExp} chars
  325. * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
  326. */
  327. function skip(chars) {
  328. return function (text, index, opts) {
  329. var backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
  330. // to check for failures (did someone say monads?).
  331. if (index === false) {
  332. return false;
  333. }
  334. var length = text.length;
  335. var cursor = index;
  336. while (cursor >= 0 && cursor < length) {
  337. var c = text.charAt(cursor);
  338. if (chars instanceof RegExp) {
  339. if (!chars.test(c)) {
  340. return cursor;
  341. }
  342. } else if (chars.indexOf(c) === -1) {
  343. return cursor;
  344. }
  345. backwards ? cursor-- : cursor++;
  346. }
  347. if (cursor === -1 || cursor === length) {
  348. // If we reached the beginning or end of the file, return the
  349. // out-of-bounds cursor. It's up to the caller to handle this
  350. // correctly. We don't want to indicate `false` though if it
  351. // actually skipped valid characters.
  352. return cursor;
  353. }
  354. return false;
  355. };
  356. }
  357. /**
  358. * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
  359. */
  360. var skipWhitespace = skip(/\s/);
  361. /**
  362. * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
  363. */
  364. var skipSpaces = skip(" \t");
  365. /**
  366. * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
  367. */
  368. var skipToLineEnd = skip(",; \t");
  369. /**
  370. * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
  371. */
  372. var skipEverythingButNewLine = skip(/[^\r\n]/);
  373. /**
  374. * @param {string} text
  375. * @param {number | false} index
  376. * @returns {number | false}
  377. */
  378. function skipInlineComment(text, index) {
  379. if (index === false) {
  380. return false;
  381. }
  382. if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
  383. for (var i = index + 2; i < text.length; ++i) {
  384. if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
  385. return i + 2;
  386. }
  387. }
  388. }
  389. return index;
  390. }
  391. /**
  392. * @param {string} text
  393. * @param {number | false} index
  394. * @returns {number | false}
  395. */
  396. function skipTrailingComment(text, index) {
  397. if (index === false) {
  398. return false;
  399. }
  400. if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
  401. return skipEverythingButNewLine(text, index);
  402. }
  403. return index;
  404. } // This one doesn't use the above helper function because it wants to
  405. // test \r\n in order and `skip` doesn't support ordering and we only
  406. // want to skip one newline. It's simple to implement.
  407. /**
  408. * @param {string} text
  409. * @param {number | false} index
  410. * @param {SkipOptions=} opts
  411. * @returns {number | false}
  412. */
  413. function skipNewline(text, index, opts) {
  414. var backwards = opts && opts.backwards;
  415. if (index === false) {
  416. return false;
  417. }
  418. var atIndex = text.charAt(index);
  419. if (backwards) {
  420. if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
  421. return index - 2;
  422. }
  423. if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
  424. return index - 1;
  425. }
  426. } else {
  427. if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
  428. return index + 2;
  429. }
  430. if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
  431. return index + 1;
  432. }
  433. }
  434. return index;
  435. }
  436. /**
  437. * @param {string} text
  438. * @param {number} index
  439. * @param {SkipOptions=} opts
  440. * @returns {boolean}
  441. */
  442. function hasNewline(text, index, opts) {
  443. opts = opts || {};
  444. var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
  445. var idx2 = skipNewline(text, idx, opts);
  446. return idx !== idx2;
  447. }
  448. /**
  449. * @param {string} text
  450. * @param {number} start
  451. * @param {number} end
  452. * @returns {boolean}
  453. */
  454. function hasNewlineInRange(text, start, end) {
  455. for (var i = start; i < end; ++i) {
  456. if (text.charAt(i) === "\n") {
  457. return true;
  458. }
  459. }
  460. return false;
  461. } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
  462. /**
  463. * @template N
  464. * @param {string} text
  465. * @param {N} node
  466. * @param {(node: N) => number} locStart
  467. */
  468. function isPreviousLineEmpty(text, node, locStart) {
  469. /** @type {number | false} */
  470. var idx = locStart(node) - 1;
  471. idx = skipSpaces(text, idx, {
  472. backwards: true
  473. });
  474. idx = skipNewline(text, idx, {
  475. backwards: true
  476. });
  477. idx = skipSpaces(text, idx, {
  478. backwards: true
  479. });
  480. var idx2 = skipNewline(text, idx, {
  481. backwards: true
  482. });
  483. return idx !== idx2;
  484. }
  485. /**
  486. * @param {string} text
  487. * @param {number} index
  488. * @returns {boolean}
  489. */
  490. function isNextLineEmptyAfterIndex(text, index) {
  491. /** @type {number | false} */
  492. var oldIdx = null;
  493. /** @type {number | false} */
  494. var idx = index;
  495. while (idx !== oldIdx) {
  496. // We need to skip all the potential trailing inline comments
  497. oldIdx = idx;
  498. idx = skipToLineEnd(text, idx);
  499. idx = skipInlineComment(text, idx);
  500. idx = skipSpaces(text, idx);
  501. }
  502. idx = skipTrailingComment(text, idx);
  503. idx = skipNewline(text, idx);
  504. return idx !== false && hasNewline(text, idx);
  505. }
  506. /**
  507. * @template N
  508. * @param {string} text
  509. * @param {N} node
  510. * @param {(node: N) => number} locEnd
  511. * @returns {boolean}
  512. */
  513. function isNextLineEmpty(text, node, locEnd) {
  514. return isNextLineEmptyAfterIndex(text, locEnd(node));
  515. }
  516. /**
  517. * @param {string} text
  518. * @param {number} idx
  519. * @returns {number | false}
  520. */
  521. function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
  522. /** @type {number | false} */
  523. var oldIdx = null;
  524. /** @type {number | false} */
  525. var nextIdx = idx;
  526. while (nextIdx !== oldIdx) {
  527. oldIdx = nextIdx;
  528. nextIdx = skipSpaces(text, nextIdx);
  529. nextIdx = skipInlineComment(text, nextIdx);
  530. nextIdx = skipTrailingComment(text, nextIdx);
  531. nextIdx = skipNewline(text, nextIdx);
  532. }
  533. return nextIdx;
  534. }
  535. /**
  536. * @template N
  537. * @param {string} text
  538. * @param {N} node
  539. * @param {(node: N) => number} locEnd
  540. * @returns {number | false}
  541. */
  542. function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
  543. return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
  544. }
  545. /**
  546. * @template N
  547. * @param {string} text
  548. * @param {N} node
  549. * @param {(node: N) => number} locEnd
  550. * @returns {string}
  551. */
  552. function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
  553. return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
  554. getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
  555. }
  556. /**
  557. * @param {string} text
  558. * @param {number} index
  559. * @param {SkipOptions=} opts
  560. * @returns {boolean}
  561. */
  562. function hasSpaces(text, index, opts) {
  563. opts = opts || {};
  564. var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
  565. return idx !== index;
  566. }
  567. /**
  568. * @param {{range?: [number, number], start?: number}} node
  569. * @param {number} index
  570. */
  571. function setLocStart(node, index) {
  572. if (node.range) {
  573. node.range[0] = index;
  574. } else {
  575. node.start = index;
  576. }
  577. }
  578. /**
  579. * @param {{range?: [number, number], end?: number}} node
  580. * @param {number} index
  581. */
  582. function setLocEnd(node, index) {
  583. if (node.range) {
  584. node.range[1] = index;
  585. } else {
  586. node.end = index;
  587. }
  588. }
  589. var PRECEDENCE = {};
  590. [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach(function (tier, i) {
  591. tier.forEach(function (op) {
  592. PRECEDENCE[op] = i;
  593. });
  594. });
  595. function getPrecedence(op) {
  596. return PRECEDENCE[op];
  597. }
  598. var equalityOperators = {
  599. "==": true,
  600. "!=": true,
  601. "===": true,
  602. "!==": true
  603. };
  604. var multiplicativeOperators = {
  605. "*": true,
  606. "/": true,
  607. "%": true
  608. };
  609. var bitshiftOperators = {
  610. ">>": true,
  611. ">>>": true,
  612. "<<": true
  613. };
  614. function shouldFlatten(parentOp, nodeOp) {
  615. if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
  616. return false;
  617. } // ** is right-associative
  618. // x ** y ** z --> x ** (y ** z)
  619. if (parentOp === "**") {
  620. return false;
  621. } // x == y == z --> (x == y) == z
  622. if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
  623. return false;
  624. } // x * y % z --> (x * y) % z
  625. if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
  626. return false;
  627. } // x * y / z --> (x * y) / z
  628. // x / y * z --> (x / y) * z
  629. if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
  630. return false;
  631. } // x << y << z --> (x << y) << z
  632. if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
  633. return false;
  634. }
  635. return true;
  636. }
  637. function isBitwiseOperator(operator) {
  638. return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
  639. } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
  640. // holds) `function`, `class`, or `do {}`. Will be overzealous if there's
  641. // already necessary grouping parentheses.
  642. function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
  643. node = getLeftMost(node);
  644. switch (node.type) {
  645. case "FunctionExpression":
  646. case "ClassExpression":
  647. case "DoExpression":
  648. return forbidFunctionClassAndDoExpr;
  649. case "ObjectExpression":
  650. return true;
  651. case "MemberExpression":
  652. case "OptionalMemberExpression":
  653. return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
  654. case "TaggedTemplateExpression":
  655. if (node.tag.type === "FunctionExpression") {
  656. // IIFEs are always already parenthesized
  657. return false;
  658. }
  659. return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
  660. case "CallExpression":
  661. case "OptionalCallExpression":
  662. if (node.callee.type === "FunctionExpression") {
  663. // IIFEs are always already parenthesized
  664. return false;
  665. }
  666. return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
  667. case "ConditionalExpression":
  668. return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
  669. case "UpdateExpression":
  670. return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
  671. case "BindExpression":
  672. return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
  673. case "SequenceExpression":
  674. return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
  675. case "TSAsExpression":
  676. return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
  677. default:
  678. return false;
  679. }
  680. }
  681. function getLeftMost(node) {
  682. if (node.left) {
  683. return getLeftMost(node.left);
  684. }
  685. return node;
  686. }
  687. /**
  688. * @param {string} value
  689. * @param {number} tabWidth
  690. * @param {number=} startIndex
  691. * @returns {number}
  692. */
  693. function getAlignmentSize(value, tabWidth, startIndex) {
  694. startIndex = startIndex || 0;
  695. var size = 0;
  696. for (var i = startIndex; i < value.length; ++i) {
  697. if (value[i] === "\t") {
  698. // Tabs behave in a way that they are aligned to the nearest
  699. // multiple of tabWidth:
  700. // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
  701. // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
  702. size = size + tabWidth - size % tabWidth;
  703. } else {
  704. size++;
  705. }
  706. }
  707. return size;
  708. }
  709. /**
  710. * @param {string} value
  711. * @param {number} tabWidth
  712. * @returns {number}
  713. */
  714. function getIndentSize(value, tabWidth) {
  715. var lastNewlineIndex = value.lastIndexOf("\n");
  716. if (lastNewlineIndex === -1) {
  717. return 0;
  718. }
  719. return getAlignmentSize( // All the leading whitespaces
  720. value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth);
  721. }
  722. /**
  723. * @typedef {'"' | "'"} Quote
  724. */
  725. /**
  726. *
  727. * @param {string} raw
  728. * @param {Quote} preferredQuote
  729. * @returns {Quote}
  730. */
  731. function getPreferredQuote(raw, preferredQuote) {
  732. // `rawContent` is the string exactly like it appeared in the input source
  733. // code, without its enclosing quotes.
  734. var rawContent = raw.slice(1, -1);
  735. /** @type {{ quote: '"', regex: RegExp }} */
  736. var double = {
  737. quote: '"',
  738. regex: /"/g
  739. };
  740. /** @type {{ quote: "'", regex: RegExp }} */
  741. var single = {
  742. quote: "'",
  743. regex: /'/g
  744. };
  745. var preferred = preferredQuote === "'" ? single : double;
  746. var alternate = preferred === single ? double : single;
  747. var result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
  748. // the string, we might want to enclose with the alternate quote instead, to
  749. // minimize the number of escaped quotes.
  750. if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
  751. var numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
  752. var numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
  753. result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
  754. }
  755. return result;
  756. }
  757. function printString(raw, options, isDirectiveLiteral) {
  758. // `rawContent` is the string exactly like it appeared in the input source
  759. // code, without its enclosing quotes.
  760. var rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
  761. // the quotes on a DirectiveLiteral.
  762. var canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
  763. /** @type {Quote} */
  764. var enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
  765. // change the escape sequences they use.
  766. // See https://github.com/prettier/prettier/issues/1555
  767. // and https://tc39.github.io/ecma262/#directive-prologue
  768. if (isDirectiveLiteral) {
  769. if (canChangeDirectiveQuotes) {
  770. return enclosingQuote + rawContent + enclosingQuote;
  771. }
  772. return raw;
  773. } // It might sound unnecessary to use `makeString` even if the string already
  774. // is enclosed with `enclosingQuote`, but it isn't. The string could contain
  775. // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
  776. // sure that we consistently output the minimum amount of escaped quotes.
  777. return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
  778. }
  779. /**
  780. * @param {string} rawContent
  781. * @param {Quote} enclosingQuote
  782. * @param {boolean=} unescapeUnnecessaryEscapes
  783. * @returns {string}
  784. */
  785. function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
  786. var otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
  787. var regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to
  788. // enclose `rawContent` with `enclosingQuote`.
  789. var newContent = rawContent.replace(regex, function (match, escaped, quote) {
  790. // If we matched an escape, and the escaped character is a quote of the
  791. // other type than we intend to enclose the string with, there's no need for
  792. // it to be escaped, so return it _without_ the backslash.
  793. if (escaped === otherQuote) {
  794. return escaped;
  795. } // If we matched an unescaped quote and it is of the _same_ type as we
  796. // intend to enclose the string with, it must be escaped, so return it with
  797. // a backslash.
  798. if (quote === enclosingQuote) {
  799. return "\\" + quote;
  800. }
  801. if (quote) {
  802. return quote;
  803. } // Unescape any unnecessarily escaped character.
  804. // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
  805. return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped;
  806. });
  807. return enclosingQuote + newContent + enclosingQuote;
  808. }
  809. function printNumber(rawNumber) {
  810. return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
  811. .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
  812. .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
  813. .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
  814. .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
  815. .replace(/\.(?=e|$)/, "");
  816. }
  817. /**
  818. * @param {string} str
  819. * @param {string} target
  820. * @returns {number}
  821. */
  822. function getMaxContinuousCount(str, target) {
  823. var results = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g"));
  824. if (results === null) {
  825. return 0;
  826. }
  827. return results.reduce(function (maxCount, result) {
  828. return Math.max(maxCount, result.length / target.length);
  829. }, 0);
  830. }
  831. function getMinNotPresentContinuousCount(str, target) {
  832. var matches = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g"));
  833. if (matches === null) {
  834. return 0;
  835. }
  836. var countPresent = new Map();
  837. var max = 0;
  838. var _iteratorNormalCompletion = true;
  839. var _didIteratorError = false;
  840. var _iteratorError = undefined;
  841. try {
  842. for (var _iterator = matches[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  843. var match = _step.value;
  844. var count = match.length / target.length;
  845. countPresent.set(count, true);
  846. if (count > max) {
  847. max = count;
  848. }
  849. }
  850. } catch (err) {
  851. _didIteratorError = true;
  852. _iteratorError = err;
  853. } finally {
  854. try {
  855. if (!_iteratorNormalCompletion && _iterator.return != null) {
  856. _iterator.return();
  857. }
  858. } finally {
  859. if (_didIteratorError) {
  860. throw _iteratorError;
  861. }
  862. }
  863. }
  864. for (var i = 1; i < max; i++) {
  865. if (!countPresent.get(i)) {
  866. return i;
  867. }
  868. }
  869. return max + 1;
  870. }
  871. /**
  872. * @param {string} text
  873. * @returns {number}
  874. */
  875. function getStringWidth(text) {
  876. if (!text) {
  877. return 0;
  878. } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
  879. if (!notAsciiRegex.test(text)) {
  880. return text.length;
  881. }
  882. return stringWidth_1(text);
  883. }
  884. function hasIgnoreComment(path) {
  885. var node = path.getValue();
  886. return hasNodeIgnoreComment(node);
  887. }
  888. function hasNodeIgnoreComment(node) {
  889. return node && node.comments && node.comments.length > 0 && node.comments.some(function (comment) {
  890. return comment.value.trim() === "prettier-ignore";
  891. });
  892. }
  893. function matchAncestorTypes(path, types, index) {
  894. index = index || 0;
  895. types = types.slice();
  896. while (types.length) {
  897. var parent = path.getParentNode(index);
  898. var type = types.shift();
  899. if (!parent || parent.type !== type) {
  900. return false;
  901. }
  902. index++;
  903. }
  904. return true;
  905. }
  906. function addCommentHelper(node, comment) {
  907. var comments = node.comments || (node.comments = []);
  908. comments.push(comment);
  909. comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
  910. // We already "print" it via the raw text, we don't need to re-print it as a
  911. // comment
  912. if (node.type === "JSXText") {
  913. comment.printed = true;
  914. }
  915. }
  916. function addLeadingComment(node, comment) {
  917. comment.leading = true;
  918. comment.trailing = false;
  919. addCommentHelper(node, comment);
  920. }
  921. function addDanglingComment(node, comment) {
  922. comment.leading = false;
  923. comment.trailing = false;
  924. addCommentHelper(node, comment);
  925. }
  926. function addTrailingComment(node, comment) {
  927. comment.leading = false;
  928. comment.trailing = true;
  929. addCommentHelper(node, comment);
  930. }
  931. function isWithinParentArrayProperty(path, propertyName) {
  932. var node = path.getValue();
  933. var parent = path.getParentNode();
  934. if (parent == null) {
  935. return false;
  936. }
  937. if (!Array.isArray(parent[propertyName])) {
  938. return false;
  939. }
  940. var key = path.getName();
  941. return parent[propertyName][key] === node;
  942. }
  943. function replaceEndOfLineWith(text, replacement) {
  944. var parts = [];
  945. var _iteratorNormalCompletion2 = true;
  946. var _didIteratorError2 = false;
  947. var _iteratorError2 = undefined;
  948. try {
  949. for (var _iterator2 = text.split("\n")[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  950. var part = _step2.value;
  951. if (parts.length !== 0) {
  952. parts.push(replacement);
  953. }
  954. parts.push(part);
  955. }
  956. } catch (err) {
  957. _didIteratorError2 = true;
  958. _iteratorError2 = err;
  959. } finally {
  960. try {
  961. if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
  962. _iterator2.return();
  963. }
  964. } finally {
  965. if (_didIteratorError2) {
  966. throw _iteratorError2;
  967. }
  968. }
  969. }
  970. return parts;
  971. }
  972. var util = {
  973. replaceEndOfLineWith: replaceEndOfLineWith,
  974. getStringWidth: getStringWidth,
  975. getMaxContinuousCount: getMaxContinuousCount,
  976. getMinNotPresentContinuousCount: getMinNotPresentContinuousCount,
  977. getPrecedence: getPrecedence,
  978. shouldFlatten: shouldFlatten,
  979. isBitwiseOperator: isBitwiseOperator,
  980. isExportDeclaration: isExportDeclaration,
  981. getParentExportDeclaration: getParentExportDeclaration,
  982. getPenultimate: getPenultimate,
  983. getLast: getLast,
  984. getNextNonSpaceNonCommentCharacterIndexWithStartIndex: getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
  985. getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex,
  986. getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter,
  987. skip: skip,
  988. skipWhitespace: skipWhitespace,
  989. skipSpaces: skipSpaces,
  990. skipToLineEnd: skipToLineEnd,
  991. skipEverythingButNewLine: skipEverythingButNewLine,
  992. skipInlineComment: skipInlineComment,
  993. skipTrailingComment: skipTrailingComment,
  994. skipNewline: skipNewline,
  995. isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex,
  996. isNextLineEmpty: isNextLineEmpty,
  997. isPreviousLineEmpty: isPreviousLineEmpty,
  998. hasNewline: hasNewline,
  999. hasNewlineInRange: hasNewlineInRange,
  1000. hasSpaces: hasSpaces,
  1001. setLocStart: setLocStart,
  1002. setLocEnd: setLocEnd,
  1003. startsWithNoLookaheadToken: startsWithNoLookaheadToken,
  1004. getAlignmentSize: getAlignmentSize,
  1005. getIndentSize: getIndentSize,
  1006. getPreferredQuote: getPreferredQuote,
  1007. printString: printString,
  1008. printNumber: printNumber,
  1009. hasIgnoreComment: hasIgnoreComment,
  1010. hasNodeIgnoreComment: hasNodeIgnoreComment,
  1011. makeString: makeString,
  1012. matchAncestorTypes: matchAncestorTypes,
  1013. addLeadingComment: addLeadingComment,
  1014. addDanglingComment: addDanglingComment,
  1015. addTrailingComment: addTrailingComment,
  1016. isWithinParentArrayProperty: isWithinParentArrayProperty
  1017. };
  1018. function guessEndOfLine(text) {
  1019. var index = text.indexOf("\r");
  1020. if (index >= 0) {
  1021. return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
  1022. }
  1023. return "lf";
  1024. }
  1025. function convertEndOfLineToChars(value) {
  1026. switch (value) {
  1027. case "cr":
  1028. return "\r";
  1029. case "crlf":
  1030. return "\r\n";
  1031. default:
  1032. return "\n";
  1033. }
  1034. }
  1035. var endOfLine = {
  1036. guessEndOfLine: guessEndOfLine,
  1037. convertEndOfLineToChars: convertEndOfLineToChars
  1038. };
  1039. var getStringWidth$1 = util.getStringWidth;
  1040. var convertEndOfLineToChars$1 = endOfLine.convertEndOfLineToChars;
  1041. var concat$1 = docBuilders.concat,
  1042. fill$1 = docBuilders.fill,
  1043. cursor$1 = docBuilders.cursor;
  1044. /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
  1045. var groupModeMap;
  1046. var MODE_BREAK = 1;
  1047. var MODE_FLAT = 2;
  1048. function rootIndent() {
  1049. return {
  1050. value: "",
  1051. length: 0,
  1052. queue: []
  1053. };
  1054. }
  1055. function makeIndent(ind, options) {
  1056. return generateInd(ind, {
  1057. type: "indent"
  1058. }, options);
  1059. }
  1060. function makeAlign(ind, n, options) {
  1061. return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, {
  1062. type: "dedent"
  1063. }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, {
  1064. root: ind
  1065. }) : typeof n === "string" ? generateInd(ind, {
  1066. type: "stringAlign",
  1067. n: n
  1068. }, options) : generateInd(ind, {
  1069. type: "numberAlign",
  1070. n: n
  1071. }, options);
  1072. }
  1073. function generateInd(ind, newPart, options) {
  1074. var queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
  1075. var value = "";
  1076. var length = 0;
  1077. var lastTabs = 0;
  1078. var lastSpaces = 0;
  1079. var _iteratorNormalCompletion = true;
  1080. var _didIteratorError = false;
  1081. var _iteratorError = undefined;
  1082. try {
  1083. for (var _iterator = queue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  1084. var part = _step.value;
  1085. switch (part.type) {
  1086. case "indent":
  1087. flush();
  1088. if (options.useTabs) {
  1089. addTabs(1);
  1090. } else {
  1091. addSpaces(options.tabWidth);
  1092. }
  1093. break;
  1094. case "stringAlign":
  1095. flush();
  1096. value += part.n;
  1097. length += part.n.length;
  1098. break;
  1099. case "numberAlign":
  1100. lastTabs += 1;
  1101. lastSpaces += part.n;
  1102. break;
  1103. /* istanbul ignore next */
  1104. default:
  1105. throw new Error("Unexpected type '".concat(part.type, "'"));
  1106. }
  1107. }
  1108. } catch (err) {
  1109. _didIteratorError = true;
  1110. _iteratorError = err;
  1111. } finally {
  1112. try {
  1113. if (!_iteratorNormalCompletion && _iterator.return != null) {
  1114. _iterator.return();
  1115. }
  1116. } finally {
  1117. if (_didIteratorError) {
  1118. throw _iteratorError;
  1119. }
  1120. }
  1121. }
  1122. flushSpaces();
  1123. return Object.assign({}, ind, {
  1124. value: value,
  1125. length: length,
  1126. queue: queue
  1127. });
  1128. function addTabs(count) {
  1129. value += "\t".repeat(count);
  1130. length += options.tabWidth * count;
  1131. }
  1132. function addSpaces(count) {
  1133. value += " ".repeat(count);
  1134. length += count;
  1135. }
  1136. function flush() {
  1137. if (options.useTabs) {
  1138. flushTabs();
  1139. } else {
  1140. flushSpaces();
  1141. }
  1142. }
  1143. function flushTabs() {
  1144. if (lastTabs > 0) {
  1145. addTabs(lastTabs);
  1146. }
  1147. resetLast();
  1148. }
  1149. function flushSpaces() {
  1150. if (lastSpaces > 0) {
  1151. addSpaces(lastSpaces);
  1152. }
  1153. resetLast();
  1154. }
  1155. function resetLast() {
  1156. lastTabs = 0;
  1157. lastSpaces = 0;
  1158. }
  1159. }
  1160. function trim$1(out) {
  1161. if (out.length === 0) {
  1162. return 0;
  1163. }
  1164. var trimCount = 0; // Trim whitespace at the end of line
  1165. while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) {
  1166. trimCount += out.pop().length;
  1167. }
  1168. if (out.length && typeof out[out.length - 1] === "string") {
  1169. var trimmed = out[out.length - 1].replace(/[ \t]*$/, "");
  1170. trimCount += out[out.length - 1].length - trimmed.length;
  1171. out[out.length - 1] = trimmed;
  1172. }
  1173. return trimCount;
  1174. }
  1175. function fits(next, restCommands, width, options, mustBeFlat) {
  1176. var restIdx = restCommands.length;
  1177. var cmds = [next]; // `out` is only used for width counting because `trim` requires to look
  1178. // backwards for space characters.
  1179. var out = [];
  1180. while (width >= 0) {
  1181. if (cmds.length === 0) {
  1182. if (restIdx === 0) {
  1183. return true;
  1184. }
  1185. cmds.push(restCommands[restIdx - 1]);
  1186. restIdx--;
  1187. continue;
  1188. }
  1189. var x = cmds.pop();
  1190. var ind = x[0];
  1191. var mode = x[1];
  1192. var doc = x[2];
  1193. if (typeof doc === "string") {
  1194. out.push(doc);
  1195. width -= getStringWidth$1(doc);
  1196. } else {
  1197. switch (doc.type) {
  1198. case "concat":
  1199. for (var i = doc.parts.length - 1; i >= 0; i--) {
  1200. cmds.push([ind, mode, doc.parts[i]]);
  1201. }
  1202. break;
  1203. case "indent":
  1204. cmds.push([makeIndent(ind, options), mode, doc.contents]);
  1205. break;
  1206. case "align":
  1207. cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
  1208. break;
  1209. case "trim":
  1210. width += trim$1(out);
  1211. break;
  1212. case "group":
  1213. if (mustBeFlat && doc.break) {
  1214. return false;
  1215. }
  1216. cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
  1217. if (doc.id) {
  1218. groupModeMap[doc.id] = cmds[cmds.length - 1][1];
  1219. }
  1220. break;
  1221. case "fill":
  1222. for (var _i = doc.parts.length - 1; _i >= 0; _i--) {
  1223. cmds.push([ind, mode, doc.parts[_i]]);
  1224. }
  1225. break;
  1226. case "if-break":
  1227. {
  1228. var groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
  1229. if (groupMode === MODE_BREAK) {
  1230. if (doc.breakContents) {
  1231. cmds.push([ind, mode, doc.breakContents]);
  1232. }
  1233. }
  1234. if (groupMode === MODE_FLAT) {
  1235. if (doc.flatContents) {
  1236. cmds.push([ind, mode, doc.flatContents]);
  1237. }
  1238. }
  1239. break;
  1240. }
  1241. case "line":
  1242. switch (mode) {
  1243. // fallthrough
  1244. case MODE_FLAT:
  1245. if (!doc.hard) {
  1246. if (!doc.soft) {
  1247. out.push(" ");
  1248. width -= 1;
  1249. }
  1250. break;
  1251. }
  1252. return true;
  1253. case MODE_BREAK:
  1254. return true;
  1255. }
  1256. break;
  1257. }
  1258. }
  1259. }
  1260. return false;
  1261. }
  1262. function printDocToString(doc, options) {
  1263. groupModeMap = {};
  1264. var width = options.printWidth;
  1265. var newLine = convertEndOfLineToChars$1(options.endOfLine);
  1266. var pos = 0; // cmds is basically a stack. We've turned a recursive call into a
  1267. // while loop which is much faster. The while loop below adds new
  1268. // cmds to the array instead of recursively calling `print`.
  1269. var cmds = [[rootIndent(), MODE_BREAK, doc]];
  1270. var out = [];
  1271. var shouldRemeasure = false;
  1272. var lineSuffix = [];
  1273. while (cmds.length !== 0) {
  1274. var x = cmds.pop();
  1275. var ind = x[0];
  1276. var mode = x[1];
  1277. var _doc = x[2];
  1278. if (typeof _doc === "string") {
  1279. out.push(_doc);
  1280. pos += getStringWidth$1(_doc);
  1281. } else {
  1282. switch (_doc.type) {
  1283. case "cursor":
  1284. out.push(cursor$1.placeholder);
  1285. break;
  1286. case "concat":
  1287. for (var i = _doc.parts.length - 1; i >= 0; i--) {
  1288. cmds.push([ind, mode, _doc.parts[i]]);
  1289. }
  1290. break;
  1291. case "indent":
  1292. cmds.push([makeIndent(ind, options), mode, _doc.contents]);
  1293. break;
  1294. case "align":
  1295. cmds.push([makeAlign(ind, _doc.n, options), mode, _doc.contents]);
  1296. break;
  1297. case "trim":
  1298. pos -= trim$1(out);
  1299. break;
  1300. case "group":
  1301. switch (mode) {
  1302. case MODE_FLAT:
  1303. if (!shouldRemeasure) {
  1304. cmds.push([ind, _doc.break ? MODE_BREAK : MODE_FLAT, _doc.contents]);
  1305. break;
  1306. }
  1307. // fallthrough
  1308. case MODE_BREAK:
  1309. {
  1310. shouldRemeasure = false;
  1311. var next = [ind, MODE_FLAT, _doc.contents];
  1312. var rem = width - pos;
  1313. if (!_doc.break && fits(next, cmds, rem, options)) {
  1314. cmds.push(next);
  1315. } else {
  1316. // Expanded states are a rare case where a document
  1317. // can manually provide multiple representations of
  1318. // itself. It provides an array of documents
  1319. // going from the least expanded (most flattened)
  1320. // representation first to the most expanded. If a
  1321. // group has these, we need to manually go through
  1322. // these states and find the first one that fits.
  1323. if (_doc.expandedStates) {
  1324. var mostExpanded = _doc.expandedStates[_doc.expandedStates.length - 1];
  1325. if (_doc.break) {
  1326. cmds.push([ind, MODE_BREAK, mostExpanded]);
  1327. break;
  1328. } else {
  1329. for (var _i2 = 1; _i2 < _doc.expandedStates.length + 1; _i2++) {
  1330. if (_i2 >= _doc.expandedStates.length) {
  1331. cmds.push([ind, MODE_BREAK, mostExpanded]);
  1332. break;
  1333. } else {
  1334. var state = _doc.expandedStates[_i2];
  1335. var cmd = [ind, MODE_FLAT, state];
  1336. if (fits(cmd, cmds, rem, options)) {
  1337. cmds.push(cmd);
  1338. break;
  1339. }
  1340. }
  1341. }
  1342. }
  1343. } else {
  1344. cmds.push([ind, MODE_BREAK, _doc.contents]);
  1345. }
  1346. }
  1347. break;
  1348. }
  1349. }
  1350. if (_doc.id) {
  1351. groupModeMap[_doc.id] = cmds[cmds.length - 1][1];
  1352. }
  1353. break;
  1354. // Fills each line with as much code as possible before moving to a new
  1355. // line with the same indentation.
  1356. //
  1357. // Expects doc.parts to be an array of alternating content and
  1358. // whitespace. The whitespace contains the linebreaks.
  1359. //
  1360. // For example:
  1361. // ["I", line, "love", line, "monkeys"]
  1362. // or
  1363. // [{ type: group, ... }, softline, { type: group, ... }]
  1364. //
  1365. // It uses this parts structure to handle three main layout cases:
  1366. // * The first two content items fit on the same line without
  1367. // breaking
  1368. // -> output the first content item and the whitespace "flat".
  1369. // * Only the first content item fits on the line without breaking
  1370. // -> output the first content item "flat" and the whitespace with
  1371. // "break".
  1372. // * Neither content item fits on the line without breaking
  1373. // -> output the first content item and the whitespace with "break".
  1374. case "fill":
  1375. {
  1376. var _rem = width - pos;
  1377. var parts = _doc.parts;
  1378. if (parts.length === 0) {
  1379. break;
  1380. }
  1381. var content = parts[0];
  1382. var contentFlatCmd = [ind, MODE_FLAT, content];
  1383. var contentBreakCmd = [ind, MODE_BREAK, content];
  1384. var contentFits = fits(contentFlatCmd, [], _rem, options, true);
  1385. if (parts.length === 1) {
  1386. if (contentFits) {
  1387. cmds.push(contentFlatCmd);
  1388. } else {
  1389. cmds.push(contentBreakCmd);
  1390. }
  1391. break;
  1392. }
  1393. var whitespace = parts[1];
  1394. var whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
  1395. var whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
  1396. if (parts.length === 2) {
  1397. if (contentFits) {
  1398. cmds.push(whitespaceFlatCmd);
  1399. cmds.push(contentFlatCmd);
  1400. } else {
  1401. cmds.push(whitespaceBreakCmd);
  1402. cmds.push(contentBreakCmd);
  1403. }
  1404. break;
  1405. } // At this point we've handled the first pair (context, separator)
  1406. // and will create a new fill doc for the rest of the content.
  1407. // Ideally we wouldn't mutate the array here but coping all the
  1408. // elements to a new array would make this algorithm quadratic,
  1409. // which is unusable for large arrays (e.g. large texts in JSX).
  1410. parts.splice(0, 2);
  1411. var remainingCmd = [ind, mode, fill$1(parts)];
  1412. var secondContent = parts[0];
  1413. var firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
  1414. var firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], _rem, options, true);
  1415. if (firstAndSecondContentFits) {
  1416. cmds.push(remainingCmd);
  1417. cmds.push(whitespaceFlatCmd);
  1418. cmds.push(contentFlatCmd);
  1419. } else if (contentFits) {
  1420. cmds.push(remainingCmd);
  1421. cmds.push(whitespaceBreakCmd);
  1422. cmds.push(contentFlatCmd);
  1423. } else {
  1424. cmds.push(remainingCmd);
  1425. cmds.push(whitespaceBreakCmd);
  1426. cmds.push(contentBreakCmd);
  1427. }
  1428. break;
  1429. }
  1430. case "if-break":
  1431. {
  1432. var groupMode = _doc.groupId ? groupModeMap[_doc.groupId] : mode;
  1433. if (groupMode === MODE_BREAK) {
  1434. if (_doc.breakContents) {
  1435. cmds.push([ind, mode, _doc.breakContents]);
  1436. }
  1437. }
  1438. if (groupMode === MODE_FLAT) {
  1439. if (_doc.flatContents) {
  1440. cmds.push([ind, mode, _doc.flatContents]);
  1441. }
  1442. }
  1443. break;
  1444. }
  1445. case "line-suffix":
  1446. lineSuffix.push([ind, mode, _doc.contents]);
  1447. break;
  1448. case "line-suffix-boundary":
  1449. if (lineSuffix.length > 0) {
  1450. cmds.push([ind, mode, {
  1451. type: "line",
  1452. hard: true
  1453. }]);
  1454. }
  1455. break;
  1456. case "line":
  1457. switch (mode) {
  1458. case MODE_FLAT:
  1459. if (!_doc.hard) {
  1460. if (!_doc.soft) {
  1461. out.push(" ");
  1462. pos += 1;
  1463. }
  1464. break;
  1465. } else {
  1466. // This line was forced into the output even if we
  1467. // were in flattened mode, so we need to tell the next
  1468. // group that no matter what, it needs to remeasure
  1469. // because the previous measurement didn't accurately
  1470. // capture the entire expression (this is necessary
  1471. // for nested groups)
  1472. shouldRemeasure = true;
  1473. }
  1474. // fallthrough
  1475. case MODE_BREAK:
  1476. if (lineSuffix.length) {
  1477. cmds.push([ind, mode, _doc]);
  1478. [].push.apply(cmds, lineSuffix.reverse());
  1479. lineSuffix = [];
  1480. break;
  1481. }
  1482. if (_doc.literal) {
  1483. if (ind.root) {
  1484. out.push(newLine, ind.root.value);
  1485. pos = ind.root.length;
  1486. } else {
  1487. out.push(newLine);
  1488. pos = 0;
  1489. }
  1490. } else {
  1491. pos -= trim$1(out);
  1492. out.push(newLine + ind.value);
  1493. pos = ind.length;
  1494. }
  1495. break;
  1496. }
  1497. break;
  1498. }
  1499. }
  1500. }
  1501. var cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
  1502. if (cursorPlaceholderIndex !== -1) {
  1503. var otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
  1504. var beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
  1505. var aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
  1506. var afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
  1507. return {
  1508. formatted: beforeCursor + aroundCursor + afterCursor,
  1509. cursorNodeStart: beforeCursor.length,
  1510. cursorNodeText: aroundCursor
  1511. };
  1512. }
  1513. return {
  1514. formatted: out.join("")
  1515. };
  1516. }
  1517. var docPrinter = {
  1518. printDocToString: printDocToString
  1519. };
  1520. var traverseDocOnExitStackMarker = {};
  1521. function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
  1522. var docsStack = [doc];
  1523. while (docsStack.length !== 0) {
  1524. var _doc = docsStack.pop();
  1525. if (_doc === traverseDocOnExitStackMarker) {
  1526. onExit(docsStack.pop());
  1527. continue;
  1528. }
  1529. var shouldRecurse = true;
  1530. if (onEnter) {
  1531. if (onEnter(_doc) === false) {
  1532. shouldRecurse = false;
  1533. }
  1534. }
  1535. if (onExit) {
  1536. docsStack.push(_doc);
  1537. docsStack.push(traverseDocOnExitStackMarker);
  1538. }
  1539. if (shouldRecurse) {
  1540. // When there are multiple parts to process,
  1541. // the parts need to be pushed onto the stack in reverse order,
  1542. // so that they are processed in the original order
  1543. // when the stack is popped.
  1544. if (_doc.type === "concat" || _doc.type === "fill") {
  1545. for (var ic = _doc.parts.length, i = ic - 1; i >= 0; --i) {
  1546. docsStack.push(_doc.parts[i]);
  1547. }
  1548. } else if (_doc.type === "if-break") {
  1549. if (_doc.flatContents) {
  1550. docsStack.push(_doc.flatContents);
  1551. }
  1552. if (_doc.breakContents) {
  1553. docsStack.push(_doc.breakContents);
  1554. }
  1555. } else if (_doc.type === "group" && _doc.expandedStates) {
  1556. if (shouldTraverseConditionalGroups) {
  1557. for (var _ic = _doc.expandedStates.length, _i = _ic - 1; _i >= 0; --_i) {
  1558. docsStack.push(_doc.expandedStates[_i]);
  1559. }
  1560. } else {
  1561. docsStack.push(_doc.contents);
  1562. }
  1563. } else if (_doc.contents) {
  1564. docsStack.push(_doc.contents);
  1565. }
  1566. }
  1567. }
  1568. }
  1569. function mapDoc(doc, cb) {
  1570. if (doc.type === "concat" || doc.type === "fill") {
  1571. var parts = doc.parts.map(function (part) {
  1572. return mapDoc(part, cb);
  1573. });
  1574. return cb(Object.assign({}, doc, {
  1575. parts: parts
  1576. }));
  1577. } else if (doc.type === "if-break") {
  1578. var breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
  1579. var flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
  1580. return cb(Object.assign({}, doc, {
  1581. breakContents: breakContents,
  1582. flatContents: flatContents
  1583. }));
  1584. } else if (doc.contents) {
  1585. var contents = mapDoc(doc.contents, cb);
  1586. return cb(Object.assign({}, doc, {
  1587. contents: contents
  1588. }));
  1589. }
  1590. return cb(doc);
  1591. }
  1592. function findInDoc(doc, fn, defaultValue) {
  1593. var result = defaultValue;
  1594. var hasStopped = false;
  1595. function findInDocOnEnterFn(doc) {
  1596. var maybeResult = fn(doc);
  1597. if (maybeResult !== undefined) {
  1598. hasStopped = true;
  1599. result = maybeResult;
  1600. }
  1601. if (hasStopped) {
  1602. return false;
  1603. }
  1604. }
  1605. traverseDoc(doc, findInDocOnEnterFn);
  1606. return result;
  1607. }
  1608. function isEmpty(n) {
  1609. return typeof n === "string" && n.length === 0;
  1610. }
  1611. function isLineNextFn(doc) {
  1612. if (typeof doc === "string") {
  1613. return false;
  1614. }
  1615. if (doc.type === "line") {
  1616. return true;
  1617. }
  1618. }
  1619. function isLineNext(doc) {
  1620. return findInDoc(doc, isLineNextFn, false);
  1621. }
  1622. function willBreakFn(doc) {
  1623. if (doc.type === "group" && doc.break) {
  1624. return true;
  1625. }
  1626. if (doc.type === "line" && doc.hard) {
  1627. return true;
  1628. }
  1629. if (doc.type === "break-parent") {
  1630. return true;
  1631. }
  1632. }
  1633. function willBreak(doc) {
  1634. return findInDoc(doc, willBreakFn, false);
  1635. }
  1636. function breakParentGroup(groupStack) {
  1637. if (groupStack.length > 0) {
  1638. var parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
  1639. // the user is expected to manually handle what breaks.
  1640. if (!parentGroup.expandedStates) {
  1641. parentGroup.break = true;
  1642. }
  1643. }
  1644. return null;
  1645. }
  1646. function propagateBreaks(doc) {
  1647. var alreadyVisitedSet = new Set();
  1648. var groupStack = [];
  1649. function propagateBreaksOnEnterFn(doc) {
  1650. if (doc.type === "break-parent") {
  1651. breakParentGroup(groupStack);
  1652. }
  1653. if (doc.type === "group") {
  1654. groupStack.push(doc);
  1655. if (alreadyVisitedSet.has(doc)) {
  1656. return false;
  1657. }
  1658. alreadyVisitedSet.add(doc);
  1659. }
  1660. }
  1661. function propagateBreaksOnExitFn(doc) {
  1662. if (doc.type === "group") {
  1663. var group = groupStack.pop();
  1664. if (group.break) {
  1665. breakParentGroup(groupStack);
  1666. }
  1667. }
  1668. }
  1669. traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
  1670. /* shouldTraverseConditionalGroups */
  1671. true);
  1672. }
  1673. function removeLinesFn(doc) {
  1674. // Force this doc into flat mode by statically converting all
  1675. // lines into spaces (or soft lines into nothing). Hard lines
  1676. // should still output because there's too great of a chance
  1677. // of breaking existing assumptions otherwise.
  1678. if (doc.type === "line" && !doc.hard) {
  1679. return doc.soft ? "" : " ";
  1680. } else if (doc.type === "if-break") {
  1681. return doc.flatContents || "";
  1682. }
  1683. return doc;
  1684. }
  1685. function removeLines(doc) {
  1686. return mapDoc(doc, removeLinesFn);
  1687. }
  1688. function stripTrailingHardline(doc) {
  1689. // HACK remove ending hardline, original PR: #1984
  1690. if (doc.type === "concat" && doc.parts.length !== 0) {
  1691. var lastPart = doc.parts[doc.parts.length - 1];
  1692. if (lastPart.type === "concat") {
  1693. if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
  1694. return {
  1695. type: "concat",
  1696. parts: doc.parts.slice(0, -1)
  1697. };
  1698. }
  1699. return {
  1700. type: "concat",
  1701. parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
  1702. };
  1703. }
  1704. }
  1705. return doc;
  1706. }
  1707. var docUtils = {
  1708. isEmpty: isEmpty,
  1709. willBreak: willBreak,
  1710. isLineNext: isLineNext,
  1711. traverseDoc: traverseDoc,
  1712. findInDoc: findInDoc,
  1713. mapDoc: mapDoc,
  1714. propagateBreaks: propagateBreaks,
  1715. removeLines: removeLines,
  1716. stripTrailingHardline: stripTrailingHardline
  1717. };
  1718. function flattenDoc(doc) {
  1719. if (doc.type === "concat") {
  1720. var res = [];
  1721. for (var i = 0; i < doc.parts.length; ++i) {
  1722. var doc2 = doc.parts[i];
  1723. if (typeof doc2 !== "string" && doc2.type === "concat") {
  1724. [].push.apply(res, flattenDoc(doc2).parts);
  1725. } else {
  1726. var flattened = flattenDoc(doc2);
  1727. if (flattened !== "") {
  1728. res.push(flattened);
  1729. }
  1730. }
  1731. }
  1732. return Object.assign({}, doc, {
  1733. parts: res
  1734. });
  1735. } else if (doc.type === "if-break") {
  1736. return Object.assign({}, doc, {
  1737. breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
  1738. flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
  1739. });
  1740. } else if (doc.type === "group") {
  1741. return Object.assign({}, doc, {
  1742. contents: flattenDoc(doc.contents),
  1743. expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
  1744. });
  1745. } else if (doc.contents) {
  1746. return Object.assign({}, doc, {
  1747. contents: flattenDoc(doc.contents)
  1748. });
  1749. }
  1750. return doc;
  1751. }
  1752. function printDoc(doc) {
  1753. if (typeof doc === "string") {
  1754. return JSON.stringify(doc);
  1755. }
  1756. if (doc.type === "line") {
  1757. if (doc.literal) {
  1758. return "literalline";
  1759. }
  1760. if (doc.hard) {
  1761. return "hardline";
  1762. }
  1763. if (doc.soft) {
  1764. return "softline";
  1765. }
  1766. return "line";
  1767. }
  1768. if (doc.type === "break-parent") {
  1769. return "breakParent";
  1770. }
  1771. if (doc.type === "trim") {
  1772. return "trim";
  1773. }
  1774. if (doc.type === "concat") {
  1775. return "[" + doc.parts.map(printDoc).join(", ") + "]";
  1776. }
  1777. if (doc.type === "indent") {
  1778. return "indent(" + printDoc(doc.contents) + ")";
  1779. }
  1780. if (doc.type === "align") {
  1781. return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")";
  1782. }
  1783. if (doc.type === "if-break") {
  1784. return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
  1785. }
  1786. if (doc.type === "group") {
  1787. if (doc.expandedStates) {
  1788. return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
  1789. }
  1790. return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
  1791. }
  1792. if (doc.type === "fill") {
  1793. return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
  1794. }
  1795. if (doc.type === "line-suffix") {
  1796. return "lineSuffix(" + printDoc(doc.contents) + ")";
  1797. }
  1798. if (doc.type === "line-suffix-boundary") {
  1799. return "lineSuffixBoundary";
  1800. }
  1801. throw new Error("Unknown doc type " + doc.type);
  1802. }
  1803. var docDebug = {
  1804. printDocToDebug: function printDocToDebug(doc) {
  1805. return printDoc(flattenDoc(doc));
  1806. }
  1807. };
  1808. var doc = {
  1809. builders: docBuilders,
  1810. printer: docPrinter,
  1811. utils: docUtils,
  1812. debug: docDebug
  1813. };
  1814. var doc_1 = doc.builders;
  1815. var doc_2 = doc.printer;
  1816. var doc_3 = doc.utils;
  1817. var doc_4 = doc.debug;
  1818. exports.builders = doc_1;
  1819. exports.debug = doc_4;
  1820. exports.default = doc;
  1821. exports.printer = doc_2;
  1822. exports.utils = doc_3;
  1823. Object.defineProperty(exports, '__esModule', { value: true });
  1824. })));