From 275277a7a392b81720d318e7337101539c5bc0e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9rome=20Perrin?= <jerome@nexedi.com> Date: Fri, 22 Nov 2019 11:05:43 +0000 Subject: [PATCH] =?UTF-8?q?monaco=5Feditor:=20prettier=20version=20?= =?UTF-8?q?=E2=86=91=202.0.5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../monaco-editor.gadget.html.html | 4 +- .../monaco-editor.gadget.js.js | 4 +- .../prettier%401.14.0/parser-babylon.js.js | 1 - .../prettier%401.14.0/standalone.js.js | 20786 ---------- ...tier%401.14.0.xml => prettier%402.0.5.xml} | 2 +- .../prettier%402.0.5/parser-babel.js.js | 1 + .../parser-babel.js.xml} | 4 +- .../prettier%402.0.5/standalone.js.js | 32923 ++++++++++++++++ .../standalone.js.xml | 0 .../monaco_editor_support.zpt | 8 +- 10 files changed, 32935 insertions(+), 20798 deletions(-) delete mode 100644 bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/parser-babylon.js.js delete mode 100644 bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/standalone.js.js rename bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/{prettier%401.14.0.xml => prettier%402.0.5.xml} (90%) create mode 100644 bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/parser-babel.js.js rename bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/{prettier%401.14.0/parser-babylon.js.xml => prettier%402.0.5/parser-babel.js.xml} (86%) create mode 100644 bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/standalone.js.js rename bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/{prettier%401.14.0 => prettier%402.0.5}/standalone.js.xml (100%) diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor.gadget.html.html b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor.gadget.html.html index 574b22d9aa..c3ce11dd6b 100644 --- a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor.gadget.html.html +++ b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor.gadget.html.html @@ -9,8 +9,8 @@ <script src="renderjs.js"></script> <script src="jslint.js" type="text/javascript"></script> - <script src="monaco-editor/prettier@1.14.0/standalone.js"></script> - <script src="monaco-editor/prettier@1.14.0/parser-babylon.js"></script> + <script src="monaco-editor/prettier@2.0.5/standalone.js"></script> + <script src="monaco-editor/prettier@2.0.5/parser-babel.js"></script> <script> /* diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor.gadget.js.js b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor.gadget.js.js index 537103f21e..4329b70ed7 100644 --- a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor.gadget.js.js +++ b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor.gadget.js.js @@ -131,8 +131,8 @@ { provideDocumentFormattingEdits(model, options, token) { const text = prettier.format(model.getValue(), { - parser: 'babylon', - plugins: [prettierPlugins.babylon], + parser: 'babel', + plugins: [prettierPlugins.babel], // see http://json.schemastore.org/prettierrc for supported options. singleQuote: true, tabWidth: 2 diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/parser-babylon.js.js b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/parser-babylon.js.js deleted file mode 100644 index 31aa962e51..0000000000 --- a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/parser-babylon.js.js +++ /dev/null @@ -1 +0,0 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t.prettierPlugins=t.prettierPlugins||{},t.prettierPlugins.babylon=e())}(this,function(){"use strict";var t=function(t,e){var s=new SyntaxError(t+" ("+e.start.line+":"+e.start.column+")");return s.loc=e,s};function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function s(t,e){return t(e={exports:{}},e.exports),e.exports}var i=s(function(t){t.exports=function(t){if("string"!=typeof t)throw new TypeError("Expected a string");var e=t.match(/(?:\r?\n)/g)||[];if(0===e.length)return null;var s=e.filter(function(t){return"\r\n"===t}).length;return s>e.length-s?"\r\n":"\n"},t.exports.graceful=function(e){return t.exports(e)||"\n"}}),r={EOL:"\n"},a=Object.freeze({default:r}),n=a&&r||a,o=s(function(t,e){var s,r;function a(){return s=(t=i)&&t.__esModule?t:{default:t};var t}function o(){return r=n}Object.defineProperty(e,"__esModule",{value:!0}),e.extract=function(t){var e=t.match(c);return e?e[0].trimLeft():""},e.strip=function(t){var e=t.match(c);return e&&e[0]?t.substring(e[0].length):t},e.parse=function(t){return y(t).pragmas},e.parseWithComments=y,e.print=function(t){var e=t.comments,i=void 0===e?"":e,n=t.pragmas,h=void 0===n?{}:n,p=(0,(s||a()).default)(i)||(r||o()).EOL,c=Object.keys(h),l=c.map(function(t){return x(t,h[t])}).reduce(function(t,e){return t.concat(e)},[]).map(function(t){return" * "+t+p}).join("");if(!i){if(0===c.length)return"";if(1===c.length&&!Array.isArray(h[c[0]])){var u=h[c[0]];return"".concat("/**"," ").concat(x(c[0],u)[0]).concat(" */")}}var d=i.split(p).map(function(t){return"".concat(" *"," ").concat(t)}).join(p)+p;return"/**"+p+(i?d:"")+(i&&c.length?" *"+p:"")+l+" */"};var h=/\*\/$/,p=/^\/\*\*/,c=/^\s*(\/\*\*?(.|\r?\n)*?\*\/)/,l=/(^|\s+)\/\/([^\r\n]*)/g,u=/^(\r?\n)+/,d=/(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g,f=/(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g,m=/(\r?\n|^) *\* ?/g;function y(t){var e=(0,(s||a()).default)(t)||(r||o()).EOL;t=t.replace(p,"").replace(h,"").replace(m,"$1");for(var i="";i!==t;)i=t,t=t.replace(d,"".concat(e,"$1 $2").concat(e));t=t.replace(u,"").trimRight();for(var n,c=Object.create(null),y=t.replace(f,"").replace(u,"").trimRight();n=f.exec(t);){var x=n[2].replace(l,"");"string"==typeof c[n[1]]||Array.isArray(c[n[1]])?c[n[1]]=[].concat(c[n[1]],x):c[n[1]]=x}return{comments:y,pragmas:c}}function x(t,e){return[].concat(e).map(function(e){return"@".concat(t," ").concat(e).trim()})}});e(o);var h=function(t){var e=Object.keys(o.parse(o.extract(t)));return-1!==e.indexOf("prettier")||-1!==e.indexOf("format")},p=function(t){return t.length>0?t[t.length-1]:null};var c={locStart:function t(e){return e.declaration&&e.declaration.decorators&&e.declaration.decorators.length>0?t(e.declaration.decorators[0]):e.decorators&&e.decorators.length>0?t(e.decorators[0]):e.__location?e.__location.startOffset:e.range?e.range[0]:"number"==typeof e.start?e.start:e.loc?e.loc.start:null},locEnd:function t(e){var s=e.nodes&&p(e.nodes);if(s&&e.source&&!e.source.end&&(e=s),e.__location)return e.__location.endOffset;var i=e.range?e.range[1]:"number"==typeof e.end?e.end:null;return e.typeAnnotation?Math.max(i,t(e.typeAnnotation)):e.loc&&!i?e.loc.end:i}},l=s(function(t,e){function s(t){var e,s;function i(e,s){try{var a=t[e](s),n=a.value,o=n instanceof function(t){this.wrapped=t};Promise.resolve(o?n.wrapped:n).then(function(t){o?i("next",t):r(a.done?"return":"normal",t)},function(t){i("throw",t)})}catch(t){r("throw",t)}}function r(t,r){switch(t){case"return":e.resolve({value:r,done:!0});break;case"throw":e.reject(r);break;default:e.resolve({value:r,done:!1})}(e=e.next)?i(e.key,e.arg):s=null}this._invoke=function(t,r){return new Promise(function(a,n){var o={key:t,arg:r,resolve:a,reject:n,next:null};s?s=s.next=o:(e=s=o,i(t,r))})},"function"!=typeof t.return&&(this.return=void 0)}function i(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}Object.defineProperty(e,"__esModule",{value:!0}),"function"==typeof Symbol&&Symbol.asyncIterator&&(s.prototype[Symbol.asyncIterator]=function(){return this}),s.prototype.next=function(t){return this._invoke("next",t)},s.prototype.throw=function(t){return this._invoke("throw",t)},s.prototype.return=function(t){return this._invoke("return",t)};var r=!0,a=function(t,e){void 0===e&&(e={}),this.label=t,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.rightAssociative=!!e.rightAssociative,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=0===e.binop?0:e.binop||null,this.updateContext=null},n=function(t){function e(e,s){return void 0===s&&(s={}),s.keyword=e,t.call(this,e,s)||this}return i(e,t),e}(a),o=function(t){function e(e,s){return t.call(this,e,{beforeExpr:r,binop:s})||this}return i(e,t),e}(a),h={num:new a("num",{startsExpr:!0}),bigint:new a("bigint",{startsExpr:!0}),regexp:new a("regexp",{startsExpr:!0}),string:new a("string",{startsExpr:!0}),name:new a("name",{startsExpr:!0}),eof:new a("eof"),bracketL:new a("[",{beforeExpr:r,startsExpr:!0}),bracketR:new a("]"),braceL:new a("{",{beforeExpr:r,startsExpr:!0}),braceBarL:new a("{|",{beforeExpr:r,startsExpr:!0}),braceR:new a("}"),braceBarR:new a("|}"),parenL:new a("(",{beforeExpr:r,startsExpr:!0}),parenR:new a(")"),comma:new a(",",{beforeExpr:r}),semi:new a(";",{beforeExpr:r}),colon:new a(":",{beforeExpr:r}),doubleColon:new a("::",{beforeExpr:r}),dot:new a("."),question:new a("?",{beforeExpr:r}),questionDot:new a("?."),arrow:new a("=>",{beforeExpr:r}),template:new a("template"),ellipsis:new a("...",{beforeExpr:r}),backQuote:new a("`",{startsExpr:!0}),dollarBraceL:new a("${",{beforeExpr:r,startsExpr:!0}),at:new a("@"),hash:new a("#"),interpreterDirective:new a("#!..."),eq:new a("=",{beforeExpr:r,isAssign:!0}),assign:new a("_=",{beforeExpr:r,isAssign:!0}),incDec:new a("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),bang:new a("!",{beforeExpr:r,prefix:!0,startsExpr:!0}),tilde:new a("~",{beforeExpr:r,prefix:!0,startsExpr:!0}),pipeline:new o("|>",0),nullishCoalescing:new o("??",1),logicalOR:new o("||",1),logicalAND:new o("&&",2),bitwiseOR:new o("|",3),bitwiseXOR:new o("^",4),bitwiseAND:new o("&",5),equality:new o("==/!=",6),relational:new o("</>",7),bitShift:new o("<</>>",8),plusMin:new a("+/-",{beforeExpr:r,binop:9,prefix:!0,startsExpr:!0}),modulo:new o("%",10),star:new o("*",10),slash:new o("/",10),exponent:new a("**",{beforeExpr:r,binop:11,rightAssociative:!0})},p={break:new n("break"),case:new n("case",{beforeExpr:r}),catch:new n("catch"),continue:new n("continue"),debugger:new n("debugger"),default:new n("default",{beforeExpr:r}),do:new n("do",{isLoop:!0,beforeExpr:r}),else:new n("else",{beforeExpr:r}),finally:new n("finally"),for:new n("for",{isLoop:!0}),function:new n("function",{startsExpr:!0}),if:new n("if"),return:new n("return",{beforeExpr:r}),switch:new n("switch"),throw:new n("throw",{beforeExpr:r,prefix:!0,startsExpr:!0}),try:new n("try"),var:new n("var"),let:new n("let"),const:new n("const"),while:new n("while",{isLoop:!0}),with:new n("with"),new:new n("new",{beforeExpr:r,startsExpr:!0}),this:new n("this",{startsExpr:!0}),super:new n("super",{startsExpr:!0}),class:new n("class"),extends:new n("extends",{beforeExpr:r}),export:new n("export"),import:new n("import",{startsExpr:!0}),yield:new n("yield",{beforeExpr:r,startsExpr:!0}),null:new n("null",{startsExpr:!0}),true:new n("true",{startsExpr:!0}),false:new n("false",{startsExpr:!0}),in:new n("in",{beforeExpr:r,binop:7}),instanceof:new n("instanceof",{beforeExpr:r,binop:7}),typeof:new n("typeof",{beforeExpr:r,prefix:!0,startsExpr:!0}),void:new n("void",{beforeExpr:r,prefix:!0,startsExpr:!0}),delete:new n("delete",{beforeExpr:r,prefix:!0,startsExpr:!0})};function c(t){return null!=t&&"Property"===t.type&&"init"===t.kind&&!1===t.method}Object.keys(p).forEach(function(t){h["_"+t]=p[t]});function l(t){var e=t.split(" ");return function(t){return e.indexOf(t)>=0}}var u={6:l("enum await"),strict:l("implements interface let package private protected public static yield"),strictBind:l("eval arguments")},d=l("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this let const class extends export import yield super"),f="ªµºÀ-ÖØ-öø-ˈ-Ë‘Ë -ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ÒÒŠ-Ô¯Ô±-Õ–Õ™Õ¡-Ö‡×-תװ-×²Ø -يٮٯٱ-Û“Û•Û¥Û¦Û®Û¯Ûº-Û¼Û¿ÜÜ’-ܯÝ-ޥޱߊ-ßªß´ßµßºà €-à •à šà ¤à ¨à¡€-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࢽऄ-हऽà¥à¥˜-ॡॱ-ঀঅ-ঌà¦à¦à¦“-নপ-রলশ-হঽৎড়à§à§Ÿ-ৡৰৱৼਅ-ਊà¨à¨à¨“-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-àªàª-ઑઓ-નપ-રલળવ-હઽà«à« ૡૹଅ-ଌà¬à¬à¬“-ନପ-ରଲଳଵ-ହଽàœààŸ-à¡à±à®ƒà®…-ஊஎ-à®à®’-கஙசஜஞடணதந-பம-ஹà¯à°…-ఌఎ-à°à°’-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-à²à²’-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-à´à´’-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-à·†à¸-ะาำเ-ๆàºàº‚ຄງຈຊàºàº”-ທນ-ຟມ-ຣລວສຫàº-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿá-á•áš-áá¡á¥á¦á®-á°áµ-á‚á‚Žá‚ -ჅჇáƒáƒ-ჺჼ-ቈቊ-á‰á‰-ቖቘቚ-á‰á‰ -ኈኊ-áŠáŠ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-áŒáŒ’-ጕጘ-ášáŽ€-áŽáŽ -áµá¸-á½á-ᙬᙯ-ᙿáš-áššáš -ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱá€-á‘á -á¬á®-á°áž€-ឳៗៜá -ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞá¥-á¥á¥°-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳá…-á‹á®ƒ-ᮠᮮᮯᮺ-ᯥᰀ-á°£á±-á±á±š-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-á¼á¼ -ὅὈ-á½á½-ὗὙὛá½á½Ÿ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-á¿Œá¿-á¿“á¿–-Ίῠ-Ῥῲ-ῴῶ-ῼâ±â¿â‚-ₜℂℇℊ-ℓℕ℘-â„ℤΩℨK-ℹℼ-â„¿â……-â…‰â…Žâ… -ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧâ´â´°-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-â·Žâ·-â·–â·˜-ⷞ々-〇〡-〩〱-〵〸-〼ã-ã‚–ã‚›-ã‚Ÿã‚¡-ヺー-ヿㄅ-ㄮㄱ-ㆎㆠ-ㆺㇰ-ㇿã€-䶵一-鿪ꀀ-ê’Œê“-ꓽꔀ-ꘌê˜-ꘟꘪꘫꙀ-ꙮꙿ-êšêš -ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ê ê ƒ-ê …ê ‡-ê Šê Œ-ê ¢ê¡€-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ê¥†ê¥ -ꥼꦄ-ꦲê§ê§ -ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ê©‚ê©„-ê©‹ê© -ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ê«ê« -ꫪꫲ-ê«´ê¬-ꬆꬉ-ꬎꬑ-ê¬–ê¬ -ꬦꬨ-ꬮꬰ-êšêœ-ê¥ê°-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-ï©ï©°-龎ff-stﬓ-ﬗï¬ï¬Ÿ-ﬨשׁ-זּטּ-לּמּï€ïïƒï„ï†-ﮱﯓ-ï´½ïµ-ï¶ï¶’-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Zï½-zヲ-하-ᅦᅧ-ï¿ï¿’-ï¿—ï¿š-ï¿œ",m="‌â€Â·Ì€-ͯ·҃-Ò‡Ö‘-Ö½Ö¿×ׇׂׅׄØ-ØšÙ‹-٩ٰۖ-ۜ۟-Û¤Û§Û¨Ûª-ÛÛ°-۹ܑܰ-ÝŠÞ¦-ް߀-߉߫-ß³à –-à ™à ›-à £à ¥-à §à ©-à à¡™-࡛ࣔ-ࣣ࣡-ःऺ-़ा-à¥à¥‘-ॗॢॣ०-९à¦-ঃ়া-ৄেৈো-à§à§—ৢৣ০-৯à¨-ਃ਼ਾ-ੂੇੈੋ-à©à©‘੦-ੱੵàª-ઃ઼ા-ૅે-ૉો-à«à«¢à«£à«¦-૯ૺ-à«¿à¬-ଃ଼ା-à„à‡àˆà‹-àà–à—à¢à£à¦-à¯à®‚ா-ூெ-ைொ-à¯à¯—௦-௯ఀ-ఃా-ౄె-ైొ-à±à±•à±–ౢౣ౦-౯à²-ಃ಼ಾ-ೄೆ-ೈೊ-à³à³•à³–ೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-àµàµ—ൢൣ൦-൯ංඃ්à·-ුූෘ-à·Ÿà·¦-෯ෲෳัิ-ฺ็-๎à¹-๙ັິ-ູົຼ່-à»à»-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇à¾-ྗྙ-ྼ࿆ါ-ှá€-á‰á–-á™áž-á á¢-á¤á§-áá±-á´á‚‚-á‚á‚-á‚á-áŸá©-á±áœ’-᜔ᜲ-᜴á’á“á²á³áž´-៓áŸáŸ -áŸ©á ‹-á á -á ™á¢©á¤ -ᤫᤰ-᤻᥆-á¥á§-᧚ᨗ-ᨛᩕ-á©žá© -᩿᩼-᪉áª-᪙᪰-᪽ᬀ-ᬄ᬴-á„á-á™á«-á³á®€-ᮂᮡ-á®á®°-᮹᯦-᯳ᰤ-á°·á±€-᱉á±-á±™á³-á³’á³”-᳨á³á³²-á³´á³·-᳹᷀-᷹᷻-᷿‿â€â”âƒ-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-ã€¯ã‚™ã‚šê˜ -꘩꙯ꙴ-ê™½êšžêšŸê›°ê›±ê ‚ê †ê ‹ê £-ê §ê¢€ê¢ê¢´-ꣅê£-ê£™ê£ -꣱꤀-꤉ꤦ-ê¤ê¥‡-꥓ꦀ-ꦃ꦳-꧀ê§-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌê©ê©-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿ê«ê««-ꫯꫵ꫶ꯣ-ꯪ꯬ê¯ê¯°-꯹ﬞ︀-ï¸ï¸ -︯︳︴ï¹-ï¹ï¼-9_",y=new RegExp("["+f+"]"),x=new RegExp("["+f+m+"]");f=m=null;var v=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,257,0,11,39,8,0,22,0,12,39,3,3,55,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,698,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,1,31,6124,20,754,9486,286,82,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541],P=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,280,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,19719,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239];function g(t,e){for(var s=65536,i=0;i<e.length;i+=2){if((s+=e[i])>t)return!1;if((s+=e[i+1])>=t)return!0}return!1}function b(t){return t<65?36===t:t<91||(t<97?95===t:t<123||(t<=65535?t>=170&&y.test(String.fromCharCode(t)):g(t,v)))}function T(t){return t<48?36===t:t<58||!(t<65)&&(t<91||(t<97?95===t:t<123||(t<=65535?t>=170&&x.test(String.fromCharCode(t)):g(t,v)||g(t,P))))}var w=["any","bool","boolean","empty","false","mixed","null","number","static","string","true","typeof","void"];function A(t){return"type"===t.importKind||"typeof"===t.importKind}function E(t){return(t.type===h.name||!!t.type.keyword)&&"from"!==t.value}var C={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};var N=/\*?\s*@((?:no)?flow)\b/,k={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"Â¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"Â",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Ã",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Ã…",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"ÃŒ",Iacute:"Ã",Icirc:"ÃŽ",Iuml:"Ã",ETH:"Ã",Ntilde:"Ñ",Ograve:"Ã’",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ãœ",Yacute:"Ã",THORN:"Þ",szlig:"ß",agrave:"à ",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"Ã¥",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"Ã",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Å’",oelig:"Å“",Scaron:"Å ",scaron:"Å¡",Yuml:"Ÿ",fnof:"Æ’",circ:"ˆ",tilde:"Ëœ",Alpha:"Α",Beta:"Î’",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Îœ",Nu:"Î",Xi:"Ξ",Omicron:"Ο",Pi:"Î ",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Î¥",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"Ï€",rho:"Ï",sigmaf:"Ï‚",sigma:"σ",tau:"Ï„",upsilon:"Ï…",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"Ï‘",upsih:"Ï’",piv:"Ï–",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"â€",lrm:"‎",rlm:"â€",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"â€",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"â„",euro:"€",image:"â„‘",weierp:"℘",real:"â„œ",trade:"â„¢",alefsym:"ℵ",larr:"â†",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"â‡",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"âˆ",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"âˆ",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"â‹…",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"â—Š",spades:"â™ ",clubs:"♣",hearts:"♥",diams:"♦"},S=/\r\n?|\n|\u2028|\u2029/,I=new RegExp(S.source,"g");function L(t){return 10===t||13===t||8232===t||8233===t}var O=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,M=function(t,e,s,i){this.token=t,this.isExpr=!!e,this.preserveSpace=!!s,this.override=i},D={braceStatement:new M("{",!1),braceExpression:new M("{",!0),templateQuasi:new M("${",!0),parenStatement:new M("(",!1),parenExpression:new M("(",!0),template:new M("`",!0,!0,function(t){return t.readTmplToken()}),functionExpression:new M("function",!0)};h.parenR.updateContext=h.braceR.updateContext=function(){if(1!==this.state.context.length){var t=this.state.context.pop();t===D.braceStatement&&this.curContext()===D.functionExpression?(this.state.context.pop(),this.state.exprAllowed=!1):t===D.templateQuasi?this.state.exprAllowed=!0:this.state.exprAllowed=!t.isExpr}else this.state.exprAllowed=!0},h.name.updateContext=function(t){"of"!==this.state.value||this.curContext()!==D.parenStatement?(this.state.exprAllowed=!1,t!==h._let&&t!==h._const&&t!==h._var||S.test(this.input.slice(this.state.end))&&(this.state.exprAllowed=!0),this.state.isIterator&&(this.state.isIterator=!1)):this.state.exprAllowed=!t.beforeExpr},h.braceL.updateContext=function(t){this.state.context.push(this.braceIsBlock(t)?D.braceStatement:D.braceExpression),this.state.exprAllowed=!0},h.dollarBraceL.updateContext=function(){this.state.context.push(D.templateQuasi),this.state.exprAllowed=!0},h.parenL.updateContext=function(t){var e=t===h._if||t===h._for||t===h._with||t===h._while;this.state.context.push(e?D.parenStatement:D.parenExpression),this.state.exprAllowed=!0},h.incDec.updateContext=function(){},h._function.updateContext=function(t){this.state.exprAllowed&&!this.braceIsBlock(t)&&this.state.context.push(D.functionExpression),this.state.exprAllowed=!1},h.backQuote.updateContext=function(){this.curContext()===D.template?this.state.context.pop():this.state.context.push(D.template),this.state.exprAllowed=!1};var _=/^[\da-fA-F]+$/,R=/^\d+$/;function j(t){return!!t&&("JSXOpeningFragment"===t.type||"JSXClosingFragment"===t.type)}function F(t){if("JSXIdentifier"===t.type)return t.name;if("JSXNamespacedName"===t.type)return t.namespace.name+":"+t.name.name;if("JSXMemberExpression"===t.type)return F(t.object)+"."+F(t.property);throw new Error("Node had unexpected type: "+t.type)}D.j_oTag=new M("<tag",!1),D.j_cTag=new M("</tag",!1),D.j_expr=new M("<tag>...</tag>",!0,!0),h.jsxName=new a("jsxName"),h.jsxText=new a("jsxText",{beforeExpr:!0}),h.jsxTagStart=new a("jsxTagStart",{startsExpr:!0}),h.jsxTagEnd=new a("jsxTagEnd"),h.jsxTagStart.updateContext=function(){this.state.context.push(D.j_expr),this.state.context.push(D.j_oTag),this.state.exprAllowed=!1},h.jsxTagEnd.updateContext=function(t){var e=this.state.context.pop();e===D.j_oTag&&t===h.slash||e===D.j_cTag?(this.state.context.pop(),this.state.exprAllowed=this.curContext()===D.j_expr):this.state.exprAllowed=!0};var B={sourceType:"script",sourceFilename:void 0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,plugins:[],strictMode:null,ranges:!1,tokens:!1};var q=function(t,e){this.line=t,this.column=e},U=function(t,e){this.start=t,this.end=e};function V(t){return t[t.length-1]}var K=function(t){function e(){return t.apply(this,arguments)||this}return i(e,t),e.prototype.raise=function(t,e,s){var i=void 0===s?{}:s,r=i.missingPluginNames,a=i.code,n=function(t,e){for(var s=1,i=0;;){I.lastIndex=i;var r=I.exec(t);if(!(r&&r.index<e))return new q(s,e-i);++s,i=r.index+r[0].length}throw new Error("Unreachable")}(this.input,t);e+=" ("+n.line+":"+n.column+")";var o=new SyntaxError(e);throw o.pos=t,o.loc=n,r&&(o.missingPlugin=r),void 0!==a&&(o.code=a),o},e}(function(t){function e(){return t.apply(this,arguments)||this}i(e,t);var s=e.prototype;return s.addComment=function(t){this.filename&&(t.loc.filename=this.filename),this.state.trailingComments.push(t),this.state.leadingComments.push(t)},s.processComment=function(t){if(!("Program"===t.type&&t.body.length>0)){var e,s,i,r,a,n=this.state.commentStack;if(this.state.trailingComments.length>0)this.state.trailingComments[0].start>=t.end?(i=this.state.trailingComments,this.state.trailingComments=[]):this.state.trailingComments.length=0;else if(n.length>0){var o=V(n);o.trailingComments&&o.trailingComments[0].start>=t.end&&(i=o.trailingComments,delete o.trailingComments)}for(n.length>0&&V(n).start>=t.start&&(e=n.pop());n.length>0&&V(n).start>=t.start;)s=n.pop();if(!s&&e&&(s=e),e&&this.state.leadingComments.length>0){var h=V(this.state.leadingComments);if("ObjectProperty"===e.type){if(h.start>=t.start&&this.state.commentPreviousNode){for(a=0;a<this.state.leadingComments.length;a++)this.state.leadingComments[a].end<this.state.commentPreviousNode.end&&(this.state.leadingComments.splice(a,1),a--);this.state.leadingComments.length>0&&(e.trailingComments=this.state.leadingComments,this.state.leadingComments=[])}}else if("CallExpression"===t.type&&t.arguments&&t.arguments.length){var p=V(t.arguments);p&&h.start>=p.start&&h.end<=t.end&&this.state.commentPreviousNode&&this.state.leadingComments.length>0&&(p.trailingComments=this.state.leadingComments,this.state.leadingComments=[])}}if(s){if(s.leadingComments)if(s!==t&&s.leadingComments.length>0&&V(s.leadingComments).end<=t.start)t.leadingComments=s.leadingComments,delete s.leadingComments;else for(r=s.leadingComments.length-2;r>=0;--r)if(s.leadingComments[r].end<=t.start){t.leadingComments=s.leadingComments.splice(0,r+1);break}}else if(this.state.leadingComments.length>0)if(V(this.state.leadingComments).end<=t.start){if(this.state.commentPreviousNode)for(a=0;a<this.state.leadingComments.length;a++)this.state.leadingComments[a].end<this.state.commentPreviousNode.end&&(this.state.leadingComments.splice(a,1),a--);this.state.leadingComments.length>0&&(t.leadingComments=this.state.leadingComments,this.state.leadingComments=[])}else{for(r=0;r<this.state.leadingComments.length&&!(this.state.leadingComments[r].end>t.start);r++);var c=this.state.leadingComments.slice(0,r);c.length&&(t.leadingComments=c),0===(i=this.state.leadingComments.slice(r)).length&&(i=null)}this.state.commentPreviousNode=t,i&&(i.length&&i[0].start>=t.start&&V(i).end<=t.end?t.innerComments=i:t.trailingComments=i),n.push(t)}},e}(function(){function t(){this.sawUnambiguousESM=!1}var e=t.prototype;return e.isReservedWord=function(t){return"await"===t?this.inModule:u[6](t)},e.hasPlugin=function(t){return Object.hasOwnProperty.call(this.plugins,t)},e.getPluginOption=function(t,e){if(this.hasPlugin(t))return this.plugins[t][e]},t}())),W=function(){function t(){}var e=t.prototype;return e.init=function(t,e){this.strict=!1!==t.strictMode&&"module"===t.sourceType,this.input=e,this.potentialArrowAt=-1,this.noArrowAt=[],this.noArrowParamsConversionAt=[],this.inMethod=!1,this.inFunction=!1,this.inParameters=!1,this.maybeInArrowParameters=!1,this.inGenerator=!1,this.inAsync=!1,this.inPropertyName=!1,this.inType=!1,this.inClassProperty=!1,this.noAnonFunctionType=!1,this.hasFlowComment=!1,this.isIterator=!1,this.classLevel=0,this.labels=[],this.decoratorStack=[[]],this.yieldInPossibleArrowParameters=null,this.tokens=[],this.comments=[],this.trailingComments=[],this.leadingComments=[],this.commentStack=[],this.commentPreviousNode=null,this.pos=this.lineStart=0,this.curLine=t.startLine,this.type=h.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=[D.braceStatement],this.exprAllowed=!0,this.containsEsc=this.containsOctal=!1,this.octalPosition=null,this.invalidTemplateEscapePosition=null,this.exportedIdentifiers=[]},e.curPosition=function(){return new q(this.curLine,this.pos-this.lineStart)},e.clone=function(e){var s=this,i=new t;return Object.keys(this).forEach(function(t){var r=s[t];e&&"context"!==t||!Array.isArray(r)||(r=r.slice()),i[t]=r}),i},t}(),G=function(t){return t>=48&&t<=57},X={decBinOct:[46,66,69,79,95,98,101,111],hex:[46,88,95,120]},J={bin:[48,49]};J.oct=J.bin.concat([50,51,52,53,54,55]),J.dec=J.oct.concat([56,57]),J.hex=J.dec.concat([65,66,67,68,69,70,97,98,99,100,101,102]);function H(t){return t<=65535?String.fromCharCode(t):String.fromCharCode(55296+(t-65536>>10),56320+(t-65536&1023))}var z=function(t){function e(){return t.apply(this,arguments)||this}i(e,t);var s=e.prototype;return s.addExtra=function(t,e,s){t&&((t.extra=t.extra||{})[e]=s)},s.isRelational=function(t){return this.match(h.relational)&&this.state.value===t},s.isLookaheadRelational=function(t){var e=this.lookahead();return e.type==h.relational&&e.value==t},s.expectRelational=function(t){this.isRelational(t)?this.next():this.unexpected(null,h.relational)},s.eatRelational=function(t){return!!this.isRelational(t)&&(this.next(),!0)},s.isContextual=function(t){return this.match(h.name)&&this.state.value===t&&!this.state.containsEsc},s.isLookaheadContextual=function(t){var e=this.lookahead();return e.type===h.name&&e.value===t},s.eatContextual=function(t){return this.isContextual(t)&&this.eat(h.name)},s.expectContextual=function(t,e){this.eatContextual(t)||this.unexpected(null,e)},s.canInsertSemicolon=function(){return this.match(h.eof)||this.match(h.braceR)||this.hasPrecedingLineBreak()},s.hasPrecedingLineBreak=function(){return S.test(this.input.slice(this.state.lastTokEnd,this.state.start))},s.isLineTerminator=function(){return this.eat(h.semi)||this.canInsertSemicolon()},s.semicolon=function(){this.isLineTerminator()||this.unexpected(null,h.semi)},s.expect=function(t,e){this.eat(t)||this.unexpected(e,t)},s.unexpected=function(t,e){throw void 0===e&&(e="Unexpected token"),"string"!=typeof e&&(e='Unexpected token, expected "'+e.label+'"'),this.raise(null!=t?t:this.state.start,e)},s.expectPlugin=function(t,e){if(!this.hasPlugin(t))throw this.raise(null!=e?e:this.state.start,"This experimental syntax requires enabling the parser plugin: '"+t+"'",{missingPluginNames:[t]});return!0},s.expectOnePlugin=function(t,e){var s=this;if(!t.some(function(t){return s.hasPlugin(t)}))throw this.raise(null!=e?e:this.state.start,"This experimental syntax requires enabling one of the following parser plugin(s): '"+t.join(", ")+"'",{missingPluginNames:t})},e}(function(t){function e(e,s){var i;return(i=t.call(this)||this).state=new W,i.state.init(e,s),i.isLookahead=!1,i}i(e,t);var s=e.prototype;return s.next=function(){this.options.tokens&&!this.isLookahead&&this.state.tokens.push(new function(t){this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new U(t.startLoc,t.endLoc)}(this.state)),this.state.lastTokEnd=this.state.end,this.state.lastTokStart=this.state.start,this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()},s.eat=function(t){return!!this.match(t)&&(this.next(),!0)},s.match=function(t){return this.state.type===t},s.isKeyword=function(t){return d(t)},s.lookahead=function(){var t=this.state;this.state=t.clone(!0),this.isLookahead=!0,this.next(),this.isLookahead=!1;var e=this.state;return this.state=t,e},s.setStrict=function(t){if(this.state.strict=t,this.match(h.num)||this.match(h.string)){for(this.state.pos=this.state.start;this.state.pos<this.state.lineStart;)this.state.lineStart=this.input.lastIndexOf("\n",this.state.lineStart-2)+1,--this.state.curLine;this.nextToken()}},s.curContext=function(){return this.state.context[this.state.context.length-1]},s.nextToken=function(){var t=this.curContext();t&&t.preserveSpace||this.skipSpace(),this.state.containsOctal=!1,this.state.octalPosition=null,this.state.start=this.state.pos,this.state.startLoc=this.state.curPosition(),this.state.pos>=this.input.length?this.finishToken(h.eof):t.override?t.override(this):this.readToken(this.fullCharCodeAtPos())},s.readToken=function(t){b(t)||92===t?this.readWord():this.getTokenFromCode(t)},s.fullCharCodeAtPos=function(){var t=this.input.charCodeAt(this.state.pos);return t<=55295||t>=57344?t:(t<<10)+this.input.charCodeAt(this.state.pos+1)-56613888},s.pushComment=function(t,e,s,i,r,a){var n={type:t?"CommentBlock":"CommentLine",value:e,start:s,end:i,loc:new U(r,a)};this.isLookahead||(this.options.tokens&&this.state.tokens.push(n),this.state.comments.push(n),this.addComment(n))},s.skipBlockComment=function(){var t,e=this.state.curPosition(),s=this.state.pos,i=this.input.indexOf("*/",this.state.pos+=2);for(-1===i&&this.raise(this.state.pos-2,"Unterminated comment"),this.state.pos=i+2,I.lastIndex=s;(t=I.exec(this.input))&&t.index<this.state.pos;)++this.state.curLine,this.state.lineStart=t.index+t[0].length;this.pushComment(!0,this.input.slice(s+2,i),s,this.state.pos,e,this.state.curPosition())},s.skipLineComment=function(t){var e=this.state.pos,s=this.state.curPosition(),i=this.input.charCodeAt(this.state.pos+=t);if(this.state.pos<this.input.length)for(;10!==i&&13!==i&&8232!==i&&8233!==i&&++this.state.pos<this.input.length;)i=this.input.charCodeAt(this.state.pos);this.pushComment(!1,this.input.slice(e+t,this.state.pos),e,this.state.pos,s,this.state.curPosition())},s.skipSpace=function(){t:for(;this.state.pos<this.input.length;){var t=this.input.charCodeAt(this.state.pos);switch(t){case 32:case 160:++this.state.pos;break;case 13:10===this.input.charCodeAt(this.state.pos+1)&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break t}break;default:if(!(t>8&&t<14||t>=5760&&O.test(String.fromCharCode(t))))break t;++this.state.pos}}},s.finishToken=function(t,e){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();var s=this.state.type;this.state.type=t,this.state.value=e,this.updateContext(s)},s.readToken_dot=function(){var t=this.input.charCodeAt(this.state.pos+1);if(t>=48&&t<=57)this.readNumber(!0);else{var e=this.input.charCodeAt(this.state.pos+2);46===t&&46===e?(this.state.pos+=3,this.finishToken(h.ellipsis)):(++this.state.pos,this.finishToken(h.dot))}},s.readToken_slash=function(){if(this.state.exprAllowed)return++this.state.pos,void this.readRegexp();61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(h.assign,2):this.finishOp(h.slash,1)},s.readToken_interpreter=function(){if(0!==this.state.pos||this.state.input.length<2)return!1;var t=this.state.pos;this.state.pos+=1;var e=this.input.charCodeAt(this.state.pos);if(33!==e)return!1;for(;10!==e&&13!==e&&8232!==e&&8233!==e&&++this.state.pos<this.input.length;)e=this.input.charCodeAt(this.state.pos);var s=this.input.slice(t+2,this.state.pos);return this.finishToken(h.interpreterDirective,s),!0},s.readToken_mult_modulo=function(t){var e=42===t?h.star:h.modulo,s=1,i=this.input.charCodeAt(this.state.pos+1),r=this.state.exprAllowed;42===t&&42===i&&(s++,i=this.input.charCodeAt(this.state.pos+2),e=h.exponent),61!==i||r||(s++,e=h.assign),this.finishOp(e,s)},s.readToken_pipe_amp=function(t){var e=this.input.charCodeAt(this.state.pos+1);if(e!==t){if(124===t){if(62===e)return void this.finishOp(h.pipeline,2);if(125===e&&this.hasPlugin("flow"))return void this.finishOp(h.braceBarR,2)}61!==e?this.finishOp(124===t?h.bitwiseOR:h.bitwiseAND,1):this.finishOp(h.assign,2)}else 61===this.input.charCodeAt(this.state.pos+2)?this.finishOp(h.assign,3):this.finishOp(124===t?h.logicalOR:h.logicalAND,2)},s.readToken_caret=function(){61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(h.assign,2):this.finishOp(h.bitwiseXOR,1)},s.readToken_plus_min=function(t){var e=this.input.charCodeAt(this.state.pos+1);if(e===t)return 45===e&&!this.inModule&&62===this.input.charCodeAt(this.state.pos+2)&&S.test(this.input.slice(this.state.lastTokEnd,this.state.pos))?(this.skipLineComment(3),this.skipSpace(),void this.nextToken()):void this.finishOp(h.incDec,2);61===e?this.finishOp(h.assign,2):this.finishOp(h.plusMin,1)},s.readToken_lt_gt=function(t){var e=this.input.charCodeAt(this.state.pos+1),s=1;return e===t?(s=62===t&&62===this.input.charCodeAt(this.state.pos+2)?3:2,61===this.input.charCodeAt(this.state.pos+s)?void this.finishOp(h.assign,s+1):void this.finishOp(h.bitShift,s)):33!==e||60!==t||this.inModule||45!==this.input.charCodeAt(this.state.pos+2)||45!==this.input.charCodeAt(this.state.pos+3)?(61===e&&(s=2),void this.finishOp(h.relational,s)):(this.skipLineComment(4),this.skipSpace(),void this.nextToken())},s.readToken_eq_excl=function(t){var e=this.input.charCodeAt(this.state.pos+1);if(61!==e)return 61===t&&62===e?(this.state.pos+=2,void this.finishToken(h.arrow)):void this.finishOp(61===t?h.eq:h.bang,1);this.finishOp(h.equality,61===this.input.charCodeAt(this.state.pos+2)?3:2)},s.readToken_question=function(){var t=this.input.charCodeAt(this.state.pos+1),e=this.input.charCodeAt(this.state.pos+2);63===t?61===e?this.finishOp(h.assign,3):this.finishOp(h.nullishCoalescing,2):46!==t||e>=48&&e<=57?(++this.state.pos,this.finishToken(h.question)):(this.state.pos+=2,this.finishToken(h.questionDot))},s.getTokenFromCode=function(t){switch(t){case 35:if(0===this.state.pos&&this.readToken_interpreter())return;if((this.hasPlugin("classPrivateProperties")||this.hasPlugin("classPrivateMethods"))&&this.state.classLevel>0)return++this.state.pos,void this.finishToken(h.hash);this.raise(this.state.pos,"Unexpected character '"+H(t)+"'");case 46:return void this.readToken_dot();case 40:return++this.state.pos,void this.finishToken(h.parenL);case 41:return++this.state.pos,void this.finishToken(h.parenR);case 59:return++this.state.pos,void this.finishToken(h.semi);case 44:return++this.state.pos,void this.finishToken(h.comma);case 91:return++this.state.pos,void this.finishToken(h.bracketL);case 93:return++this.state.pos,void this.finishToken(h.bracketR);case 123:return void(this.hasPlugin("flow")&&124===this.input.charCodeAt(this.state.pos+1)?this.finishOp(h.braceBarL,2):(++this.state.pos,this.finishToken(h.braceL)));case 125:return++this.state.pos,void this.finishToken(h.braceR);case 58:return void(this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(h.doubleColon,2):(++this.state.pos,this.finishToken(h.colon)));case 63:return void this.readToken_question();case 64:return++this.state.pos,void this.finishToken(h.at);case 96:return++this.state.pos,void this.finishToken(h.backQuote);case 48:var e=this.input.charCodeAt(this.state.pos+1);if(120===e||88===e)return void this.readRadixNumber(16);if(111===e||79===e)return void this.readRadixNumber(8);if(98===e||66===e)return void this.readRadixNumber(2);case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return void this.readNumber(!1);case 34:case 39:return void this.readString(t);case 47:return void this.readToken_slash();case 37:case 42:return void this.readToken_mult_modulo(t);case 124:case 38:return void this.readToken_pipe_amp(t);case 94:return void this.readToken_caret();case 43:case 45:return void this.readToken_plus_min(t);case 60:case 62:return void this.readToken_lt_gt(t);case 61:case 33:return void this.readToken_eq_excl(t);case 126:return void this.finishOp(h.tilde,1)}this.raise(this.state.pos,"Unexpected character '"+H(t)+"'")},s.finishOp=function(t,e){var s=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(t,s)},s.readRegexp=function(){for(var t,e,s=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var i=this.input.charAt(this.state.pos);if(S.test(i)&&this.raise(s,"Unterminated regular expression"),t)t=!1;else{if("["===i)e=!0;else if("]"===i&&e)e=!1;else if("/"===i&&!e)break;t="\\"===i}++this.state.pos}var r=this.input.slice(s,this.state.pos);++this.state.pos;for(var a="";this.state.pos<this.input.length;){var n=this.input[this.state.pos],o=this.fullCharCodeAtPos();if("gmsiyu".indexOf(n)>-1)a.indexOf(n)>-1&&this.raise(this.state.pos+1,"Duplicate regular expression flag"),++this.state.pos,a+=n;else{if(!T(o)&&92!==o)break;this.raise(this.state.pos+1,"Invalid regular expression flag")}}this.finishToken(h.regexp,{pattern:r,flags:a})},s.readInt=function(t,e){for(var s=this.state.pos,i=16===t?X.hex:X.decBinOct,r=16===t?J.hex:10===t?J.dec:8===t?J.oct:J.bin,a=0,n=0,o=null==e?1/0:e;n<o;++n){var h=this.input.charCodeAt(this.state.pos),p=void 0;if(this.hasPlugin("numericSeparator")){var c=this.input.charCodeAt(this.state.pos-1),l=this.input.charCodeAt(this.state.pos+1);if(95===h){-1===r.indexOf(l)&&this.raise(this.state.pos,"Invalid or unexpected token"),(i.indexOf(c)>-1||i.indexOf(l)>-1||Number.isNaN(l))&&this.raise(this.state.pos,"Invalid or unexpected token"),++this.state.pos;continue}}if((p=h>=97?h-97+10:h>=65?h-65+10:G(h)?h-48:1/0)>=t)break;++this.state.pos,a=a*t+p}return this.state.pos===s||null!=e&&this.state.pos-s!==e?null:a},s.readRadixNumber=function(t){var e=this.state.pos,s=!1;this.state.pos+=2;var i=this.readInt(t);if(null==i&&this.raise(this.state.start+2,"Expected number in radix "+t),this.hasPlugin("bigInt")&&110===this.input.charCodeAt(this.state.pos)&&(++this.state.pos,s=!0),b(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number"),s){var r=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");this.finishToken(h.bigint,r)}else this.finishToken(h.num,i)},s.readNumber=function(t){var e=this.state.pos,s=48===this.input.charCodeAt(e),i=!1,r=!1;t||null!==this.readInt(10)||this.raise(e,"Invalid number"),s&&this.state.pos==e+1&&(s=!1);var a=this.input.charCodeAt(this.state.pos);46!==a||s||(++this.state.pos,this.readInt(10),i=!0,a=this.input.charCodeAt(this.state.pos)),69!==a&&101!==a||s||(43!==(a=this.input.charCodeAt(++this.state.pos))&&45!==a||++this.state.pos,null===this.readInt(10)&&this.raise(e,"Invalid number"),i=!0,a=this.input.charCodeAt(this.state.pos)),this.hasPlugin("bigInt")&&110===a&&((i||s)&&this.raise(e,"Invalid BigIntLiteral"),++this.state.pos,r=!0),b(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number");var n,o=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");r?this.finishToken(h.bigint,o):(i?n=parseFloat(o):s&&1!==o.length?this.state.strict?this.raise(e,"Invalid number"):n=/[89]/.test(o)?parseInt(o,10):parseInt(o,8):n=parseInt(o,10),this.finishToken(h.num,n))},s.readCodePoint=function(t){var e;if(123===this.input.charCodeAt(this.state.pos)){var s=++this.state.pos;if(e=this.readHexChar(this.input.indexOf("}",this.state.pos)-this.state.pos,t),++this.state.pos,null===e)--this.state.invalidTemplateEscapePosition;else if(e>1114111){if(!t)return this.state.invalidTemplateEscapePosition=s-2,null;this.raise(s,"Code point out of bounds")}}else e=this.readHexChar(4,t);return e},s.readString=function(t){for(var e="",s=++this.state.pos,i=this.hasPlugin("jsonStrings");;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var r=this.input.charCodeAt(this.state.pos);if(r===t)break;92===r?(e+=this.input.slice(s,this.state.pos),e+=this.readEscapedChar(!1),s=this.state.pos):(!i||8232!==r&&8233!==r)&&L(r)?this.raise(this.state.start,"Unterminated string constant"):++this.state.pos}e+=this.input.slice(s,this.state.pos++),this.finishToken(h.string,e)},s.readTmplToken=function(){for(var t="",e=this.state.pos,s=!1;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated template");var i=this.input.charCodeAt(this.state.pos);if(96===i||36===i&&123===this.input.charCodeAt(this.state.pos+1))return this.state.pos===this.state.start&&this.match(h.template)?36===i?(this.state.pos+=2,void this.finishToken(h.dollarBraceL)):(++this.state.pos,void this.finishToken(h.backQuote)):(t+=this.input.slice(e,this.state.pos),void this.finishToken(h.template,s?null:t));if(92===i){t+=this.input.slice(e,this.state.pos);var r=this.readEscapedChar(!0);null===r?s=!0:t+=r,e=this.state.pos}else if(L(i)){switch(t+=this.input.slice(e,this.state.pos),++this.state.pos,i){case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:t+="\n";break;default:t+=String.fromCharCode(i)}++this.state.curLine,this.state.lineStart=this.state.pos,e=this.state.pos}else++this.state.pos}},s.readEscapedChar=function(t){var e=!t,s=this.input.charCodeAt(++this.state.pos);switch(++this.state.pos,s){case 110:return"\n";case 114:return"\r";case 120:var i=this.readHexChar(2,e);return null===i?null:String.fromCharCode(i);case 117:var r=this.readCodePoint(e);return null===r?null:H(r);case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:return this.state.lineStart=this.state.pos,++this.state.curLine,"";default:if(s>=48&&s<=55){var a=this.state.pos-1,n=this.input.substr(this.state.pos-1,3).match(/^[0-7]+/)[0],o=parseInt(n,8);if(o>255&&(n=n.slice(0,-1),o=parseInt(n,8)),o>0){if(t)return this.state.invalidTemplateEscapePosition=a,null;this.state.strict?this.raise(a,"Octal literal in strict mode"):this.state.containsOctal||(this.state.containsOctal=!0,this.state.octalPosition=a)}return this.state.pos+=n.length-1,String.fromCharCode(o)}return String.fromCharCode(s)}},s.readHexChar=function(t,e){var s=this.state.pos,i=this.readInt(16,t);return null===i&&(e?this.raise(s,"Bad character escape sequence"):(this.state.pos=s-1,this.state.invalidTemplateEscapePosition=s-1)),i},s.readWord1=function(){this.state.containsEsc=!1;for(var t="",e=!0,s=this.state.pos;this.state.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(T(i))this.state.pos+=i<=65535?1:2;else if(this.state.isIterator&&64===i)this.state.pos+=1;else{if(92!==i)break;this.state.containsEsc=!0,t+=this.input.slice(s,this.state.pos);var r=this.state.pos;117!==this.input.charCodeAt(++this.state.pos)&&this.raise(this.state.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.state.pos;var a=this.readCodePoint(!0);(e?b:T)(a,!0)||this.raise(r,"Invalid Unicode escape"),t+=H(a),s=this.state.pos}e=!1}return t+this.input.slice(s,this.state.pos)},s.isIterator=function(t){return"@@iterator"===t||"@@asyncIterator"===t},s.readWord=function(){var t=this.readWord1(),e=h.name;this.isKeyword(t)&&(this.state.containsEsc&&this.raise(this.state.pos,"Escape sequence in keyword "+t),e=p[t]),!this.state.isIterator||this.isIterator(t)&&this.state.inType||this.raise(this.state.pos,"Invalid identifier "+t),this.finishToken(e,t)},s.braceIsBlock=function(t){if(t===h.colon){var e=this.curContext();if(e===D.braceStatement||e===D.braceExpression)return!e.isExpr}return t===h._return?S.test(this.input.slice(this.state.lastTokEnd,this.state.start)):t===h._else||t===h.semi||t===h.eof||t===h.parenR||(t===h.braceL?this.curContext()===D.braceStatement:t===h.relational||!this.state.exprAllowed)},s.updateContext=function(t){var e,s=this.state.type;!s.keyword||t!==h.dot&&t!==h.questionDot?(e=s.updateContext)?e.call(this,t):this.state.exprAllowed=s.beforeExpr:this.state.exprAllowed=!1},e}(K)),Q=["leadingComments","trailingComments","innerComments"],Y=function(){function t(t,e,s){this.type="",this.start=e,this.end=0,this.loc=new U(s),t&&t.options.ranges&&(this.range=[e,0]),t&&t.filename&&(this.loc.filename=t.filename)}return t.prototype.__clone=function(){var e=this,s=new t;return Object.keys(this).forEach(function(t){Q.indexOf(t)<0&&(s[t]=e[t])}),s},t}(),$=[],Z={kind:"loop"},tt={kind:"switch"},et=function(t){function e(e,s){var i;return e=function(t){var e={};for(var s in B)e[s]=t&&null!=t[s]?t[s]:B[s];return e}(e),(i=t.call(this,e,s)||this).options=e,i.inModule="module"===i.options.sourceType,i.input=s,i.plugins=function(t){for(var e=Object.create(null),s=0;s<t.length;s++){var i=t[s],r=Array.isArray(i)?i:[i,{}],a=r[0],n=r[1],o=void 0===n?{}:n;e[a]||(e[a]=o||{})}return e}(i.options.plugins),i.filename=e.sourceFilename,i}return i(e,t),e.prototype.parse=function(){var t=this.startNode(),e=this.startNode();return this.nextToken(),this.parseTopLevel(t,e)},e}(function(t){function e(){return t.apply(this,arguments)||this}i(e,t);var s=e.prototype;return s.parseTopLevel=function(t,e){return e.sourceType=this.options.sourceType,e.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(e,!0,!0,h.eof),t.program=this.finishNode(e,"Program"),t.comments=this.state.comments,this.options.tokens&&(t.tokens=this.state.tokens),this.finishNode(t,"File")},s.stmtToDirective=function(t){var e=t.expression,s=this.startNodeAt(e.start,e.loc.start),i=this.startNodeAt(t.start,t.loc.start),r=this.input.slice(e.start,e.end),a=s.value=r.slice(1,-1);return this.addExtra(s,"raw",r),this.addExtra(s,"rawValue",a),i.value=this.finishNodeAt(s,"DirectiveLiteral",e.end,e.loc.end),this.finishNodeAt(i,"Directive",t.end,t.loc.end)},s.parseInterpreterDirective=function(){if(!this.match(h.interpreterDirective))return null;var t=this.startNode();return t.value=this.state.value,this.next(),this.finishNode(t,"InterpreterDirective")},s.parseStatement=function(t,e){return this.match(h.at)&&this.parseDecorators(!0),this.parseStatementContent(t,e)},s.parseStatementContent=function(t,e){var s=this.state.type,i=this.startNode();switch(s){case h._break:case h._continue:return this.parseBreakContinueStatement(i,s.keyword);case h._debugger:return this.parseDebuggerStatement(i);case h._do:return this.parseDoStatement(i);case h._for:return this.parseForStatement(i);case h._function:if(this.lookahead().type===h.dot)break;return t||this.unexpected(),this.parseFunctionStatement(i);case h._class:return t||this.unexpected(),this.parseClass(i,!0);case h._if:return this.parseIfStatement(i);case h._return:return this.parseReturnStatement(i);case h._switch:return this.parseSwitchStatement(i);case h._throw:return this.parseThrowStatement(i);case h._try:return this.parseTryStatement(i);case h._let:case h._const:t||this.unexpected();case h._var:return this.parseVarStatement(i,s);case h._while:return this.parseWhileStatement(i);case h._with:return this.parseWithStatement(i);case h.braceL:return this.parseBlock();case h.semi:return this.parseEmptyStatement(i);case h._export:case h._import:var r,a=this.lookahead();if(a.type===h.parenL||a.type===h.dot)break;return this.options.allowImportExportEverywhere||e||this.raise(this.state.start,"'import' and 'export' may only appear at the top level"),this.next(),s==h._import?"ImportDeclaration"!==(r=this.parseImport(i)).type||r.importKind&&"value"!==r.importKind||(this.sawUnambiguousESM=!0):("ExportNamedDeclaration"!==(r=this.parseExport(i)).type||r.exportKind&&"value"!==r.exportKind)&&("ExportAllDeclaration"!==r.type||r.exportKind&&"value"!==r.exportKind)&&"ExportDefaultDeclaration"!==r.type||(this.sawUnambiguousESM=!0),this.assertModuleNodeAllowed(i),r;case h.name:if(this.isContextual("async")){var n=this.state.clone();if(this.next(),this.match(h._function)&&!this.canInsertSemicolon())return this.expect(h._function),this.parseFunction(i,!0,!1,!0);this.state=n}}var o=this.state.value,p=this.parseExpression();return s===h.name&&"Identifier"===p.type&&this.eat(h.colon)?this.parseLabeledStatement(i,o,p):this.parseExpressionStatement(i,p)},s.assertModuleNodeAllowed=function(t){this.options.allowImportExportEverywhere||this.inModule||this.raise(t.start,"'import' and 'export' may appear only with 'sourceType: \"module\"'",{code:"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"})},s.takeDecorators=function(t){var e=this.state.decoratorStack[this.state.decoratorStack.length-1];e.length&&(t.decorators=e,this.resetStartLocationFromNode(t,e[0]),this.state.decoratorStack[this.state.decoratorStack.length-1]=[])},s.canHaveLeadingDecorator=function(){return this.match(h._class)},s.parseDecorators=function(t){for(var e=this.state.decoratorStack[this.state.decoratorStack.length-1];this.match(h.at);){var s=this.parseDecorator();e.push(s)}this.match(h._export)?(t||this.unexpected(),this.hasPlugin("decorators")&&!this.getPluginOption("decorators","decoratorsBeforeExport")&&this.raise(this.state.start,"Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead, or set the 'decoratorsBeforeExport' option to true.")):this.canHaveLeadingDecorator()||this.raise(this.state.start,"Leading decorators must be attached to a class declaration")},s.parseDecorator=function(){this.expectOnePlugin(["decorators-legacy","decorators"]);var t=this.startNode();if(this.next(),this.hasPlugin("decorators")){if(this.state.decoratorStack.push([]),this.eat(h.parenL))t.callee=this.parseExpression(),this.expect(h.parenR);else{for(var e=this.state.start,s=this.state.startLoc,i=this.parseIdentifier(!1);this.eat(h.dot);){var r=this.startNodeAt(e,s);r.object=i,r.property=this.parseIdentifier(!0),r.computed=!1,i=this.finishNode(r,"MemberExpression")}t.callee=i}this.eat(h.parenL)&&(t.arguments=this.parseCallExpressionArguments(h.parenR,!1),this.toReferencedList(t.arguments)),this.state.decoratorStack.pop()}else t.callee=this.parseMaybeAssign();return this.finishNode(t,"Decorator")},s.parseBreakContinueStatement=function(t,e){var s,i="break"===e;for(this.next(),this.isLineTerminator()?t.label=null:this.match(h.name)?(t.label=this.parseIdentifier(),this.semicolon()):this.unexpected(),s=0;s<this.state.labels.length;++s){var r=this.state.labels[s];if(null==t.label||r.name===t.label.name){if(null!=r.kind&&(i||"loop"===r.kind))break;if(t.label&&i)break}}return s===this.state.labels.length&&this.raise(t.start,"Unsyntactic "+e),this.finishNode(t,i?"BreakStatement":"ContinueStatement")},s.parseDebuggerStatement=function(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")},s.parseDoStatement=function(t){return this.next(),this.state.labels.push(Z),t.body=this.parseStatement(!1),this.state.labels.pop(),this.expect(h._while),t.test=this.parseParenExpression(),this.eat(h.semi),this.finishNode(t,"DoWhileStatement")},s.parseForStatement=function(t){this.next(),this.state.labels.push(Z);var e=!1;if(this.state.inAsync&&this.isContextual("await")&&(this.expectPlugin("asyncGenerators"),e=!0,this.next()),this.expect(h.parenL),this.match(h.semi))return e&&this.unexpected(),this.parseFor(t,null);if(this.match(h._var)||this.match(h._let)||this.match(h._const)){var s=this.startNode(),i=this.state.type;if(this.next(),this.parseVar(s,!0,i),this.finishNode(s,"VariableDeclaration"),(this.match(h._in)||this.isContextual("of"))&&1===s.declarations.length){var r=s.declarations[0],a=i===h._var&&r.init&&"ObjectPattern"!=r.id.type&&"ArrayPattern"!=r.id.type&&!this.isContextual("of");if(this.state.strict&&a)this.raise(this.state.start,"for-in initializer in strict mode");else if(a||!r.init)return this.parseForIn(t,s,e)}return e&&this.unexpected(),this.parseFor(t,s)}var n={start:0},o=this.parseExpression(!0,n);if(this.match(h._in)||this.isContextual("of")){var p=this.isContextual("of")?"for-of statement":"for-in statement";return this.toAssignable(o,void 0,p),this.checkLVal(o,void 0,void 0,p),this.parseForIn(t,o,e)}return n.start&&this.unexpected(n.start),e&&this.unexpected(),this.parseFor(t,o)},s.parseFunctionStatement=function(t){return this.next(),this.parseFunction(t,!0)},s.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement(!1),t.alternate=this.eat(h._else)?this.parseStatement(!1):null,this.finishNode(t,"IfStatement")},s.parseReturnStatement=function(t){return this.state.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.state.start,"'return' outside of function"),this.next(),this.isLineTerminator()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")},s.parseSwitchStatement=function(t){this.next(),t.discriminant=this.parseParenExpression();var e,s,i=t.cases=[];for(this.expect(h.braceL),this.state.labels.push(tt);!this.match(h.braceR);)if(this.match(h._case)||this.match(h._default)){var r=this.match(h._case);e&&this.finishNode(e,"SwitchCase"),i.push(e=this.startNode()),e.consequent=[],this.next(),r?e.test=this.parseExpression():(s&&this.raise(this.state.lastTokStart,"Multiple default clauses"),s=!0,e.test=null),this.expect(h.colon)}else e?e.consequent.push(this.parseStatement(!0)):this.unexpected();return e&&this.finishNode(e,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(t,"SwitchStatement")},s.parseThrowStatement=function(t){return this.next(),S.test(this.input.slice(this.state.lastTokEnd,this.state.start))&&this.raise(this.state.lastTokEnd,"Illegal newline after throw"),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")},s.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.match(h._catch)){var e=this.startNode();if(this.next(),this.match(h.parenL)){this.expect(h.parenL),e.param=this.parseBindingAtom();var s=Object.create(null);this.checkLVal(e.param,!0,s,"catch clause"),this.expect(h.parenR)}else this.expectPlugin("optionalCatchBinding"),e.param=null;e.body=this.parseBlock(),t.handler=this.finishNode(e,"CatchClause")}return t.guardedHandlers=$,t.finalizer=this.eat(h._finally)?this.parseBlock():null,t.handler||t.finalizer||this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")},s.parseVarStatement=function(t,e){return this.next(),this.parseVar(t,!1,e),this.semicolon(),this.finishNode(t,"VariableDeclaration")},s.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.state.labels.push(Z),t.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(t,"WhileStatement")},s.parseWithStatement=function(t){return this.state.strict&&this.raise(this.state.start,"'with' in strict mode"),this.next(),t.object=this.parseParenExpression(),t.body=this.parseStatement(!1),this.finishNode(t,"WithStatement")},s.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")},s.parseLabeledStatement=function(t,e,s){for(var i=0,r=this.state.labels;i<r.length;i++){r[i].name===e&&this.raise(s.start,"Label '"+e+"' is already declared")}for(var a=this.state.type.isLoop?"loop":this.match(h._switch)?"switch":null,n=this.state.labels.length-1;n>=0;n--){var o=this.state.labels[n];if(o.statementStart!==t.start)break;o.statementStart=this.state.start,o.kind=a}return this.state.labels.push({name:e,kind:a,statementStart:this.state.start}),t.body=this.parseStatement(!0),("ClassDeclaration"==t.body.type||"VariableDeclaration"==t.body.type&&"var"!==t.body.kind||"FunctionDeclaration"==t.body.type&&(this.state.strict||t.body.generator||t.body.async))&&this.raise(t.body.start,"Invalid labeled declaration"),this.state.labels.pop(),t.label=s,this.finishNode(t,"LabeledStatement")},s.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")},s.parseBlock=function(t){var e=this.startNode();return this.expect(h.braceL),this.parseBlockBody(e,t,!1,h.braceR),this.finishNode(e,"BlockStatement")},s.isValidDirective=function(t){return"ExpressionStatement"===t.type&&"StringLiteral"===t.expression.type&&!t.expression.extra.parenthesized},s.parseBlockBody=function(t,e,s,i){var r=t.body=[],a=t.directives=[];this.parseBlockOrModuleBlockBody(r,e?a:void 0,s,i)},s.parseBlockOrModuleBlockBody=function(t,e,s,i){for(var r,a,n=!1;!this.eat(i);){n||!this.state.containsOctal||a||(a=this.state.octalPosition);var o=this.parseStatement(!0,s);if(e&&!n&&this.isValidDirective(o)){var h=this.stmtToDirective(o);e.push(h),void 0===r&&"use strict"===h.value.value&&(r=this.state.strict,this.setStrict(!0),a&&this.raise(a,"Octal literal in strict mode"))}else n=!0,t.push(o)}!1===r&&this.setStrict(!1)},s.parseFor=function(t,e){return t.init=e,this.expect(h.semi),t.test=this.match(h.semi)?null:this.parseExpression(),this.expect(h.semi),t.update=this.match(h.parenR)?null:this.parseExpression(),this.expect(h.parenR),t.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(t,"ForStatement")},s.parseForIn=function(t,e,s){var i=this.match(h._in)?"ForInStatement":"ForOfStatement";return s?this.eatContextual("of"):this.next(),"ForOfStatement"===i&&(t.await=!!s),t.left=e,t.right=this.parseExpression(),this.expect(h.parenR),t.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(t,i)},s.parseVar=function(t,e,s){var i=t.declarations=[];for(t.kind=s.keyword;;){var r=this.startNode();if(this.parseVarHead(r),this.eat(h.eq)?r.init=this.parseMaybeAssign(e):(s!==h._const||this.match(h._in)||this.isContextual("of")?"Identifier"===r.id.type||e&&(this.match(h._in)||this.isContextual("of"))||this.raise(this.state.lastTokEnd,"Complex binding patterns require an initialization value"):this.hasPlugin("typescript")||this.unexpected(),r.init=null),i.push(this.finishNode(r,"VariableDeclarator")),!this.eat(h.comma))break}return t},s.parseVarHead=function(t){t.id=this.parseBindingAtom(),this.checkLVal(t.id,!0,void 0,"variable declaration")},s.parseFunction=function(t,e,s,i,r){var a=this.state.inFunction,n=this.state.inMethod,o=this.state.inGenerator,p=this.state.inClassProperty;return this.state.inFunction=!0,this.state.inMethod=!1,this.state.inClassProperty=!1,this.initFunction(t,i),this.match(h.star)&&(t.async&&this.expectPlugin("asyncGenerators"),t.generator=!0,this.next()),!e||r||this.match(h.name)||this.match(h._yield)||this.unexpected(),e||(this.state.inGenerator=t.generator),(this.match(h.name)||this.match(h._yield))&&(t.id=this.parseBindingIdentifier()),e&&(this.state.inGenerator=t.generator),this.parseFunctionParams(t),this.parseFunctionBodyAndFinish(t,e?"FunctionDeclaration":"FunctionExpression",s),this.state.inFunction=a,this.state.inMethod=n,this.state.inGenerator=o,this.state.inClassProperty=p,t},s.parseFunctionParams=function(t,e){var s=this.state.inParameters;this.state.inParameters=!0,this.expect(h.parenL),t.params=this.parseBindingList(h.parenR,!1,e),this.state.inParameters=s},s.parseClass=function(t,e,s){return this.next(),this.takeDecorators(t),this.parseClassId(t,e,s),this.parseClassSuper(t),this.parseClassBody(t),this.finishNode(t,e?"ClassDeclaration":"ClassExpression")},s.isClassProperty=function(){return this.match(h.eq)||this.match(h.semi)||this.match(h.braceR)},s.isClassMethod=function(){return this.match(h.parenL)},s.isNonstaticConstructor=function(t){return!(t.computed||t.static||"constructor"!==t.key.name&&"constructor"!==t.key.value)},s.parseClassBody=function(t){var e=this.state.strict;this.state.strict=!0,this.state.classLevel++;var s={hadConstructor:!1},i=[],r=this.startNode();for(r.body=[],this.expect(h.braceL);!this.eat(h.braceR);)if(this.eat(h.semi))i.length>0&&this.raise(this.state.lastTokEnd,"Decorators must not be followed by a semicolon");else if(this.match(h.at))i.push(this.parseDecorator());else{var a=this.startNode();i.length&&(a.decorators=i,this.resetStartLocationFromNode(a,i[0]),i=[]),this.parseClassMember(r,a,s),"constructor"===a.kind&&a.decorators&&a.decorators.length>0&&this.raise(a.start,"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?")}i.length&&this.raise(this.state.start,"You have trailing decorators with no method"),t.body=this.finishNode(r,"ClassBody"),this.state.classLevel--,this.state.strict=e},s.parseClassMember=function(t,e,s){var i=!1,r=this.state.containsEsc;if(this.match(h.name)&&"static"===this.state.value){var a=this.parseIdentifier(!0);if(this.isClassMethod()){var n=e;return n.kind="method",n.computed=!1,n.key=a,n.static=!1,void this.pushClassMethod(t,n,!1,!1,!1)}if(this.isClassProperty()){var o=e;return o.computed=!1,o.key=a,o.static=!1,void t.body.push(this.parseClassProperty(o))}if(r)throw this.unexpected();i=!0}this.parseClassMemberWithIsStatic(t,e,s,i)},s.parseClassMemberWithIsStatic=function(t,e,s,i){var r=e,a=e,n=e,o=e,p=r,c=r;if(e.static=i,this.eat(h.star))return p.kind="method",this.parseClassPropertyName(p),"PrivateName"===p.key.type?void this.pushClassPrivateMethod(t,a,!0,!1):(this.isNonstaticConstructor(r)&&this.raise(r.key.start,"Constructor can't be a generator"),void this.pushClassMethod(t,r,!0,!1,!1));var l=this.parseClassPropertyName(e),u="PrivateName"===l.type,d="Identifier"===l.type;if(this.parsePostMemberNameModifiers(c),this.isClassMethod()){if(p.kind="method",u)return void this.pushClassPrivateMethod(t,a,!1,!1);var f=this.isNonstaticConstructor(r);f&&(r.kind="constructor",r.decorators&&this.raise(r.start,"You can't attach decorators to a class constructor"),s.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(l.start,"Duplicate constructor in the same class"),s.hadConstructor=!0),this.pushClassMethod(t,r,!1,!1,f)}else if(this.isClassProperty())u?this.pushClassPrivateProperty(t,o):this.pushClassProperty(t,n);else if(d&&"async"===l.name&&!this.isLineTerminator()){var m=this.match(h.star);m&&(this.expectPlugin("asyncGenerators"),this.next()),p.kind="method",this.parseClassPropertyName(p),"PrivateName"===p.key.type?this.pushClassPrivateMethod(t,a,m,!0):(this.isNonstaticConstructor(r)&&this.raise(r.key.start,"Constructor can't be an async function"),this.pushClassMethod(t,r,m,!0,!1))}else!d||"get"!==l.name&&"set"!==l.name||this.isLineTerminator()&&this.match(h.star)?this.isLineTerminator()?u?this.pushClassPrivateProperty(t,o):this.pushClassProperty(t,n):this.unexpected():(p.kind=l.name,this.parseClassPropertyName(r),"PrivateName"===p.key.type?this.pushClassPrivateMethod(t,a,!1,!1):(this.isNonstaticConstructor(r)&&this.raise(r.key.start,"Constructor can't have get/set modifier"),this.pushClassMethod(t,r,!1,!1,!1)),this.checkGetterSetterParams(r))},s.parseClassPropertyName=function(t){var e=this.parsePropertyName(t);return t.computed||!t.static||"prototype"!==e.name&&"prototype"!==e.value||this.raise(e.start,"Classes may not have static property named prototype"),"PrivateName"===e.type&&"constructor"===e.id.name&&this.raise(e.start,"Classes may not have a private field named '#constructor'"),e},s.pushClassProperty=function(t,e){this.isNonstaticConstructor(e)&&this.raise(e.key.start,"Classes may not have a non-static field named 'constructor'"),t.body.push(this.parseClassProperty(e))},s.pushClassPrivateProperty=function(t,e){this.expectPlugin("classPrivateProperties",e.key.start),t.body.push(this.parseClassPrivateProperty(e))},s.pushClassMethod=function(t,e,s,i,r){t.body.push(this.parseMethod(e,s,i,r,"ClassMethod"))},s.pushClassPrivateMethod=function(t,e,s,i){this.expectPlugin("classPrivateMethods",e.key.start),t.body.push(this.parseMethod(e,s,i,!1,"ClassPrivateMethod"))},s.parsePostMemberNameModifiers=function(t){},s.parseAccessModifier=function(){},s.parseClassPrivateProperty=function(t){var e=this.state.inMethod;return this.state.inMethod=!1,this.state.inClassProperty=!0,t.value=this.eat(h.eq)?this.parseMaybeAssign():null,this.semicolon(),this.state.inClassProperty=!1,this.state.inMethod=e,this.finishNode(t,"ClassPrivateProperty")},s.parseClassProperty=function(t){t.typeAnnotation||this.expectPlugin("classProperties");var e=this.state.inMethod;return this.state.inMethod=!1,this.state.inClassProperty=!0,this.match(h.eq)?(this.expectPlugin("classProperties"),this.next(),t.value=this.parseMaybeAssign()):t.value=null,this.semicolon(),this.state.inClassProperty=!1,this.state.inMethod=e,this.finishNode(t,"ClassProperty")},s.parseClassId=function(t,e,s){this.match(h.name)?t.id=this.parseIdentifier():s||!e?t.id=null:this.unexpected(null,"A class name is required")},s.parseClassSuper=function(t){t.superClass=this.eat(h._extends)?this.parseExprSubscripts():null},s.parseExport=function(t){if(this.shouldParseExportStar()){if(this.parseExportStar(t),"ExportAllDeclaration"===t.type)return t}else if(this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom");var e=this.startNode();e.exported=this.parseIdentifier(!0);var s=[this.finishNode(e,"ExportDefaultSpecifier")];if(t.specifiers=s,this.match(h.comma)&&this.lookahead().type===h.star){this.expect(h.comma);var i=this.startNode();this.expect(h.star),this.expectContextual("as"),i.exported=this.parseIdentifier(),s.push(this.finishNode(i,"ExportNamespaceSpecifier"))}else this.parseExportSpecifiersMaybe(t);this.parseExportFrom(t,!0)}else{if(this.eat(h._default))return t.declaration=this.parseExportDefaultExpression(),this.checkExport(t,!0,!0),this.finishNode(t,"ExportDefaultDeclaration");if(this.shouldParseExportDeclaration()){if(this.isContextual("async")){var r=this.lookahead();r.type!==h._function&&this.unexpected(r.start,'Unexpected token, expected "function"')}t.specifiers=[],t.source=null,t.declaration=this.parseExportDeclaration(t)}else t.declaration=null,t.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(t)}return this.checkExport(t,!0),this.finishNode(t,"ExportNamedDeclaration")},s.parseExportDefaultExpression=function(){var t=this.startNode();if(this.eat(h._function))return this.parseFunction(t,!0,!1,!1,!0);if(this.isContextual("async")&&this.lookahead().type===h._function)return this.eatContextual("async"),this.eat(h._function),this.parseFunction(t,!0,!1,!0,!0);if(this.match(h._class))return this.parseClass(t,!0,!0);if(this.match(h.at))return this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")&&this.unexpected(this.state.start,"Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax"),this.parseDecorators(!1),this.parseClass(t,!0,!0);if(this.match(h._let)||this.match(h._const)||this.match(h._var))return this.raise(this.state.start,"Only expressions, functions or classes are allowed as the `default` export.");var e=this.parseMaybeAssign();return this.semicolon(),e},s.parseExportDeclaration=function(t){return this.parseStatement(!0)},s.isExportDefaultSpecifier=function(){if(this.match(h.name))return"async"!==this.state.value;if(!this.match(h._default))return!1;var t=this.lookahead();return t.type===h.comma||t.type===h.name&&"from"===t.value},s.parseExportSpecifiersMaybe=function(t){this.eat(h.comma)&&(t.specifiers=t.specifiers.concat(this.parseExportSpecifiers()))},s.parseExportFrom=function(t,e){this.eatContextual("from")?(t.source=this.match(h.string)?this.parseExprAtom():this.unexpected(),this.checkExport(t)):e?this.unexpected():t.source=null,this.semicolon()},s.shouldParseExportStar=function(){return this.match(h.star)},s.parseExportStar=function(t){this.expect(h.star),this.isContextual("as")?this.parseExportNamespace(t):(this.parseExportFrom(t,!0),this.finishNode(t,"ExportAllDeclaration"))},s.parseExportNamespace=function(t){this.expectPlugin("exportNamespaceFrom");var e=this.startNodeAt(this.state.lastTokStart,this.state.lastTokStartLoc);this.next(),e.exported=this.parseIdentifier(!0),t.specifiers=[this.finishNode(e,"ExportNamespaceSpecifier")],this.parseExportSpecifiersMaybe(t),this.parseExportFrom(t,!0)},s.shouldParseExportDeclaration=function(){if(this.match(h.at)&&(this.expectOnePlugin(["decorators","decorators-legacy"]),this.hasPlugin("decorators"))){if(!this.getPluginOption("decorators","decoratorsBeforeExport"))return!0;this.unexpected(this.state.start,"Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax")}return"var"===this.state.type.keyword||"const"===this.state.type.keyword||"let"===this.state.type.keyword||"function"===this.state.type.keyword||"class"===this.state.type.keyword||this.isContextual("async")},s.checkExport=function(t,e,s){if(e)if(s)this.checkDuplicateExports(t,"default");else if(t.specifiers&&t.specifiers.length)for(var i=0,r=t.specifiers;i<r.length;i++){var a=r[i];this.checkDuplicateExports(a,a.exported.name)}else if(t.declaration)if("FunctionDeclaration"===t.declaration.type||"ClassDeclaration"===t.declaration.type){var n=t.declaration.id;if(!n)throw new Error("Assertion failure");this.checkDuplicateExports(t,n.name)}else if("VariableDeclaration"===t.declaration.type)for(var o=0,h=t.declaration.declarations;o<h.length;o++){var p=h[o];this.checkDeclaration(p.id)}if(this.state.decoratorStack[this.state.decoratorStack.length-1].length){var c=t.declaration&&("ClassDeclaration"===t.declaration.type||"ClassExpression"===t.declaration.type);if(!t.declaration||!c)throw this.raise(t.start,"You can only use decorators on an export when exporting a class");this.takeDecorators(t.declaration)}},s.checkDeclaration=function(t){if("ObjectPattern"===t.type)for(var e=0,s=t.properties;e<s.length;e++){var i=s[e];this.checkDeclaration(i)}else if("ArrayPattern"===t.type)for(var r=0,a=t.elements;r<a.length;r++){var n=a[r];n&&this.checkDeclaration(n)}else"ObjectProperty"===t.type?this.checkDeclaration(t.value):"RestElement"===t.type?this.checkDeclaration(t.argument):"Identifier"===t.type&&this.checkDuplicateExports(t,t.name)},s.checkDuplicateExports=function(t,e){this.state.exportedIdentifiers.indexOf(e)>-1&&this.raiseDuplicateExportError(t,e),this.state.exportedIdentifiers.push(e)},s.raiseDuplicateExportError=function(t,e){throw this.raise(t.start,"default"===e?"Only one default export allowed per module.":"`"+e+"` has already been exported. Exported identifiers must be unique.")},s.parseExportSpecifiers=function(){var t,e=[],s=!0;for(this.expect(h.braceL);!this.eat(h.braceR);){if(s)s=!1;else if(this.expect(h.comma),this.eat(h.braceR))break;var i=this.match(h._default);i&&!t&&(t=!0);var r=this.startNode();r.local=this.parseIdentifier(i),r.exported=this.eatContextual("as")?this.parseIdentifier(!0):r.local.__clone(),e.push(this.finishNode(r,"ExportSpecifier"))}return t&&!this.isContextual("from")&&this.unexpected(),e},s.parseImport=function(t){return this.match(h.string)?(t.specifiers=[],t.source=this.parseExprAtom()):(t.specifiers=[],this.parseImportSpecifiers(t),this.expectContextual("from"),t.source=this.match(h.string)?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(t,"ImportDeclaration")},s.shouldParseDefaultImport=function(t){return this.match(h.name)},s.parseImportSpecifierLocal=function(t,e,s,i){e.local=this.parseIdentifier(),this.checkLVal(e.local,!0,void 0,i),t.specifiers.push(this.finishNode(e,s))},s.parseImportSpecifiers=function(t){var e=!0;if(!this.shouldParseDefaultImport(t)||(this.parseImportSpecifierLocal(t,this.startNode(),"ImportDefaultSpecifier","default import specifier"),this.eat(h.comma))){if(this.match(h.star)){var s=this.startNode();return this.next(),this.expectContextual("as"),void this.parseImportSpecifierLocal(t,s,"ImportNamespaceSpecifier","import namespace specifier")}for(this.expect(h.braceL);!this.eat(h.braceR);){if(e)e=!1;else if(this.eat(h.colon)&&this.unexpected(null,"ES2015 named imports do not destructure. Use another statement for destructuring after the import."),this.expect(h.comma),this.eat(h.braceR))break;this.parseImportSpecifier(t)}}},s.parseImportSpecifier=function(t){var e=this.startNode();e.imported=this.parseIdentifier(!0),this.eatContextual("as")?e.local=this.parseIdentifier():(this.checkReservedWord(e.imported.name,e.start,!0,!0),e.local=e.imported.__clone()),this.checkLVal(e.local,!0,void 0,"import specifier"),t.specifiers.push(this.finishNode(e,"ImportSpecifier"))},e}(function(t){function e(){return t.apply(this,arguments)||this}i(e,t);var s=e.prototype;return s.checkPropClash=function(t,e){if(!t.computed&&!t.kind){var s=t.key;"__proto__"===("Identifier"===s.type?s.name:String(s.value))&&(e.proto&&this.raise(s.start,"Redefinition of __proto__ property"),e.proto=!0)}},s.getExpression=function(){this.nextToken();var t=this.parseExpression();return this.match(h.eof)||this.unexpected(),t.comments=this.state.comments,t},s.parseExpression=function(t,e){var s=this.state.start,i=this.state.startLoc,r=this.parseMaybeAssign(t,e);if(this.match(h.comma)){var a=this.startNodeAt(s,i);for(a.expressions=[r];this.eat(h.comma);)a.expressions.push(this.parseMaybeAssign(t,e));return this.toReferencedList(a.expressions),this.finishNode(a,"SequenceExpression")}return r},s.parseMaybeAssign=function(t,e,s,i){var r,a=this.state.start,n=this.state.startLoc;if(this.match(h._yield)&&this.state.inGenerator){var o=this.parseYield();return s&&(o=s.call(this,o,a,n)),o}e?r=!1:(e={start:0},r=!0),(this.match(h.parenL)||this.match(h.name)||this.match(h._yield))&&(this.state.potentialArrowAt=this.state.start);var p=this.parseMaybeConditional(t,e,i);if(s&&(p=s.call(this,p,a,n)),this.state.type.isAssign){var c,l=this.startNodeAt(a,n),u=this.state.value;if(l.operator=u,"??="===u&&(this.expectPlugin("nullishCoalescingOperator"),this.expectPlugin("logicalAssignment")),"||="!==u&&"&&="!==u||this.expectPlugin("logicalAssignment"),l.left=this.match(h.eq)?this.toAssignable(p,void 0,"assignment expression"):p,e.start=0,this.checkLVal(p,void 0,void 0,"assignment expression"),p.extra&&p.extra.parenthesized)"ObjectPattern"===p.type?c="`({a}) = 0` use `({a} = 0)`":"ArrayPattern"===p.type&&(c="`([a]) = 0` use `([a] = 0)`"),c&&this.raise(p.start,"You're trying to assign to a parenthesized expression, eg. instead of "+c);return this.next(),l.right=this.parseMaybeAssign(t),this.finishNode(l,"AssignmentExpression")}return r&&e.start&&this.unexpected(e.start),p},s.parseMaybeConditional=function(t,e,s){var i=this.state.start,r=this.state.startLoc,a=this.state.potentialArrowAt,n=this.parseExprOps(t,e);return"ArrowFunctionExpression"===n.type&&n.start===a?n:e&&e.start?n:this.parseConditional(n,t,i,r,s)},s.parseConditional=function(t,e,s,i,r){if(this.eat(h.question)){var a=this.startNodeAt(s,i);return a.test=t,a.consequent=this.parseMaybeAssign(),this.expect(h.colon),a.alternate=this.parseMaybeAssign(e),this.finishNode(a,"ConditionalExpression")}return t},s.parseExprOps=function(t,e){var s=this.state.start,i=this.state.startLoc,r=this.state.potentialArrowAt,a=this.parseMaybeUnary(e);return"ArrowFunctionExpression"===a.type&&a.start===r?a:e&&e.start?a:this.parseExprOp(a,s,i,-1,t)},s.parseExprOp=function(t,e,s,i,r){var a=this.state.type.binop;if(!(null==a||r&&this.match(h._in))&&a>i){var n=this.startNodeAt(e,s),o=this.state.value;n.left=t,n.operator=o,"**"!==o||"UnaryExpression"!==t.type||!t.extra||t.extra.parenthesizedArgument||t.extra.parenthesized||this.raise(t.argument.start,"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");var p=this.state.type;p===h.nullishCoalescing?this.expectPlugin("nullishCoalescingOperator"):p===h.pipeline&&this.expectPlugin("pipelineOperator"),this.next();var c=this.state.start,l=this.state.startLoc;if(p===h.pipeline&&this.match(h.name)&&"await"===this.state.value&&this.state.inAsync)throw this.raise(this.state.start,'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal');return n.right=this.parseExprOp(this.parseMaybeUnary(),c,l,p.rightAssociative?a-1:a,r),this.finishNode(n,p===h.logicalOR||p===h.logicalAND||p===h.nullishCoalescing?"LogicalExpression":"BinaryExpression"),this.parseExprOp(n,e,s,i,r)}return t},s.parseMaybeUnary=function(t){if(this.state.type.prefix){var e=this.startNode(),s=this.match(h.incDec);e.operator=this.state.value,e.prefix=!0,"throw"===e.operator&&this.expectPlugin("throwExpressions"),this.next();var i=this.state.type;if(e.argument=this.parseMaybeUnary(),this.addExtra(e,"parenthesizedArgument",!(i!==h.parenL||e.argument.extra&&e.argument.extra.parenthesized)),t&&t.start&&this.unexpected(t.start),s)this.checkLVal(e.argument,void 0,void 0,"prefix operation");else if(this.state.strict&&"delete"===e.operator){var r=e.argument;"Identifier"===r.type?this.raise(e.start,"Deleting local variable in strict mode"):"MemberExpression"===r.type&&"PrivateName"===r.property.type&&this.raise(e.start,"Deleting a private field is not allowed")}return this.finishNode(e,s?"UpdateExpression":"UnaryExpression")}var a=this.state.start,n=this.state.startLoc,o=this.parseExprSubscripts(t);if(t&&t.start)return o;for(;this.state.type.postfix&&!this.canInsertSemicolon();){var p=this.startNodeAt(a,n);p.operator=this.state.value,p.prefix=!1,p.argument=o,this.checkLVal(o,void 0,void 0,"postfix operation"),this.next(),o=this.finishNode(p,"UpdateExpression")}return o},s.parseExprSubscripts=function(t){var e=this.state.start,s=this.state.startLoc,i=this.state.potentialArrowAt,r=this.parseExprAtom(t);return"ArrowFunctionExpression"===r.type&&r.start===i?r:t&&t.start?r:this.parseSubscripts(r,e,s)},s.parseSubscripts=function(t,e,s,i){var r={optionalChainMember:!1,stop:!1};do{t=this.parseSubscript(t,e,s,i,r)}while(!r.stop);return t},s.parseSubscript=function(t,e,s,i,r){if(!i&&this.eat(h.doubleColon)){var a=this.startNodeAt(e,s);return a.object=t,a.callee=this.parseNoCallExpr(),r.stop=!0,this.parseSubscripts(this.finishNode(a,"BindExpression"),e,s,i)}if(this.match(h.questionDot)){if(this.expectPlugin("optionalChaining"),r.optionalChainMember=!0,i&&this.lookahead().type==h.parenL)return r.stop=!0,t;this.next();var n=this.startNodeAt(e,s);if(this.eat(h.bracketL))return n.object=t,n.property=this.parseExpression(),n.computed=!0,n.optional=!0,this.expect(h.bracketR),this.finishNode(n,"OptionalMemberExpression");if(this.eat(h.parenL)){var o=this.atPossibleAsync(t);return n.callee=t,n.arguments=this.parseCallExpressionArguments(h.parenR,o),n.optional=!0,this.finishNode(n,"OptionalCallExpression")}return n.object=t,n.property=this.parseIdentifier(!0),n.computed=!1,n.optional=!0,this.finishNode(n,"OptionalMemberExpression")}if(this.eat(h.dot)){var p=this.startNodeAt(e,s);return p.object=t,p.property=this.parseMaybePrivateName(),p.computed=!1,r.optionalChainMember?(p.optional=!1,this.finishNode(p,"OptionalMemberExpression")):this.finishNode(p,"MemberExpression")}if(this.eat(h.bracketL)){var c=this.startNodeAt(e,s);return c.object=t,c.property=this.parseExpression(),c.computed=!0,this.expect(h.bracketR),r.optionalChainMember?(c.optional=!1,this.finishNode(c,"OptionalMemberExpression")):this.finishNode(c,"MemberExpression")}if(!i&&this.match(h.parenL)){var l=this.atPossibleAsync(t);this.next();var u=this.startNodeAt(e,s);u.callee=t;var d={start:-1};return u.arguments=this.parseCallExpressionArguments(h.parenR,l,d),r.optionalChainMember?this.finishOptionalCallExpression(u):this.finishCallExpression(u),l&&this.shouldParseAsyncArrow()?(r.stop=!0,d.start>-1&&this.raise(d.start,"A trailing comma is not permitted after the rest element"),this.parseAsyncArrowFromCallExpression(this.startNodeAt(e,s),u)):(this.toReferencedList(u.arguments),u)}if(this.match(h.backQuote)){var f=this.startNodeAt(e,s);return f.tag=t,f.quasi=this.parseTemplate(!0),r.optionalChainMember&&this.raise(e,"Tagged Template Literals are not allowed in optionalChain"),this.finishNode(f,"TaggedTemplateExpression")}return r.stop=!0,t},s.atPossibleAsync=function(t){return!this.state.containsEsc&&this.state.potentialArrowAt===t.start&&"Identifier"===t.type&&"async"===t.name&&!this.canInsertSemicolon()},s.finishCallExpression=function(t){if("Import"===t.callee.type){1!==t.arguments.length&&this.raise(t.start,"import() requires exactly one argument");var e=t.arguments[0];e&&"SpreadElement"===e.type&&this.raise(e.start,"... is not allowed in import()")}return this.finishNode(t,"CallExpression")},s.finishOptionalCallExpression=function(t){if("Import"===t.callee.type){1!==t.arguments.length&&this.raise(t.start,"import() requires exactly one argument");var e=t.arguments[0];e&&"SpreadElement"===e.type&&this.raise(e.start,"... is not allowed in import()")}return this.finishNode(t,"OptionalCallExpression")},s.parseCallExpressionArguments=function(t,e,s){for(var i,r=[],a=!0;!this.eat(t);){if(a)a=!1;else if(this.expect(h.comma),this.eat(t))break;this.match(h.parenL)&&!i&&(i=this.state.start),r.push(this.parseExprListItem(!1,e?{start:0}:void 0,e?{start:0}:void 0,e?s:void 0))}return e&&i&&this.shouldParseAsyncArrow()&&this.unexpected(),r},s.shouldParseAsyncArrow=function(){return this.match(h.arrow)},s.parseAsyncArrowFromCallExpression=function(t,e){var s=this.state.yieldInPossibleArrowParameters;return this.state.yieldInPossibleArrowParameters=null,this.expect(h.arrow),this.parseArrowExpression(t,e.arguments,!0),this.state.yieldInPossibleArrowParameters=s,t},s.parseNoCallExpr=function(){var t=this.state.start,e=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,e,!0)},s.parseExprAtom=function(t){var e,s=this.state.potentialArrowAt===this.state.start;switch(this.state.type){case h._super:return this.state.inMethod||this.state.inClassProperty||this.options.allowSuperOutsideMethod||this.raise(this.state.start,"super is only allowed in object methods and classes"),e=this.startNode(),this.next(),this.match(h.parenL)||this.match(h.bracketL)||this.match(h.dot)||this.unexpected(),this.match(h.parenL)&&"constructor"!==this.state.inMethod&&!this.options.allowSuperOutsideMethod&&this.raise(e.start,"super() is only valid inside a class constructor. Make sure the method name is spelled exactly as 'constructor'."),this.finishNode(e,"Super");case h._import:return this.lookahead().type===h.dot?this.parseImportMetaProperty():(this.expectPlugin("dynamicImport"),e=this.startNode(),this.next(),this.match(h.parenL)||this.unexpected(null,h.parenL),this.finishNode(e,"Import"));case h._this:return e=this.startNode(),this.next(),this.finishNode(e,"ThisExpression");case h._yield:this.state.inGenerator&&this.unexpected();case h.name:e=this.startNode();var i="await"===this.state.value&&(this.state.inAsync||!this.state.inFunction&&this.options.allowAwaitOutsideFunction),r=this.state.containsEsc,a=this.shouldAllowYieldIdentifier(),n=this.parseIdentifier(i||a);if("await"===n.name){if(this.state.inAsync||this.inModule||!this.state.inFunction&&this.options.allowAwaitOutsideFunction)return this.parseAwait(e)}else{if(!r&&"async"===n.name&&this.match(h._function)&&!this.canInsertSemicolon())return this.next(),this.parseFunction(e,!1,!1,!0);if(s&&"async"===n.name&&this.match(h.name)){var o=this.state.yieldInPossibleArrowParameters;this.state.yieldInPossibleArrowParameters=null;var p=[this.parseIdentifier()];return this.expect(h.arrow),this.parseArrowExpression(e,p,!0),this.state.yieldInPossibleArrowParameters=o,e}}if(s&&!this.canInsertSemicolon()&&this.eat(h.arrow)){var c=this.state.yieldInPossibleArrowParameters;return this.state.yieldInPossibleArrowParameters=null,this.parseArrowExpression(e,[n]),this.state.yieldInPossibleArrowParameters=c,e}return n;case h._do:this.expectPlugin("doExpressions");var l=this.startNode();this.next();var u=this.state.inFunction,d=this.state.labels;return this.state.labels=[],this.state.inFunction=!1,l.body=this.parseBlock(!1),this.state.inFunction=u,this.state.labels=d,this.finishNode(l,"DoExpression");case h.regexp:var f=this.state.value;return(e=this.parseLiteral(f.value,"RegExpLiteral")).pattern=f.pattern,e.flags=f.flags,e;case h.num:return this.parseLiteral(this.state.value,"NumericLiteral");case h.bigint:return this.parseLiteral(this.state.value,"BigIntLiteral");case h.string:return this.parseLiteral(this.state.value,"StringLiteral");case h._null:return e=this.startNode(),this.next(),this.finishNode(e,"NullLiteral");case h._true:case h._false:return this.parseBooleanLiteral();case h.parenL:return this.parseParenAndDistinguishExpression(s);case h.bracketL:return e=this.startNode(),this.next(),e.elements=this.parseExprList(h.bracketR,!0,t),this.toReferencedList(e.elements),this.finishNode(e,"ArrayExpression");case h.braceL:return this.parseObj(!1,t);case h._function:return this.parseFunctionExpression();case h.at:this.parseDecorators();case h._class:return e=this.startNode(),this.takeDecorators(e),this.parseClass(e,!1);case h._new:return this.parseNew();case h.backQuote:return this.parseTemplate(!1);case h.doubleColon:e=this.startNode(),this.next(),e.object=null;var m=e.callee=this.parseNoCallExpr();if("MemberExpression"===m.type)return this.finishNode(e,"BindExpression");throw this.raise(m.start,"Binding should be performed on object property.");default:throw this.unexpected()}},s.parseBooleanLiteral=function(){var t=this.startNode();return t.value=this.match(h._true),this.next(),this.finishNode(t,"BooleanLiteral")},s.parseMaybePrivateName=function(){if(this.match(h.hash)){this.expectOnePlugin(["classPrivateProperties","classPrivateMethods"]);var t=this.startNode();return this.next(),t.id=this.parseIdentifier(!0),this.finishNode(t,"PrivateName")}return this.parseIdentifier(!0)},s.parseFunctionExpression=function(){var t=this.startNode(),e=this.parseIdentifier(!0);return this.state.inGenerator&&this.eat(h.dot)?this.parseMetaProperty(t,e,"sent"):this.parseFunction(t,!1)},s.parseMetaProperty=function(t,e,s){t.meta=e,"function"===e.name&&"sent"===s&&(this.isContextual(s)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected());var i=this.state.containsEsc;return t.property=this.parseIdentifier(!0),(t.property.name!==s||i)&&this.raise(t.property.start,"The only valid meta property for "+e.name+" is "+e.name+"."+s),this.finishNode(t,"MetaProperty")},s.parseImportMetaProperty=function(){var t=this.startNode(),e=this.parseIdentifier(!0);return this.expect(h.dot),"import"===e.name&&(this.isContextual("meta")?this.expectPlugin("importMeta"):this.hasPlugin("importMeta")||this.raise(e.start,"Dynamic imports require a parameter: import('a.js').then")),this.inModule||this.raise(e.start,"import.meta may appear only with 'sourceType: \"module\"'",{code:"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"}),this.sawUnambiguousESM=!0,this.parseMetaProperty(t,e,"meta")},s.parseLiteral=function(t,e,s,i){s=s||this.state.start,i=i||this.state.startLoc;var r=this.startNodeAt(s,i);return this.addExtra(r,"rawValue",t),this.addExtra(r,"raw",this.input.slice(s,this.state.end)),r.value=t,this.next(),this.finishNode(r,e)},s.parseParenExpression=function(){this.expect(h.parenL);var t=this.parseExpression();return this.expect(h.parenR),t},s.parseParenAndDistinguishExpression=function(t){var e,s=this.state.start,i=this.state.startLoc;this.expect(h.parenL);var r=this.state.maybeInArrowParameters,a=this.state.yieldInPossibleArrowParameters;this.state.maybeInArrowParameters=!0,this.state.yieldInPossibleArrowParameters=null;for(var n,o,p=this.state.start,c=this.state.startLoc,l=[],u={start:0},d={start:0},f=!0;!this.match(h.parenR);){if(f)f=!1;else if(this.expect(h.comma,d.start||null),this.match(h.parenR)){o=this.state.start;break}if(this.match(h.ellipsis)){var m=this.state.start,y=this.state.startLoc;n=this.state.start,l.push(this.parseParenItem(this.parseRest(),m,y)),this.match(h.comma)&&this.lookahead().type===h.parenR&&this.raise(this.state.start,"A trailing comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,u,this.parseParenItem,d))}var x=this.state.start,v=this.state.startLoc;this.expect(h.parenR),this.state.maybeInArrowParameters=r;var P=this.startNodeAt(s,i);if(t&&this.shouldParseArrow()&&(P=this.parseArrow(P))){for(var g=0;g<l.length;g++){var b=l[g];b.extra&&b.extra.parenthesized&&this.unexpected(b.extra.parenStart)}return this.parseArrowExpression(P,l),this.state.yieldInPossibleArrowParameters=a,P}return this.state.yieldInPossibleArrowParameters=a,l.length||this.unexpected(this.state.lastTokStart),o&&this.unexpected(o),n&&this.unexpected(n),u.start&&this.unexpected(u.start),d.start&&this.unexpected(d.start),l.length>1?((e=this.startNodeAt(p,c)).expressions=l,this.toReferencedList(e.expressions),this.finishNodeAt(e,"SequenceExpression",x,v)):e=l[0],this.addExtra(e,"parenthesized",!0),this.addExtra(e,"parenStart",s),e},s.shouldParseArrow=function(){return!this.canInsertSemicolon()},s.parseArrow=function(t){if(this.eat(h.arrow))return t},s.parseParenItem=function(t,e,s){return t},s.parseNew=function(){var t=this.startNode(),e=this.parseIdentifier(!0);if(this.eat(h.dot)){var s=this.parseMetaProperty(t,e,"target");if(!this.state.inFunction&&!this.state.inClassProperty){var i="new.target can only be used in functions";this.hasPlugin("classProperties")&&(i+=" or class properties"),this.raise(s.start,i)}return s}return t.callee=this.parseNoCallExpr(),"OptionalMemberExpression"!==t.callee.type&&"OptionalCallExpression"!==t.callee.type||this.raise(this.state.lastTokEnd,"constructors in/after an Optional Chain are not allowed"),this.eat(h.questionDot)&&this.raise(this.state.start,"constructors in/after an Optional Chain are not allowed"),this.parseNewArguments(t),this.finishNode(t,"NewExpression")},s.parseNewArguments=function(t){if(this.eat(h.parenL)){var e=this.parseExprList(h.parenR);this.toReferencedList(e),t.arguments=e}else t.arguments=[]},s.parseTemplateElement=function(t){var e=this.startNode();return null===this.state.value&&(t?this.state.invalidTemplateEscapePosition=null:this.raise(this.state.invalidTemplateEscapePosition||0,"Invalid escape sequence in template")),e.value={raw:this.input.slice(this.state.start,this.state.end).replace(/\r\n?/g,"\n"),cooked:this.state.value},this.next(),e.tail=this.match(h.backQuote),this.finishNode(e,"TemplateElement")},s.parseTemplate=function(t){var e=this.startNode();this.next(),e.expressions=[];var s=this.parseTemplateElement(t);for(e.quasis=[s];!s.tail;)this.expect(h.dollarBraceL),e.expressions.push(this.parseExpression()),this.expect(h.braceR),e.quasis.push(s=this.parseTemplateElement(t));return this.next(),this.finishNode(e,"TemplateLiteral")},s.parseObj=function(t,e){var s=[],i=Object.create(null),r=!0,a=this.startNode();a.properties=[],this.next();for(var n=null;!this.eat(h.braceR);){if(r)r=!1;else if(this.expect(h.comma),this.eat(h.braceR))break;if(this.match(h.at))if(this.hasPlugin("decorators"))this.raise(this.state.start,"Stage 2 decorators disallow object literal property decorators");else for(;this.match(h.at);)s.push(this.parseDecorator());var o=this.startNode(),p=!1,c=!1,l=void 0,u=void 0;if(s.length&&(o.decorators=s,s=[]),this.match(h.ellipsis)){if(this.expectPlugin("objectRestSpread"),o=this.parseSpread(t?{start:0}:void 0),t&&this.toAssignable(o,!0,"object pattern"),a.properties.push(o),!t)continue;var d=this.state.start;if(null!==n)this.unexpected(n,"Cannot have multiple rest elements when destructuring");else{if(this.eat(h.braceR))break;if(!this.match(h.comma)||this.lookahead().type!==h.braceR){n=d;continue}this.unexpected(d,"A trailing comma is not permitted after the rest element")}}o.method=!1,(t||e)&&(l=this.state.start,u=this.state.startLoc),t||(p=this.eat(h.star));var f=this.state.containsEsc;if(!t&&this.isContextual("async")){p&&this.unexpected();var m=this.parseIdentifier();this.match(h.colon)||this.match(h.parenL)||this.match(h.braceR)||this.match(h.eq)||this.match(h.comma)?(o.key=m,o.computed=!1):(c=!0,this.match(h.star)&&(this.expectPlugin("asyncGenerators"),this.next(),p=!0),this.parsePropertyName(o))}else this.parsePropertyName(o);this.parseObjPropValue(o,l,u,p,c,t,e,f),this.checkPropClash(o,i),o.shorthand&&this.addExtra(o,"shorthand",!0),a.properties.push(o)}return null!==n&&this.unexpected(n,"The rest element has to be the last element when destructuring"),s.length&&this.raise(this.state.start,"You have trailing decorators with no property"),this.finishNode(a,t?"ObjectPattern":"ObjectExpression")},s.isGetterOrSetterMethod=function(t,e){return!e&&!t.computed&&"Identifier"===t.key.type&&("get"===t.key.name||"set"===t.key.name)&&(this.match(h.string)||this.match(h.num)||this.match(h.bracketL)||this.match(h.name)||!!this.state.type.keyword)},s.checkGetterSetterParams=function(t){var e="get"===t.kind?0:1,s=t.start;t.params.length!==e&&("get"===t.kind?this.raise(s,"getter must not have any formal parameters"):this.raise(s,"setter must have exactly one formal parameter")),"set"===t.kind&&"RestElement"===t.params[0].type&&this.raise(s,"setter function argument must not be a rest parameter")},s.parseObjectMethod=function(t,e,s,i,r){return s||e||this.match(h.parenL)?(i&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,e,s,!1,"ObjectMethod")):!r&&this.isGetterOrSetterMethod(t,i)?((e||s)&&this.unexpected(),t.kind=t.key.name,this.parsePropertyName(t),this.parseMethod(t,!1,!1,!1,"ObjectMethod"),this.checkGetterSetterParams(t),t):void 0},s.parseObjectProperty=function(t,e,s,i,r){return t.shorthand=!1,this.eat(h.colon)?(t.value=i?this.parseMaybeDefault(this.state.start,this.state.startLoc):this.parseMaybeAssign(!1,r),this.finishNode(t,"ObjectProperty")):t.computed||"Identifier"!==t.key.type?void 0:(this.checkReservedWord(t.key.name,t.key.start,!0,!0),i?t.value=this.parseMaybeDefault(e,s,t.key.__clone()):this.match(h.eq)&&r?(r.start||(r.start=this.state.start),t.value=this.parseMaybeDefault(e,s,t.key.__clone())):t.value=t.key.__clone(),t.shorthand=!0,this.finishNode(t,"ObjectProperty"))},s.parseObjPropValue=function(t,e,s,i,r,a,n,o){var h=this.parseObjectMethod(t,i,r,a,o)||this.parseObjectProperty(t,e,s,a,n);return h||this.unexpected(),h},s.parsePropertyName=function(t){if(this.eat(h.bracketL))t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(h.bracketR);else{var e=this.state.inPropertyName;this.state.inPropertyName=!0,t.key=this.match(h.num)||this.match(h.string)?this.parseExprAtom():this.parseMaybePrivateName(),"PrivateName"!==t.key.type&&(t.computed=!1),this.state.inPropertyName=e}return t.key},s.initFunction=function(t,e){t.id=null,t.generator=!1,t.async=!!e},s.parseMethod=function(t,e,s,i,r){var a=this.state.inFunction,n=this.state.inMethod,o=this.state.inGenerator;this.state.inFunction=!0,this.state.inMethod=t.kind||!0,this.state.inGenerator=e,this.initFunction(t,s),t.generator=!!e;var h=i;return this.parseFunctionParams(t,h),this.parseFunctionBodyAndFinish(t,r),this.state.inFunction=a,this.state.inMethod=n,this.state.inGenerator=o,t},s.parseArrowExpression=function(t,e,s){this.state.yieldInPossibleArrowParameters&&this.raise(this.state.yieldInPossibleArrowParameters.start,"yield is not allowed in the parameters of an arrow function inside a generator");var i=this.state.inFunction;this.state.inFunction=!0,this.initFunction(t,s),e&&this.setArrowFunctionParameters(t,e);var r=this.state.inGenerator,a=this.state.maybeInArrowParameters;return this.state.inGenerator=!1,this.state.maybeInArrowParameters=!1,this.parseFunctionBody(t,!0),this.state.inGenerator=r,this.state.inFunction=i,this.state.maybeInArrowParameters=a,this.finishNode(t,"ArrowFunctionExpression")},s.setArrowFunctionParameters=function(t,e){t.params=this.toAssignableList(e,!0,"arrow function parameters")},s.isStrictBody=function(t){if("BlockStatement"===t.body.type&&t.body.directives.length)for(var e=0,s=t.body.directives;e<s.length;e++){if("use strict"===s[e].value.value)return!0}return!1},s.parseFunctionBodyAndFinish=function(t,e,s){this.parseFunctionBody(t,s),this.finishNode(t,e)},s.parseFunctionBody=function(t,e){var s=e&&!this.match(h.braceL),i=this.state.inParameters,r=this.state.inAsync;if(this.state.inParameters=!1,this.state.inAsync=t.async,s)t.body=this.parseMaybeAssign();else{var a=this.state.inGenerator,n=this.state.inFunction,o=this.state.labels;this.state.inGenerator=t.generator,this.state.inFunction=!0,this.state.labels=[],t.body=this.parseBlock(!0),this.state.inFunction=n,this.state.inGenerator=a,this.state.labels=o}this.state.inAsync=r,this.checkFunctionNameAndParams(t,e),this.state.inParameters=i},s.checkFunctionNameAndParams=function(t,e){var s=this.isStrictBody(t),i=this.state.strict||s||e,r=this.state.strict;if(s&&(this.state.strict=s),i){var a=Object.create(null);t.id&&this.checkLVal(t.id,!0,void 0,"function name");for(var n=0,o=t.params;n<o.length;n++){var h=o[n];s&&"Identifier"!==h.type&&this.raise(h.start,"Non-simple parameter in strict mode"),this.checkLVal(h,!0,a,"function parameter list")}}this.state.strict=r},s.parseExprList=function(t,e,s){for(var i=[],r=!0;!this.eat(t);){if(r)r=!1;else if(this.expect(h.comma),this.eat(t))break;i.push(this.parseExprListItem(e,s))}return i},s.parseExprListItem=function(t,e,s,i){var r;if(t&&this.match(h.comma))r=null;else if(this.match(h.ellipsis)){var a=this.state.start,n=this.state.startLoc;r=this.parseParenItem(this.parseSpread(e,s),a,n),i&&this.match(h.comma)&&(i.start=this.state.start)}else r=this.parseMaybeAssign(!1,e,this.parseParenItem,s);return r},s.parseIdentifier=function(t){var e=this.startNode(),s=this.parseIdentifierName(e.start,t);return e.name=s,e.loc.identifierName=s,this.finishNode(e,"Identifier")},s.parseIdentifierName=function(t,e){var s;if(e||this.checkReservedWord(this.state.value,this.state.start,!!this.state.type.keyword,!1),this.match(h.name))s=this.state.value;else{if(!this.state.type.keyword)throw this.unexpected();s=this.state.type.keyword}return!e&&"await"===s&&this.state.inAsync&&this.raise(t,"invalid use of await inside of an async function"),this.next(),s},s.checkReservedWord=function(t,e,s,i){this.state.strict&&(u.strict(t)||i&&u.strictBind(t))&&this.raise(e,t+" is a reserved word in strict mode"),this.state.inGenerator&&"yield"===t&&this.raise(e,"yield is a reserved word inside generator functions"),this.state.inClassProperty&&"arguments"===t&&this.raise(e,"'arguments' is not allowed in class field initializer"),(this.isReservedWord(t)||s&&this.isKeyword(t))&&this.raise(e,t+" is a reserved word")},s.parseAwait=function(t){return this.state.inAsync||!this.state.inFunction&&this.options.allowAwaitOutsideFunction||this.unexpected(),this.match(h.star)&&this.raise(t.start,"await* has been removed from the async functions proposal. Use Promise.all() instead."),t.argument=this.parseMaybeUnary(),this.finishNode(t,"AwaitExpression")},s.parseYield=function(){var t=this.startNode();return this.state.inParameters&&this.raise(t.start,"yield is not allowed in generator parameters"),this.state.maybeInArrowParameters&&!this.state.yieldInPossibleArrowParameters&&(this.state.yieldInPossibleArrowParameters=t),this.next(),this.match(h.semi)||this.canInsertSemicolon()||!this.match(h.star)&&!this.state.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(h.star),t.argument=this.parseMaybeAssign()),this.finishNode(t,"YieldExpression")},e}(function(t){function e(){return t.apply(this,arguments)||this}i(e,t);var s=e.prototype;return s.toAssignable=function(t,e,s){if(t)switch(t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":t.type="ObjectPattern";for(var i=0;i<t.properties.length;i++){var r=t.properties[i],a=i===t.properties.length-1;this.toAssignableObjectExpressionProp(r,e,a)}break;case"ObjectProperty":this.toAssignable(t.value,e,s);break;case"SpreadElement":this.checkToRestConversion(t),t.type="RestElement";var n=t.argument;this.toAssignable(n,e,s);break;case"ArrayExpression":t.type="ArrayPattern",this.toAssignableList(t.elements,e,s);break;case"AssignmentExpression":"="===t.operator?(t.type="AssignmentPattern",delete t.operator):this.raise(t.left.end,"Only '=' operator can be used for specifying default value.");break;case"MemberExpression":if(!e)break;default:var o="Invalid left-hand side"+(s?" in "+s:"expression");this.raise(t.start,o)}return t},s.toAssignableObjectExpressionProp=function(t,e,s){if("ObjectMethod"===t.type){var i="get"===t.kind||"set"===t.kind?"Object pattern can't contain getter or setter":"Object pattern can't contain methods";this.raise(t.key.start,i)}else"SpreadElement"!==t.type||s?this.toAssignable(t,e,"object destructuring pattern"):this.raise(t.start,"The rest element has to be the last element when destructuring")},s.toAssignableList=function(t,e,s){var i=t.length;if(i){var r=t[i-1];if(r&&"RestElement"===r.type)--i;else if(r&&"SpreadElement"===r.type){r.type="RestElement";var a=r.argument;this.toAssignable(a,e,s),-1===["Identifier","MemberExpression","ArrayPattern","ObjectPattern"].indexOf(a.type)&&this.unexpected(a.start),--i}}for(var n=0;n<i;n++){var o=t[n];o&&"SpreadElement"===o.type&&this.raise(o.start,"The rest element has to be the last element when destructuring"),o&&this.toAssignable(o,e,s)}return t},s.toReferencedList=function(t){return t},s.parseSpread=function(t,e){var s=this.startNode();return this.next(),s.argument=this.parseMaybeAssign(!1,t,void 0,e),this.finishNode(s,"SpreadElement")},s.parseRest=function(){var t=this.startNode();return this.next(),t.argument=this.parseBindingAtom(),this.finishNode(t,"RestElement")},s.shouldAllowYieldIdentifier=function(){return this.match(h._yield)&&!this.state.strict&&!this.state.inGenerator},s.parseBindingIdentifier=function(){return this.parseIdentifier(this.shouldAllowYieldIdentifier())},s.parseBindingAtom=function(){switch(this.state.type){case h._yield:case h.name:return this.parseBindingIdentifier();case h.bracketL:var t=this.startNode();return this.next(),t.elements=this.parseBindingList(h.bracketR,!0),this.finishNode(t,"ArrayPattern");case h.braceL:return this.parseObj(!0);default:throw this.unexpected()}},s.parseBindingList=function(t,e,s){for(var i=[],r=!0;!this.eat(t);)if(r?r=!1:this.expect(h.comma),e&&this.match(h.comma))i.push(null);else{if(this.eat(t))break;if(this.match(h.ellipsis)){i.push(this.parseAssignableListItemTypes(this.parseRest())),this.expect(t);break}var a=[];for(this.match(h.at)&&this.hasPlugin("decorators")&&this.raise(this.state.start,"Stage 2 decorators cannot be used to decorate parameters");this.match(h.at);)a.push(this.parseDecorator());i.push(this.parseAssignableListItem(s,a))}return i},s.parseAssignableListItem=function(t,e){var s=this.parseMaybeDefault();this.parseAssignableListItemTypes(s);var i=this.parseMaybeDefault(s.start,s.loc.start,s);return e.length&&(s.decorators=e),i},s.parseAssignableListItemTypes=function(t){return t},s.parseMaybeDefault=function(t,e,s){if(e=e||this.state.startLoc,t=t||this.state.start,s=s||this.parseBindingAtom(),!this.eat(h.eq))return s;var i=this.startNodeAt(t,e);return i.left=s,i.right=this.parseMaybeAssign(),this.finishNode(i,"AssignmentPattern")},s.checkLVal=function(t,e,s,i){switch(t.type){case"Identifier":if(this.checkReservedWord(t.name,t.start,!1,!0),s){var r="_"+t.name;s[r]?this.raise(t.start,"Argument name clash in strict mode"):s[r]=!0}break;case"MemberExpression":e&&this.raise(t.start,"Binding member expression");break;case"ObjectPattern":for(var a=0,n=t.properties;a<n.length;a++){var o=n[a];"ObjectProperty"===o.type&&(o=o.value),this.checkLVal(o,e,s,"object destructuring pattern")}break;case"ArrayPattern":for(var h=0,p=t.elements;h<p.length;h++){var c=p[h];c&&this.checkLVal(c,e,s,"array destructuring pattern")}break;case"AssignmentPattern":this.checkLVal(t.left,e,s,"assignment pattern");break;case"RestElement":this.checkLVal(t.argument,e,s,"rest element");break;default:var l=(e?"Binding invalid":"Invalid")+" left-hand side"+(i?" in "+i:"expression");this.raise(t.start,l)}},s.checkToRestConversion=function(t){-1===["Identifier","MemberExpression"].indexOf(t.argument.type)&&this.raise(t.argument.start,"Invalid rest operator's argument")},e}(function(t){function e(){return t.apply(this,arguments)||this}i(e,t);var s=e.prototype;return s.startNode=function(){return new Y(this,this.state.start,this.state.startLoc)},s.startNodeAt=function(t,e){return new Y(this,t,e)},s.startNodeAtNode=function(t){return this.startNodeAt(t.start,t.loc.start)},s.finishNode=function(t,e){return this.finishNodeAt(t,e,this.state.lastTokEnd,this.state.lastTokEndLoc)},s.finishNodeAt=function(t,e,s,i){return t.type=e,t.end=s,t.loc.end=i,this.options.ranges&&(t.range[1]=s),this.processComment(t),t},s.resetStartLocationFromNode=function(t,e){t.start=e.start,t.loc.start=e.loc.start,this.options.ranges&&(t.range[0]=e.range[0])},e}(z)))));function st(t){if(null==t)throw new Error("Unexpected "+t+" value.");return t}function it(t){if(!t)throw new Error("Assert fail")}function rt(t,e){return t.some(function(t){return Array.isArray(t)?t[0]===e:t===e})}var at=["estree","jsx","flow","typescript"],nt={estree:function(t){return function(t){function e(){return t.apply(this,arguments)||this}i(e,t);var s=e.prototype;return s.estreeParseRegExpLiteral=function(t){var e=t.pattern,s=t.flags,i=null;try{i=new RegExp(e,s)}catch(t){}var r=this.estreeParseLiteral(i);return r.regex={pattern:e,flags:s},r},s.estreeParseLiteral=function(t){return this.parseLiteral(t,"Literal")},s.directiveToStmt=function(t){var e=t.value,s=this.startNodeAt(t.start,t.loc.start),i=this.startNodeAt(e.start,e.loc.start);return i.value=e.value,i.raw=e.extra.raw,s.expression=this.finishNodeAt(i,"Literal",e.end,e.loc.end),s.directive=e.extra.raw.slice(1,-1),this.finishNodeAt(s,"ExpressionStatement",t.end,t.loc.end)},s.initFunction=function(e,s){t.prototype.initFunction.call(this,e,s),e.expression=!1},s.checkDeclaration=function(e){c(e)?this.checkDeclaration(e.value):t.prototype.checkDeclaration.call(this,e)},s.checkGetterSetterParams=function(t){var e=t,s="get"===e.kind?0:1,i=e.start;e.value.params.length!==s&&("get"===e.kind?this.raise(i,"getter must not have any formal parameters"):this.raise(i,"setter must have exactly one formal parameter")),"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raise(i,"setter function argument must not be a rest parameter")},s.checkLVal=function(e,s,i,r){var a=this;switch(e.type){case"ObjectPattern":e.properties.forEach(function(t){a.checkLVal("Property"===t.type?t.value:t,s,i,"object destructuring pattern")});break;default:t.prototype.checkLVal.call(this,e,s,i,r)}},s.checkPropClash=function(t,e){if(!t.computed&&c(t)){var s=t.key;"__proto__"===("Identifier"===s.type?s.name:String(s.value))&&(e.proto&&this.raise(s.start,"Redefinition of __proto__ property"),e.proto=!0)}},s.isStrictBody=function(t){if("BlockStatement"===t.body.type&&t.body.body.length>0)for(var e=0,s=t.body.body;e<s.length;e++){var i=s[e];if("ExpressionStatement"!==i.type||"Literal"!==i.expression.type)break;if("use strict"===i.expression.value)return!0}return!1},s.isValidDirective=function(t){return!("ExpressionStatement"!==t.type||"Literal"!==t.expression.type||"string"!=typeof t.expression.value||t.expression.extra&&t.expression.extra.parenthesized)},s.stmtToDirective=function(e){var s=t.prototype.stmtToDirective.call(this,e),i=e.expression.value;return s.value.value=i,s},s.parseBlockBody=function(e,s,i,r){var a=this;t.prototype.parseBlockBody.call(this,e,s,i,r);var n=e.directives.map(function(t){return a.directiveToStmt(t)});e.body=n.concat(e.body),delete e.directives},s.pushClassMethod=function(t,e,s,i,r){this.parseMethod(e,s,i,r,"MethodDefinition"),e.typeParameters&&(e.value.typeParameters=e.typeParameters,delete e.typeParameters),t.body.push(e)},s.parseExprAtom=function(e){switch(this.state.type){case h.regexp:return this.estreeParseRegExpLiteral(this.state.value);case h.num:case h.string:return this.estreeParseLiteral(this.state.value);case h._null:return this.estreeParseLiteral(null);case h._true:return this.estreeParseLiteral(!0);case h._false:return this.estreeParseLiteral(!1);default:return t.prototype.parseExprAtom.call(this,e)}},s.parseLiteral=function(e,s,i,r){var a=t.prototype.parseLiteral.call(this,e,s,i,r);return a.raw=a.extra.raw,delete a.extra,a},s.parseFunctionBody=function(e,s){t.prototype.parseFunctionBody.call(this,e,s),e.expression="BlockStatement"!==e.body.type},s.parseMethod=function(e,s,i,r,a){var n=this.startNode();return n.kind=e.kind,delete(n=t.prototype.parseMethod.call(this,n,s,i,r,"FunctionExpression")).kind,e.value=n,this.finishNode(e,a)},s.parseObjectMethod=function(e,s,i,r,a){var n=t.prototype.parseObjectMethod.call(this,e,s,i,r,a);return n&&(n.type="Property","method"===n.kind&&(n.kind="init"),n.shorthand=!1),n},s.parseObjectProperty=function(e,s,i,r,a){var n=t.prototype.parseObjectProperty.call(this,e,s,i,r,a);return n&&(n.kind="init",n.type="Property"),n},s.toAssignable=function(e,s,i){return c(e)?(this.toAssignable(e.value,s,i),e):t.prototype.toAssignable.call(this,e,s,i)},s.toAssignableObjectExpressionProp=function(e,s,i){"get"===e.kind||"set"===e.kind?this.raise(e.key.start,"Object pattern can't contain getter or setter"):e.method?this.raise(e.key.start,"Object pattern can't contain methods"):t.prototype.toAssignableObjectExpressionProp.call(this,e,s,i)},e}(t)},jsx:function(t){return function(t){function e(){return t.apply(this,arguments)||this}i(e,t);var s=e.prototype;return s.jsxReadToken=function(){for(var t="",e=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated JSX contents");var s=this.input.charCodeAt(this.state.pos);switch(s){case 60:case 123:return this.state.pos===this.state.start?60===s&&this.state.exprAllowed?(++this.state.pos,this.finishToken(h.jsxTagStart)):this.getTokenFromCode(s):(t+=this.input.slice(e,this.state.pos),this.finishToken(h.jsxText,t));case 38:t+=this.input.slice(e,this.state.pos),t+=this.jsxReadEntity(),e=this.state.pos;break;default:L(s)?(t+=this.input.slice(e,this.state.pos),t+=this.jsxReadNewLine(!0),e=this.state.pos):++this.state.pos}}},s.jsxReadNewLine=function(t){var e,s=this.input.charCodeAt(this.state.pos);return++this.state.pos,13===s&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,e=t?"\n":"\r\n"):e=String.fromCharCode(s),++this.state.curLine,this.state.lineStart=this.state.pos,e},s.jsxReadString=function(t){for(var e="",s=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var i=this.input.charCodeAt(this.state.pos);if(i===t)break;38===i?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadEntity(),s=this.state.pos):L(i)?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadNewLine(!1),s=this.state.pos):++this.state.pos}return e+=this.input.slice(s,this.state.pos++),this.finishToken(h.string,e)},s.jsxReadEntity=function(){for(var t,e="",s=0,i=this.input[this.state.pos],r=++this.state.pos;this.state.pos<this.input.length&&s++<10;){if(";"===(i=this.input[this.state.pos++])){"#"===e[0]?"x"===e[1]?(e=e.substr(2),_.test(e)&&(t=String.fromCodePoint(parseInt(e,16)))):(e=e.substr(1),R.test(e)&&(t=String.fromCodePoint(parseInt(e,10)))):t=k[e];break}e+=i}return t||(this.state.pos=r,"&")},s.jsxReadWord=function(){var t,e=this.state.pos;do{t=this.input.charCodeAt(++this.state.pos)}while(T(t)||45===t);return this.finishToken(h.jsxName,this.input.slice(e,this.state.pos))},s.jsxParseIdentifier=function(){var t=this.startNode();return this.match(h.jsxName)?t.name=this.state.value:this.state.type.keyword?t.name=this.state.type.keyword:this.unexpected(),this.next(),this.finishNode(t,"JSXIdentifier")},s.jsxParseNamespacedName=function(){var t=this.state.start,e=this.state.startLoc,s=this.jsxParseIdentifier();if(!this.eat(h.colon))return s;var i=this.startNodeAt(t,e);return i.namespace=s,i.name=this.jsxParseIdentifier(),this.finishNode(i,"JSXNamespacedName")},s.jsxParseElementName=function(){for(var t=this.state.start,e=this.state.startLoc,s=this.jsxParseNamespacedName();this.eat(h.dot);){var i=this.startNodeAt(t,e);i.object=s,i.property=this.jsxParseIdentifier(),s=this.finishNode(i,"JSXMemberExpression")}return s},s.jsxParseAttributeValue=function(){var t;switch(this.state.type){case h.braceL:if("JSXEmptyExpression"===(t=this.jsxParseExpressionContainer()).expression.type)throw this.raise(t.start,"JSX attributes must only be assigned a non-empty expression");return t;case h.jsxTagStart:case h.string:return this.parseExprAtom();default:throw this.raise(this.state.start,"JSX value should be either an expression or a quoted JSX text")}},s.jsxParseEmptyExpression=function(){var t=this.startNodeAt(this.state.lastTokEnd,this.state.lastTokEndLoc);return this.finishNodeAt(t,"JSXEmptyExpression",this.state.start,this.state.startLoc)},s.jsxParseSpreadChild=function(){var t=this.startNode();return this.expect(h.braceL),this.expect(h.ellipsis),t.expression=this.parseExpression(),this.expect(h.braceR),this.finishNode(t,"JSXSpreadChild")},s.jsxParseExpressionContainer=function(){var t=this.startNode();return this.next(),this.match(h.braceR)?t.expression=this.jsxParseEmptyExpression():t.expression=this.parseExpression(),this.expect(h.braceR),this.finishNode(t,"JSXExpressionContainer")},s.jsxParseAttribute=function(){var t=this.startNode();return this.eat(h.braceL)?(this.expect(h.ellipsis),t.argument=this.parseMaybeAssign(),this.expect(h.braceR),this.finishNode(t,"JSXSpreadAttribute")):(t.name=this.jsxParseNamespacedName(),t.value=this.eat(h.eq)?this.jsxParseAttributeValue():null,this.finishNode(t,"JSXAttribute"))},s.jsxParseOpeningElementAt=function(t,e){var s=this.startNodeAt(t,e);if(this.match(h.jsxTagEnd))return this.expect(h.jsxTagEnd),this.finishNode(s,"JSXOpeningFragment");for(s.attributes=[],s.name=this.jsxParseElementName();!this.match(h.slash)&&!this.match(h.jsxTagEnd);)s.attributes.push(this.jsxParseAttribute());return s.selfClosing=this.eat(h.slash),this.expect(h.jsxTagEnd),this.finishNode(s,"JSXOpeningElement")},s.jsxParseClosingElementAt=function(t,e){var s=this.startNodeAt(t,e);return this.match(h.jsxTagEnd)?(this.expect(h.jsxTagEnd),this.finishNode(s,"JSXClosingFragment")):(s.name=this.jsxParseElementName(),this.expect(h.jsxTagEnd),this.finishNode(s,"JSXClosingElement"))},s.jsxParseElementAt=function(t,e){var s=this.startNodeAt(t,e),i=[],r=this.jsxParseOpeningElementAt(t,e),a=null;if(!r.selfClosing){t:for(;;)switch(this.state.type){case h.jsxTagStart:if(t=this.state.start,e=this.state.startLoc,this.next(),this.eat(h.slash)){a=this.jsxParseClosingElementAt(t,e);break t}i.push(this.jsxParseElementAt(t,e));break;case h.jsxText:i.push(this.parseExprAtom());break;case h.braceL:this.lookahead().type===h.ellipsis?i.push(this.jsxParseSpreadChild()):i.push(this.jsxParseExpressionContainer());break;default:throw this.unexpected()}j(r)&&!j(a)?this.raise(a.start,"Expected corresponding JSX closing tag for <>"):!j(r)&&j(a)?this.raise(a.start,"Expected corresponding JSX closing tag for <"+F(r.name)+">"):j(r)||j(a)||F(a.name)!==F(r.name)&&this.raise(a.start,"Expected corresponding JSX closing tag for <"+F(r.name)+">")}return j(r)?(s.openingFragment=r,s.closingFragment=a):(s.openingElement=r,s.closingElement=a),s.children=i,this.match(h.relational)&&"<"===this.state.value&&this.raise(this.state.start,"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"),j(r)?this.finishNode(s,"JSXFragment"):this.finishNode(s,"JSXElement")},s.jsxParseElement=function(){var t=this.state.start,e=this.state.startLoc;return this.next(),this.jsxParseElementAt(t,e)},s.parseExprAtom=function(e){return this.match(h.jsxText)?this.parseLiteral(this.state.value,"JSXText"):this.match(h.jsxTagStart)?this.jsxParseElement():t.prototype.parseExprAtom.call(this,e)},s.readToken=function(e){if(this.state.inPropertyName)return t.prototype.readToken.call(this,e);var s=this.curContext();if(s===D.j_expr)return this.jsxReadToken();if(s===D.j_oTag||s===D.j_cTag){if(b(e))return this.jsxReadWord();if(62===e)return++this.state.pos,this.finishToken(h.jsxTagEnd);if((34===e||39===e)&&s===D.j_oTag)return this.jsxReadString(e)}return 60===e&&this.state.exprAllowed?(++this.state.pos,this.finishToken(h.jsxTagStart)):t.prototype.readToken.call(this,e)},s.updateContext=function(e){if(this.match(h.braceL)){var s=this.curContext();s===D.j_oTag?this.state.context.push(D.braceExpression):s===D.j_expr?this.state.context.push(D.templateQuasi):t.prototype.updateContext.call(this,e),this.state.exprAllowed=!0}else{if(!this.match(h.slash)||e!==h.jsxTagStart)return t.prototype.updateContext.call(this,e);this.state.context.length-=2,this.state.context.push(D.j_cTag),this.state.exprAllowed=!1}},e}(t)},flow:function(t){return function(t){function e(e,s){var i;return(i=t.call(this,e,s)||this).flowPragma=void 0,i}i(e,t);var s=e.prototype;return s.shouldParseTypes=function(){return this.getPluginOption("flow","all")||"flow"===this.flowPragma},s.addComment=function(e){if(void 0===this.flowPragma){var s=N.exec(e.value);if(s)if("flow"===s[1])this.flowPragma="flow";else{if("noflow"!==s[1])throw new Error("Unexpected flow pragma");this.flowPragma="noflow"}else this.flowPragma=null}return t.prototype.addComment.call(this,e)},s.flowParseTypeInitialiser=function(t){var e=this.state.inType;this.state.inType=!0,this.expect(t||h.colon);var s=this.flowParseType();return this.state.inType=e,s},s.flowParsePredicate=function(){var t=this.startNode(),e=this.state.startLoc,s=this.state.start;this.expect(h.modulo);var i=this.state.startLoc;return this.expectContextual("checks"),e.line===i.line&&e.column===i.column-1||this.raise(s,"Spaces between ´%´ and ´checks´ are not allowed here."),this.eat(h.parenL)?(t.value=this.parseExpression(),this.expect(h.parenR),this.finishNode(t,"DeclaredPredicate")):this.finishNode(t,"InferredPredicate")},s.flowParseTypeAndPredicateInitialiser=function(){var t=this.state.inType;this.state.inType=!0,this.expect(h.colon);var e=null,s=null;return this.match(h.modulo)?(this.state.inType=t,s=this.flowParsePredicate()):(e=this.flowParseType(),this.state.inType=t,this.match(h.modulo)&&(s=this.flowParsePredicate())),[e,s]},s.flowParseDeclareClass=function(t){return this.next(),this.flowParseInterfaceish(t,!0),this.finishNode(t,"DeclareClass")},s.flowParseDeclareFunction=function(t){this.next();var e=t.id=this.parseIdentifier(),s=this.startNode(),i=this.startNode();this.isRelational("<")?s.typeParameters=this.flowParseTypeParameterDeclaration():s.typeParameters=null,this.expect(h.parenL);var r=this.flowParseFunctionTypeParams();s.params=r.params,s.rest=r.rest,this.expect(h.parenR);var a=this.flowParseTypeAndPredicateInitialiser();return s.returnType=a[0],t.predicate=a[1],i.typeAnnotation=this.finishNode(s,"FunctionTypeAnnotation"),e.typeAnnotation=this.finishNode(i,"TypeAnnotation"),this.finishNode(e,e.type),this.semicolon(),this.finishNode(t,"DeclareFunction")},s.flowParseDeclare=function(t,e){if(this.match(h._class))return this.flowParseDeclareClass(t);if(this.match(h._function))return this.flowParseDeclareFunction(t);if(this.match(h._var))return this.flowParseDeclareVariable(t);if(this.isContextual("module"))return this.lookahead().type===h.dot?this.flowParseDeclareModuleExports(t):(e&&this.unexpected(null,"`declare module` cannot be used inside another `declare module`"),this.flowParseDeclareModule(t));if(this.isContextual("type"))return this.flowParseDeclareTypeAlias(t);if(this.isContextual("opaque"))return this.flowParseDeclareOpaqueType(t);if(this.isContextual("interface"))return this.flowParseDeclareInterface(t);if(this.match(h._export))return this.flowParseDeclareExportDeclaration(t,e);throw this.unexpected()},s.flowParseDeclareVariable=function(t){return this.next(),t.id=this.flowParseTypeAnnotatableIdentifier(!0),this.semicolon(),this.finishNode(t,"DeclareVariable")},s.flowParseDeclareModule=function(t){var e=this;this.next(),this.match(h.string)?t.id=this.parseExprAtom():t.id=this.parseIdentifier();var s=t.body=this.startNode(),i=s.body=[];for(this.expect(h.braceL);!this.match(h.braceR);){var r=this.startNode();if(this.match(h._import)){var a=this.lookahead();"type"!==a.value&&"typeof"!==a.value&&this.unexpected(null,"Imports within a `declare module` body must always be `import type` or `import typeof`"),this.next(),this.parseImport(r)}else this.expectContextual("declare","Only declares and type imports are allowed inside declare module"),r=this.flowParseDeclare(r,!0);i.push(r)}this.expect(h.braceR),this.finishNode(s,"BlockStatement");var n=null,o=!1,p="Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module";return i.forEach(function(t){!function(t){return"DeclareExportAllDeclaration"===t.type||"DeclareExportDeclaration"===t.type&&(!t.declaration||"TypeAlias"!==t.declaration.type&&"InterfaceDeclaration"!==t.declaration.type)}(t)?"DeclareModuleExports"===t.type&&(o&&e.unexpected(t.start,"Duplicate `declare module.exports` statement"),"ES"===n&&e.unexpected(t.start,p),n="CommonJS",o=!0):("CommonJS"===n&&e.unexpected(t.start,p),n="ES")}),t.kind=n||"CommonJS",this.finishNode(t,"DeclareModule")},s.flowParseDeclareExportDeclaration=function(t,e){if(this.expect(h._export),this.eat(h._default))return this.match(h._function)||this.match(h._class)?t.declaration=this.flowParseDeclare(this.startNode()):(t.declaration=this.flowParseType(),this.semicolon()),t.default=!0,this.finishNode(t,"DeclareExportDeclaration");if(this.match(h._const)||this.match(h._let)||(this.isContextual("type")||this.isContextual("interface"))&&!e){var s=this.state.value,i=C[s];this.unexpected(this.state.start,"`declare export "+s+"` is not supported. Use `"+i+"` instead")}if(this.match(h._var)||this.match(h._function)||this.match(h._class)||this.isContextual("opaque"))return t.declaration=this.flowParseDeclare(this.startNode()),t.default=!1,this.finishNode(t,"DeclareExportDeclaration");if(this.match(h.star)||this.match(h.braceL)||this.isContextual("interface")||this.isContextual("type")||this.isContextual("opaque"))return"ExportNamedDeclaration"===(t=this.parseExport(t)).type&&(t.type="ExportDeclaration",t.default=!1,delete t.exportKind),t.type="Declare"+t.type,t;throw this.unexpected()},s.flowParseDeclareModuleExports=function(t){return this.expectContextual("module"),this.expect(h.dot),this.expectContextual("exports"),t.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(t,"DeclareModuleExports")},s.flowParseDeclareTypeAlias=function(t){return this.next(),this.flowParseTypeAlias(t),this.finishNode(t,"DeclareTypeAlias")},s.flowParseDeclareOpaqueType=function(t){return this.next(),this.flowParseOpaqueType(t,!0),this.finishNode(t,"DeclareOpaqueType")},s.flowParseDeclareInterface=function(t){return this.next(),this.flowParseInterfaceish(t),this.finishNode(t,"DeclareInterface")},s.flowParseInterfaceish=function(t,e){if(t.id=this.flowParseRestrictedIdentifier(!e),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.extends=[],t.implements=[],t.mixins=[],this.eat(h._extends))do{t.extends.push(this.flowParseInterfaceExtends())}while(!e&&this.eat(h.comma));if(this.isContextual("mixins")){this.next();do{t.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(h.comma))}if(this.isContextual("implements")){this.next();do{t.implements.push(this.flowParseInterfaceExtends())}while(this.eat(h.comma))}t.body=this.flowParseObjectType(!0,!1,!1)},s.flowParseInterfaceExtends=function(){var t=this.startNode();return t.id=this.flowParseQualifiedTypeIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterInstantiation():t.typeParameters=null,this.finishNode(t,"InterfaceExtends")},s.flowParseInterface=function(t){return this.flowParseInterfaceish(t),this.finishNode(t,"InterfaceDeclaration")},s.checkReservedType=function(t,e){w.indexOf(t)>-1&&this.raise(e,"Cannot overwrite primitive type "+t)},s.flowParseRestrictedIdentifier=function(t){return this.checkReservedType(this.state.value,this.state.start),this.parseIdentifier(t)},s.flowParseTypeAlias=function(t){return t.id=this.flowParseRestrictedIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.right=this.flowParseTypeInitialiser(h.eq),this.semicolon(),this.finishNode(t,"TypeAlias")},s.flowParseOpaqueType=function(t,e){return this.expectContextual("type"),t.id=this.flowParseRestrictedIdentifier(!0),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.supertype=null,this.match(h.colon)&&(t.supertype=this.flowParseTypeInitialiser(h.colon)),t.impltype=null,e||(t.impltype=this.flowParseTypeInitialiser(h.eq)),this.semicolon(),this.finishNode(t,"OpaqueType")},s.flowParseTypeParameter=function(t,e){if(void 0===t&&(t=!0),void 0===e&&(e=!1),!t&&e)throw new Error("Cannot disallow a default value (`allowDefault`) while also requiring it (`requireDefault`).");var s=this.state.start,i=this.startNode(),r=this.flowParseVariance(),a=this.flowParseTypeAnnotatableIdentifier();return i.name=a.name,i.variance=r,i.bound=a.typeAnnotation,this.match(h.eq)?t?(this.eat(h.eq),i.default=this.flowParseType()):this.unexpected():e&&this.unexpected(s,"Type parameter declaration needs a default, since a preceding type parameter declaration has a default."),this.finishNode(i,"TypeParameter")},s.flowParseTypeParameterDeclaration=function(t){void 0===t&&(t=!0);var e=this.state.inType,s=this.startNode();s.params=[],this.state.inType=!0,this.isRelational("<")||this.match(h.jsxTagStart)?this.next():this.unexpected();var i=!1;do{var r=this.flowParseTypeParameter(t,i);s.params.push(r),r.default&&(i=!0),this.isRelational(">")||this.expect(h.comma)}while(!this.isRelational(">"));return this.expectRelational(">"),this.state.inType=e,this.finishNode(s,"TypeParameterDeclaration")},s.flowParseTypeParameterInstantiation=function(){var t=this.startNode(),e=this.state.inType;for(t.params=[],this.state.inType=!0,this.expectRelational("<");!this.isRelational(">");)t.params.push(this.flowParseType()),this.isRelational(">")||this.expect(h.comma);return this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterInstantiation")},s.flowParseInterfaceType=function(){var t=this.startNode();if(this.expectContextual("interface"),t.extends=[],this.eat(h._extends))do{t.extends.push(this.flowParseInterfaceExtends())}while(this.eat(h.comma));return t.body=this.flowParseObjectType(!0,!1,!1),this.finishNode(t,"InterfaceTypeAnnotation")},s.flowParseObjectPropertyKey=function(){return this.match(h.num)||this.match(h.string)?this.parseExprAtom():this.parseIdentifier(!0)},s.flowParseObjectTypeIndexer=function(t,e,s){return t.static=e,this.lookahead().type===h.colon?(t.id=this.flowParseObjectPropertyKey(),t.key=this.flowParseTypeInitialiser()):(t.id=null,t.key=this.flowParseType()),this.expect(h.bracketR),t.value=this.flowParseTypeInitialiser(),t.variance=s,this.finishNode(t,"ObjectTypeIndexer")},s.flowParseObjectTypeInternalSlot=function(t,e){return t.static=e,t.id=this.flowParseObjectPropertyKey(),this.expect(h.bracketR),this.expect(h.bracketR),this.isRelational("<")||this.match(h.parenL)?(t.method=!0,t.optional=!1,t.value=this.flowParseObjectTypeMethodish(this.startNodeAt(t.start,t.loc.start))):(t.method=!1,this.eat(h.question)&&(t.optional=!0),t.value=this.flowParseTypeInitialiser()),this.finishNode(t,"ObjectTypeInternalSlot")},s.flowParseObjectTypeMethodish=function(t){for(t.params=[],t.rest=null,t.typeParameters=null,this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration(!1)),this.expect(h.parenL);!this.match(h.parenR)&&!this.match(h.ellipsis);)t.params.push(this.flowParseFunctionTypeParam()),this.match(h.parenR)||this.expect(h.comma);return this.eat(h.ellipsis)&&(t.rest=this.flowParseFunctionTypeParam()),this.expect(h.parenR),t.returnType=this.flowParseTypeInitialiser(),this.finishNode(t,"FunctionTypeAnnotation")},s.flowParseObjectTypeCallProperty=function(t,e){var s=this.startNode();return t.static=e,t.value=this.flowParseObjectTypeMethodish(s),this.finishNode(t,"ObjectTypeCallProperty")},s.flowParseObjectType=function(t,e,s){var i=this.state.inType;this.state.inType=!0;var r,a,n=this.startNode();for(n.callProperties=[],n.properties=[],n.indexers=[],n.internalSlots=[],e&&this.match(h.braceBarL)?(this.expect(h.braceBarL),r=h.braceBarR,a=!0):(this.expect(h.braceL),r=h.braceR,a=!1),n.exact=a;!this.match(r);){var o=!1,p=this.startNode();if(t&&this.isContextual("static")){var c=this.lookahead();c.type!==h.colon&&c.type!==h.question&&(this.next(),o=!0)}var l=this.flowParseVariance();if(this.eat(h.bracketL))this.eat(h.bracketL)?(l&&this.unexpected(l.start),n.internalSlots.push(this.flowParseObjectTypeInternalSlot(p,o))):n.indexers.push(this.flowParseObjectTypeIndexer(p,o,l));else if(this.match(h.parenL)||this.isRelational("<"))l&&this.unexpected(l.start),n.callProperties.push(this.flowParseObjectTypeCallProperty(p,o));else{var u="init";if(this.isContextual("get")||this.isContextual("set")){var d=this.lookahead();d.type!==h.name&&d.type!==h.string&&d.type!==h.num||(u=this.state.value,this.next())}n.properties.push(this.flowParseObjectTypeProperty(p,o,l,u,s))}this.flowObjectTypeSemicolon()}this.expect(r);var f=this.finishNode(n,"ObjectTypeAnnotation");return this.state.inType=i,f},s.flowParseObjectTypeProperty=function(t,e,s,i,r){if(this.match(h.ellipsis))return r||this.unexpected(null,"Spread operator cannot appear in class or interface definitions"),s&&this.unexpected(s.start,"Spread properties cannot have variance"),this.expect(h.ellipsis),t.argument=this.flowParseType(),this.finishNode(t,"ObjectTypeSpreadProperty");t.key=this.flowParseObjectPropertyKey(),t.static=e,t.kind=i;var a=!1;return this.isRelational("<")||this.match(h.parenL)?(t.method=!0,s&&this.unexpected(s.start),t.value=this.flowParseObjectTypeMethodish(this.startNodeAt(t.start,t.loc.start)),"get"!==i&&"set"!==i||this.flowCheckGetterSetterParams(t)):("init"!==i&&this.unexpected(),t.method=!1,this.eat(h.question)&&(a=!0),t.value=this.flowParseTypeInitialiser(),t.variance=s),t.optional=a,this.finishNode(t,"ObjectTypeProperty")},s.flowCheckGetterSetterParams=function(t){var e="get"===t.kind?0:1,s=t.start;t.value.params.length+(t.value.rest?1:0)!==e&&("get"===t.kind?this.raise(s,"getter must not have any formal parameters"):this.raise(s,"setter must have exactly one formal parameter")),"set"===t.kind&&t.value.rest&&this.raise(s,"setter function argument must not be a rest parameter")},s.flowObjectTypeSemicolon=function(){this.eat(h.semi)||this.eat(h.comma)||this.match(h.braceR)||this.match(h.braceBarR)||this.unexpected()},s.flowParseQualifiedTypeIdentifier=function(t,e,s){t=t||this.state.start,e=e||this.state.startLoc;for(var i=s||this.parseIdentifier();this.eat(h.dot);){var r=this.startNodeAt(t,e);r.qualification=i,r.id=this.parseIdentifier(),i=this.finishNode(r,"QualifiedTypeIdentifier")}return i},s.flowParseGenericType=function(t,e,s){var i=this.startNodeAt(t,e);return i.typeParameters=null,i.id=this.flowParseQualifiedTypeIdentifier(t,e,s),this.isRelational("<")&&(i.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(i,"GenericTypeAnnotation")},s.flowParseTypeofType=function(){var t=this.startNode();return this.expect(h._typeof),t.argument=this.flowParsePrimaryType(),this.finishNode(t,"TypeofTypeAnnotation")},s.flowParseTupleType=function(){var t=this.startNode();for(t.types=[],this.expect(h.bracketL);this.state.pos<this.input.length&&!this.match(h.bracketR)&&(t.types.push(this.flowParseType()),!this.match(h.bracketR));)this.expect(h.comma);return this.expect(h.bracketR),this.finishNode(t,"TupleTypeAnnotation")},s.flowParseFunctionTypeParam=function(){var t=null,e=!1,s=null,i=this.startNode(),r=this.lookahead();return r.type===h.colon||r.type===h.question?(t=this.parseIdentifier(),this.eat(h.question)&&(e=!0),s=this.flowParseTypeInitialiser()):s=this.flowParseType(),i.name=t,i.optional=e,i.typeAnnotation=s,this.finishNode(i,"FunctionTypeParam")},s.reinterpretTypeAsFunctionTypeParam=function(t){var e=this.startNodeAt(t.start,t.loc.start);return e.name=null,e.optional=!1,e.typeAnnotation=t,this.finishNode(e,"FunctionTypeParam")},s.flowParseFunctionTypeParams=function(t){void 0===t&&(t=[]);for(var e=null;!this.match(h.parenR)&&!this.match(h.ellipsis);)t.push(this.flowParseFunctionTypeParam()),this.match(h.parenR)||this.expect(h.comma);return this.eat(h.ellipsis)&&(e=this.flowParseFunctionTypeParam()),{params:t,rest:e}},s.flowIdentToTypeAnnotation=function(t,e,s,i){switch(i.name){case"any":return this.finishNode(s,"AnyTypeAnnotation");case"void":return this.finishNode(s,"VoidTypeAnnotation");case"bool":case"boolean":return this.finishNode(s,"BooleanTypeAnnotation");case"mixed":return this.finishNode(s,"MixedTypeAnnotation");case"empty":return this.finishNode(s,"EmptyTypeAnnotation");case"number":return this.finishNode(s,"NumberTypeAnnotation");case"string":return this.finishNode(s,"StringTypeAnnotation");default:return this.flowParseGenericType(t,e,i)}},s.flowParsePrimaryType=function(){var t,e,s=this.state.start,i=this.state.startLoc,r=this.startNode(),a=!1,n=this.state.noAnonFunctionType;switch(this.state.type){case h.name:return this.isContextual("interface")?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(s,i,r,this.parseIdentifier());case h.braceL:return this.flowParseObjectType(!1,!1,!0);case h.braceBarL:return this.flowParseObjectType(!1,!0,!0);case h.bracketL:return this.flowParseTupleType();case h.relational:if("<"===this.state.value)return r.typeParameters=this.flowParseTypeParameterDeclaration(!1),this.expect(h.parenL),t=this.flowParseFunctionTypeParams(),r.params=t.params,r.rest=t.rest,this.expect(h.parenR),this.expect(h.arrow),r.returnType=this.flowParseType(),this.finishNode(r,"FunctionTypeAnnotation");break;case h.parenL:if(this.next(),!this.match(h.parenR)&&!this.match(h.ellipsis))if(this.match(h.name)){var o=this.lookahead().type;a=o!==h.question&&o!==h.colon}else a=!0;if(a){if(this.state.noAnonFunctionType=!1,e=this.flowParseType(),this.state.noAnonFunctionType=n,this.state.noAnonFunctionType||!(this.match(h.comma)||this.match(h.parenR)&&this.lookahead().type===h.arrow))return this.expect(h.parenR),e;this.eat(h.comma)}return t=e?this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(e)]):this.flowParseFunctionTypeParams(),r.params=t.params,r.rest=t.rest,this.expect(h.parenR),this.expect(h.arrow),r.returnType=this.flowParseType(),r.typeParameters=null,this.finishNode(r,"FunctionTypeAnnotation");case h.string:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case h._true:case h._false:return r.value=this.match(h._true),this.next(),this.finishNode(r,"BooleanLiteralTypeAnnotation");case h.plusMin:if("-"===this.state.value)return this.next(),this.match(h.num)||this.unexpected(null,'Unexpected token, expected "number"'),this.parseLiteral(-this.state.value,"NumberLiteralTypeAnnotation",r.start,r.loc.start);this.unexpected();case h.num:return this.parseLiteral(this.state.value,"NumberLiteralTypeAnnotation");case h._null:return this.next(),this.finishNode(r,"NullLiteralTypeAnnotation");case h._this:return this.next(),this.finishNode(r,"ThisTypeAnnotation");case h.star:return this.next(),this.finishNode(r,"ExistsTypeAnnotation");default:if("typeof"===this.state.type.keyword)return this.flowParseTypeofType()}throw this.unexpected()},s.flowParsePostfixType=function(){for(var t=this.state.start,e=this.state.startLoc,s=this.flowParsePrimaryType();!this.canInsertSemicolon()&&this.match(h.bracketL);){var i=this.startNodeAt(t,e);i.elementType=s,this.expect(h.bracketL),this.expect(h.bracketR),s=this.finishNode(i,"ArrayTypeAnnotation")}return s},s.flowParsePrefixType=function(){var t=this.startNode();return this.eat(h.question)?(t.typeAnnotation=this.flowParsePrefixType(),this.finishNode(t,"NullableTypeAnnotation")):this.flowParsePostfixType()},s.flowParseAnonFunctionWithoutParens=function(){var t=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(h.arrow)){var e=this.startNodeAt(t.start,t.loc.start);return e.params=[this.reinterpretTypeAsFunctionTypeParam(t)],e.rest=null,e.returnType=this.flowParseType(),e.typeParameters=null,this.finishNode(e,"FunctionTypeAnnotation")}return t},s.flowParseIntersectionType=function(){var t=this.startNode();this.eat(h.bitwiseAND);var e=this.flowParseAnonFunctionWithoutParens();for(t.types=[e];this.eat(h.bitwiseAND);)t.types.push(this.flowParseAnonFunctionWithoutParens());return 1===t.types.length?e:this.finishNode(t,"IntersectionTypeAnnotation")},s.flowParseUnionType=function(){var t=this.startNode();this.eat(h.bitwiseOR);var e=this.flowParseIntersectionType();for(t.types=[e];this.eat(h.bitwiseOR);)t.types.push(this.flowParseIntersectionType());return 1===t.types.length?e:this.finishNode(t,"UnionTypeAnnotation")},s.flowParseType=function(){var t=this.state.inType;this.state.inType=!0;var e=this.flowParseUnionType();return this.state.inType=t,this.state.exprAllowed=this.state.exprAllowed||this.state.noAnonFunctionType,e},s.flowParseTypeAnnotation=function(){var t=this.startNode();return t.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(t,"TypeAnnotation")},s.flowParseTypeAnnotatableIdentifier=function(t){var e=t?this.parseIdentifier():this.flowParseRestrictedIdentifier();return this.match(h.colon)&&(e.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(e,e.type)),e},s.typeCastToParameter=function(t){return t.expression.typeAnnotation=t.typeAnnotation,this.finishNodeAt(t.expression,t.expression.type,t.typeAnnotation.end,t.typeAnnotation.loc.end)},s.flowParseVariance=function(){var t=null;return this.match(h.plusMin)&&(t=this.startNode(),"+"===this.state.value?t.kind="plus":t.kind="minus",this.next(),this.finishNode(t,"Variance")),t},s.parseFunctionBody=function(e,s){var i=this;return s?this.forwardNoArrowParamsConversionAt(e,function(){return t.prototype.parseFunctionBody.call(i,e,!0)}):t.prototype.parseFunctionBody.call(this,e,!1)},s.parseFunctionBodyAndFinish=function(e,s,i){if(!i&&this.match(h.colon)){var r=this.startNode(),a=this.flowParseTypeAndPredicateInitialiser();r.typeAnnotation=a[0],e.predicate=a[1],e.returnType=r.typeAnnotation?this.finishNode(r,"TypeAnnotation"):null}t.prototype.parseFunctionBodyAndFinish.call(this,e,s,i)},s.parseStatement=function(e,s){if(this.state.strict&&this.match(h.name)&&"interface"===this.state.value){var i=this.startNode();return this.next(),this.flowParseInterface(i)}var r=t.prototype.parseStatement.call(this,e,s);return void 0!==this.flowPragma||this.isValidDirective(r)||(this.flowPragma=null),r},s.parseExpressionStatement=function(e,s){if("Identifier"===s.type)if("declare"===s.name){if(this.match(h._class)||this.match(h.name)||this.match(h._function)||this.match(h._var)||this.match(h._export))return this.flowParseDeclare(e)}else if(this.match(h.name)){if("interface"===s.name)return this.flowParseInterface(e);if("type"===s.name)return this.flowParseTypeAlias(e);if("opaque"===s.name)return this.flowParseOpaqueType(e,!1)}return t.prototype.parseExpressionStatement.call(this,e,s)},s.shouldParseExportDeclaration=function(){return this.isContextual("type")||this.isContextual("interface")||this.isContextual("opaque")||t.prototype.shouldParseExportDeclaration.call(this)},s.isExportDefaultSpecifier=function(){return(!this.match(h.name)||"type"!==this.state.value&&"interface"!==this.state.value&&"opaque"!=this.state.value)&&t.prototype.isExportDefaultSpecifier.call(this)},s.parseConditional=function(e,s,i,r,a){var n=this;if(!this.match(h.question))return e;if(a){var o=this.state.clone();try{return t.prototype.parseConditional.call(this,e,s,i,r)}catch(t){if(t instanceof SyntaxError)return this.state=o,a.start=t.pos||this.state.start,e;throw t}}this.expect(h.question);var p=this.state.clone(),c=this.state.noArrowAt,l=this.startNodeAt(i,r),u=this.tryParseConditionalConsequent(),d=u.consequent,f=u.failed,m=this.getArrowLikeExpressions(d),y=m[0],x=m[1];if(f||x.length>0){var v=c.concat();if(x.length>0){this.state=p,this.state.noArrowAt=v;for(var P=0;P<x.length;P++)v.push(x[P].start);var g=this.tryParseConditionalConsequent();d=g.consequent,f=g.failed;var b=this.getArrowLikeExpressions(d);y=b[0],x=b[1]}if(f&&y.length>1&&this.raise(p.start,"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate."),f&&1===y.length){this.state=p,this.state.noArrowAt=v.concat(y[0].start);var T=this.tryParseConditionalConsequent();d=T.consequent,f=T.failed}this.getArrowLikeExpressions(d,!0)}return this.state.noArrowAt=c,this.expect(h.colon),l.test=e,l.consequent=d,l.alternate=this.forwardNoArrowParamsConversionAt(l,function(){return n.parseMaybeAssign(s,void 0,void 0,void 0)}),this.finishNode(l,"ConditionalExpression")},s.tryParseConditionalConsequent=function(){this.state.noArrowParamsConversionAt.push(this.state.start);var t=this.parseMaybeAssign(),e=!this.match(h.colon);return this.state.noArrowParamsConversionAt.pop(),{consequent:t,failed:e}},s.getArrowLikeExpressions=function(e,s){for(var i=this,r=[e],a=[];0!==r.length;){var n=r.pop();"ArrowFunctionExpression"===n.type?(n.typeParameters||!n.returnType?(this.toAssignableList(n.params,!0,"arrow function parameters"),t.prototype.checkFunctionNameAndParams.call(this,n,!0)):a.push(n),r.push(n.body)):"ConditionalExpression"===n.type&&(r.push(n.consequent),r.push(n.alternate))}if(s){for(var o=0;o<a.length;o++)this.toAssignableList(e.params,!0,"arrow function parameters");return[a,[]]}return function(t,e){for(var s=[],i=[],r=0;r<t.length;r++)(e(t[r],r,t)?s:i).push(t[r]);return[s,i]}(a,function(t){try{return i.toAssignableList(t.params,!0,"arrow function parameters"),!0}catch(t){return!1}})},s.forwardNoArrowParamsConversionAt=function(t,e){var s;return-1!==this.state.noArrowParamsConversionAt.indexOf(t.start)?(this.state.noArrowParamsConversionAt.push(this.state.start),s=e(),this.state.noArrowParamsConversionAt.pop()):s=e(),s},s.parseParenItem=function(e,s,i){if(e=t.prototype.parseParenItem.call(this,e,s,i),this.eat(h.question)&&(e.optional=!0),this.match(h.colon)){var r=this.startNodeAt(s,i);return r.expression=e,r.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(r,"TypeCastExpression")}return e},s.assertModuleNodeAllowed=function(e){"ImportDeclaration"===e.type&&("type"===e.importKind||"typeof"===e.importKind)||"ExportNamedDeclaration"===e.type&&"type"===e.exportKind||"ExportAllDeclaration"===e.type&&"type"===e.exportKind||t.prototype.assertModuleNodeAllowed.call(this,e)},s.parseExport=function(e){return"ExportNamedDeclaration"!==(e=t.prototype.parseExport.call(this,e)).type&&"ExportAllDeclaration"!==e.type||(e.exportKind=e.exportKind||"value"),e},s.parseExportDeclaration=function(e){if(this.isContextual("type")){e.exportKind="type";var s=this.startNode();return this.next(),this.match(h.braceL)?(e.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(e),null):this.flowParseTypeAlias(s)}if(this.isContextual("opaque")){e.exportKind="type";var i=this.startNode();return this.next(),this.flowParseOpaqueType(i,!1)}if(this.isContextual("interface")){e.exportKind="type";var r=this.startNode();return this.next(),this.flowParseInterface(r)}return t.prototype.parseExportDeclaration.call(this,e)},s.shouldParseExportStar=function(){return t.prototype.shouldParseExportStar.call(this)||this.isContextual("type")&&this.lookahead().type===h.star},s.parseExportStar=function(e){return this.eatContextual("type")&&(e.exportKind="type"),t.prototype.parseExportStar.call(this,e)},s.parseExportNamespace=function(e){return"type"===e.exportKind&&this.unexpected(),t.prototype.parseExportNamespace.call(this,e)},s.parseClassId=function(e,s,i){t.prototype.parseClassId.call(this,e,s,i),this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration())},s.isKeyword=function(e){return(!this.state.inType||"void"!==e)&&t.prototype.isKeyword.call(this,e)},s.readToken=function(e){var s=this.input.charCodeAt(this.state.pos+1);return!this.state.inType||62!==e&&60!==e?function(t,e){return 64===t&&64===e}(e,s)?(this.state.isIterator=!0,t.prototype.readWord.call(this)):t.prototype.readToken.call(this,e):this.finishOp(h.relational,1)},s.toAssignable=function(e,s,i){return"TypeCastExpression"===e.type?t.prototype.toAssignable.call(this,this.typeCastToParameter(e),s,i):t.prototype.toAssignable.call(this,e,s,i)},s.toAssignableList=function(e,s,i){for(var r=0;r<e.length;r++){var a=e[r];a&&"TypeCastExpression"===a.type&&(e[r]=this.typeCastToParameter(a))}return t.prototype.toAssignableList.call(this,e,s,i)},s.toReferencedList=function(t){for(var e=0;e<t.length;e++){var s=t[e];s&&s._exprListItem&&"TypeCastExpression"===s.type&&this.raise(s.start,"Unexpected type cast")}return t},s.parseExprListItem=function(e,s,i){var r=this.startNode(),a=t.prototype.parseExprListItem.call(this,e,s,i);return this.match(h.colon)?(r._exprListItem=!0,r.expression=a,r.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(r,"TypeCastExpression")):a},s.checkLVal=function(e,s,i,r){if("TypeCastExpression"!==e.type)return t.prototype.checkLVal.call(this,e,s,i,r)},s.parseClassProperty=function(e){return this.match(h.colon)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),t.prototype.parseClassProperty.call(this,e)},s.isClassMethod=function(){return this.isRelational("<")||t.prototype.isClassMethod.call(this)},s.isClassProperty=function(){return this.match(h.colon)||t.prototype.isClassProperty.call(this)},s.isNonstaticConstructor=function(e){return!this.match(h.colon)&&t.prototype.isNonstaticConstructor.call(this,e)},s.pushClassMethod=function(e,s,i,r,a){s.variance&&this.unexpected(s.variance.start),delete s.variance,this.isRelational("<")&&(s.typeParameters=this.flowParseTypeParameterDeclaration(!1)),t.prototype.pushClassMethod.call(this,e,s,i,r,a)},s.pushClassPrivateMethod=function(e,s,i,r){s.variance&&this.unexpected(s.variance.start),delete s.variance,this.isRelational("<")&&(s.typeParameters=this.flowParseTypeParameterDeclaration()),t.prototype.pushClassPrivateMethod.call(this,e,s,i,r)},s.parseClassSuper=function(e){if(t.prototype.parseClassSuper.call(this,e),e.superClass&&this.isRelational("<")&&(e.superTypeParameters=this.flowParseTypeParameterInstantiation()),this.isContextual("implements")){this.next();var s=e.implements=[];do{var i=this.startNode();i.id=this.flowParseRestrictedIdentifier(!0),this.isRelational("<")?i.typeParameters=this.flowParseTypeParameterInstantiation():i.typeParameters=null,s.push(this.finishNode(i,"ClassImplements"))}while(this.eat(h.comma))}},s.parsePropertyName=function(e){var s=this.flowParseVariance(),i=t.prototype.parsePropertyName.call(this,e);return e.variance=s,i},s.parseObjPropValue=function(e,s,i,r,a,n,o,p){var c;e.variance&&this.unexpected(e.variance.start),delete e.variance,this.isRelational("<")&&(c=this.flowParseTypeParameterDeclaration(!1),this.match(h.parenL)||this.unexpected()),t.prototype.parseObjPropValue.call(this,e,s,i,r,a,n,o,p),c&&((e.value||e).typeParameters=c)},s.parseAssignableListItemTypes=function(t){if(this.eat(h.question)){if("Identifier"!==t.type)throw this.raise(t.start,"A binding pattern parameter cannot be optional in an implementation signature.");t.optional=!0}return this.match(h.colon)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),this.finishNode(t,t.type),t},s.parseMaybeDefault=function(e,s,i){var r=t.prototype.parseMaybeDefault.call(this,e,s,i);return"AssignmentPattern"===r.type&&r.typeAnnotation&&r.right.start<r.typeAnnotation.start&&this.raise(r.typeAnnotation.start,"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`"),r},s.shouldParseDefaultImport=function(e){return A(e)?E(this.state):t.prototype.shouldParseDefaultImport.call(this,e)},s.parseImportSpecifierLocal=function(t,e,s,i){e.local=A(t)?this.flowParseRestrictedIdentifier(!0):this.parseIdentifier(),this.checkLVal(e.local,!0,void 0,i),t.specifiers.push(this.finishNode(e,s))},s.parseImportSpecifiers=function(e){e.importKind="value";var s=null;if(this.match(h._typeof)?s="typeof":this.isContextual("type")&&(s="type"),s){var i=this.lookahead();"type"===s&&i.type===h.star&&this.unexpected(i.start),(E(i)||i.type===h.braceL||i.type===h.star)&&(this.next(),e.importKind=s)}t.prototype.parseImportSpecifiers.call(this,e)},s.parseImportSpecifier=function(t){var e=this.startNode(),s=this.state.start,i=this.parseIdentifier(!0),r=null;"type"===i.name?r="type":"typeof"===i.name&&(r="typeof");var a=!1;if(this.isContextual("as")&&!this.isLookaheadContextual("as")){var n=this.parseIdentifier(!0);null===r||this.match(h.name)||this.state.type.keyword?(e.imported=i,e.importKind=null,e.local=this.parseIdentifier()):(e.imported=n,e.importKind=r,e.local=n.__clone())}else null!==r&&(this.match(h.name)||this.state.type.keyword)?(e.imported=this.parseIdentifier(!0),e.importKind=r,this.eatContextual("as")?e.local=this.parseIdentifier():(a=!0,e.local=e.imported.__clone())):(a=!0,e.imported=i,e.importKind=null,e.local=e.imported.__clone());var o=A(t),p=A(e);o&&p&&this.raise(s,"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements"),(o||p)&&this.checkReservedType(e.local.name,e.local.start),!a||o||p||this.checkReservedWord(e.local.name,e.start,!0,!0),this.checkLVal(e.local,!0,void 0,"import specifier"),t.specifiers.push(this.finishNode(e,"ImportSpecifier"))},s.parseFunctionParams=function(e){var s=e.kind;"get"!==s&&"set"!==s&&this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration(!1)),t.prototype.parseFunctionParams.call(this,e)},s.parseVarHead=function(e){t.prototype.parseVarHead.call(this,e),this.match(h.colon)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(e.id,e.id.type))},s.parseAsyncArrowFromCallExpression=function(e,s){if(this.match(h.colon)){var i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,e.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=i}return t.prototype.parseAsyncArrowFromCallExpression.call(this,e,s)},s.shouldParseAsyncArrow=function(){return this.match(h.colon)||t.prototype.shouldParseAsyncArrow.call(this)},s.parseMaybeAssign=function(e,s,i,r){var a=this,n=null;if(h.jsxTagStart&&this.match(h.jsxTagStart)){var o=this.state.clone();try{return t.prototype.parseMaybeAssign.call(this,e,s,i,r)}catch(t){if(!(t instanceof SyntaxError))throw t;this.state=o,this.state.context.length-=2,n=t}}if(null!=n||this.isRelational("<")){var p,c;try{c=this.flowParseTypeParameterDeclaration(),(p=this.forwardNoArrowParamsConversionAt(c,function(){return t.prototype.parseMaybeAssign.call(a,e,s,i,r)})).typeParameters=c,this.resetStartLocationFromNode(p,c)}catch(t){throw n||t}if("ArrowFunctionExpression"===p.type)return p;if(null!=n)throw n;this.raise(c.start,"Expected an arrow function after this type parameter declaration")}return t.prototype.parseMaybeAssign.call(this,e,s,i,r)},s.parseArrow=function(e){if(this.match(h.colon)){var s=this.state.clone();try{var i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;var r=this.startNode(),a=this.flowParseTypeAndPredicateInitialiser();r.typeAnnotation=a[0],e.predicate=a[1],this.state.noAnonFunctionType=i,this.canInsertSemicolon()&&this.unexpected(),this.match(h.arrow)||this.unexpected(),e.returnType=r.typeAnnotation?this.finishNode(r,"TypeAnnotation"):null}catch(t){if(!(t instanceof SyntaxError))throw t;this.state=s}}return t.prototype.parseArrow.call(this,e)},s.shouldParseArrow=function(){return this.match(h.colon)||t.prototype.shouldParseArrow.call(this)},s.setArrowFunctionParameters=function(e,s){-1!==this.state.noArrowParamsConversionAt.indexOf(e.start)?e.params=s:t.prototype.setArrowFunctionParameters.call(this,e,s)},s.checkFunctionNameAndParams=function(e,s){if(!s||-1===this.state.noArrowParamsConversionAt.indexOf(e.start))return t.prototype.checkFunctionNameAndParams.call(this,e,s)},s.parseParenAndDistinguishExpression=function(e){return t.prototype.parseParenAndDistinguishExpression.call(this,e&&-1===this.state.noArrowAt.indexOf(this.state.start))},s.parseSubscripts=function(e,s,i,r){if("Identifier"===e.type&&"async"===e.name&&-1!==this.state.noArrowAt.indexOf(s)){this.next();var a=this.startNodeAt(s,i);a.callee=e,a.arguments=this.parseCallExpressionArguments(h.parenR,!1),e=this.finishNode(a,"CallExpression")}else if("Identifier"===e.type&&"async"===e.name&&this.isRelational("<")){var n,o=this.state.clone();try{var p=this.parseAsyncArrowWithTypeParameters(s,i);if(p)return p}catch(t){n=t}this.state=o;try{return t.prototype.parseSubscripts.call(this,e,s,i,r)}catch(t){throw n||t}}return t.prototype.parseSubscripts.call(this,e,s,i,r)},s.parseSubscript=function(e,s,i,r,a){if(this.match(h.questionDot)&&this.isLookaheadRelational("<")){if(this.expectPlugin("optionalChaining"),a.optionalChainMember=!0,r)return a.stop=!0,e;this.next();var n=this.startNodeAt(s,i);return n.callee=e,n.typeArguments=this.flowParseTypeParameterInstantiation(),this.expect(h.parenL),n.arguments=this.parseCallExpressionArguments(h.parenR,!1),n.optional=!0,this.finishNode(n,"OptionalCallExpression")}if(!r&&this.shouldParseTypes()&&this.isRelational("<")){var o=this.startNodeAt(s,i);o.callee=e;var p=this.state.clone();try{return o.typeArguments=this.flowParseTypeParameterInstantiation(),this.expect(h.parenL),o.arguments=this.parseCallExpressionArguments(h.parenR,!1),a.optionalChainMember?(o.optional=!1,this.finishNode(o,"OptionalCallExpression")):this.finishNode(o,"CallExpression")}catch(t){if(!(t instanceof SyntaxError))throw t;this.state=p}}return t.prototype.parseSubscript.call(this,e,s,i,r,a)},s.parseNewArguments=function(e){var s=null;if(this.shouldParseTypes()&&this.isRelational("<")){var i=this.state.clone();try{s=this.flowParseTypeParameterInstantiation()}catch(t){if(!(t instanceof SyntaxError))throw t;this.state=i}}e.typeArguments=s,t.prototype.parseNewArguments.call(this,e)},s.parseAsyncArrowWithTypeParameters=function(t,e){var s=this.startNodeAt(t,e);if(this.parseFunctionParams(s),this.parseArrow(s))return this.parseArrowExpression(s,void 0,!0)},s.readToken_mult_modulo=function(e){var s=this.input.charCodeAt(this.state.pos+1);if(42===e&&47===s&&this.state.hasFlowComment)return this.state.hasFlowComment=!1,this.state.pos+=2,void this.nextToken();t.prototype.readToken_mult_modulo.call(this,e)},s.skipBlockComment=function(){return this.hasPlugin("flow")&&this.hasPlugin("flowComments")&&this.skipFlowComment()?(this.hasFlowCommentCompletion(),this.state.pos+=this.skipFlowComment(),void(this.state.hasFlowComment=!0)):this.hasPlugin("flow")&&this.state.hasFlowComment?(-1===(e=this.input.indexOf("*-/",this.state.pos+=2))&&this.raise(this.state.pos-2,"Unterminated comment"),void(this.state.pos=e+3)):void t.prototype.skipBlockComment.call(this);var e},s.skipFlowComment=function(){var t=this.input.charCodeAt(this.state.pos+2),e=this.input.charCodeAt(this.state.pos+3);return 58===t&&58===e?4:"flow-include"===this.input.slice(this.state.pos+2,14)?14:58===t&&58!==e&&2},s.hasFlowCommentCompletion=function(){-1===this.input.indexOf("*/",this.state.pos)&&this.raise(this.state.pos,"Unterminated comment")},e}(t)},typescript:function(t){return function(t){function e(){return t.apply(this,arguments)||this}i(e,t);var s=e.prototype;return s.tsIsIdentifier=function(){return this.match(h.name)},s.tsNextTokenCanFollowModifier=function(){return this.next(),!(this.hasPrecedingLineBreak()||this.match(h.parenL)||this.match(h.colon)||this.match(h.eq)||this.match(h.question))},s.tsParseModifier=function(t){if(this.match(h.name)){var e=this.state.value;return-1!==t.indexOf(e)&&this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))?e:void 0}},s.tsIsListTerminator=function(t){switch(t){case"EnumMembers":case"TypeMembers":return this.match(h.braceR);case"HeritageClauseElement":return this.match(h.braceL);case"TupleElementTypes":return this.match(h.bracketR);case"TypeParametersOrArguments":return this.isRelational(">")}throw new Error("Unreachable")},s.tsParseList=function(t,e){for(var s=[];!this.tsIsListTerminator(t);)s.push(e());return s},s.tsParseDelimitedList=function(t,e){return st(this.tsParseDelimitedListWorker(t,e,!0))},s.tsTryParseDelimitedList=function(t,e){return this.tsParseDelimitedListWorker(t,e,!1)},s.tsParseDelimitedListWorker=function(t,e,s){for(var i=[];!this.tsIsListTerminator(t);){var r=e();if(null==r)return;if(i.push(r),!this.eat(h.comma)){if(this.tsIsListTerminator(t))break;return void(s&&this.expect(h.comma))}}return i},s.tsParseBracketedList=function(t,e,s,i){i||(s?this.expect(h.bracketL):this.expectRelational("<"));var r=this.tsParseDelimitedList(t,e);return s?this.expect(h.bracketR):this.expectRelational(">"),r},s.tsParseEntityName=function(t){for(var e=this.parseIdentifier();this.eat(h.dot);){var s=this.startNodeAtNode(e);s.left=e,s.right=this.parseIdentifier(t),e=this.finishNode(s,"TSQualifiedName")}return e},s.tsParseTypeReference=function(){var t=this.startNode();return t.typeName=this.tsParseEntityName(!1),!this.hasPrecedingLineBreak()&&this.isRelational("<")&&(t.typeParameters=this.tsParseTypeArguments()),this.finishNode(t,"TSTypeReference")},s.tsParseThisTypePredicate=function(t){this.next();var e=this.startNode();return e.parameterName=t,e.typeAnnotation=this.tsParseTypeAnnotation(!1),this.finishNode(e,"TSTypePredicate")},s.tsParseThisTypeNode=function(){var t=this.startNode();return this.next(),this.finishNode(t,"TSThisType")},s.tsParseTypeQuery=function(){var t=this.startNode();return this.expect(h._typeof),t.exprName=this.tsParseEntityName(!0),this.finishNode(t,"TSTypeQuery")},s.tsParseTypeParameter=function(){var t=this.startNode();return t.name=this.parseIdentifierName(t.start),t.constraint=this.tsEatThenParseType(h._extends),t.default=this.tsEatThenParseType(h.eq),this.finishNode(t,"TSTypeParameter")},s.tsTryParseTypeParameters=function(){if(this.isRelational("<"))return this.tsParseTypeParameters()},s.tsParseTypeParameters=function(){var t=this.startNode();return this.isRelational("<")||this.match(h.jsxTagStart)?this.next():this.unexpected(),t.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this),!1,!0),this.finishNode(t,"TSTypeParameterDeclaration")},s.tsFillSignature=function(t,e){var s=t===h.arrow;e.typeParameters=this.tsTryParseTypeParameters(),this.expect(h.parenL),e.parameters=this.tsParseBindingListForSignature(),s?e.typeAnnotation=this.tsParseTypeOrTypePredicateAnnotation(t):this.match(t)&&(e.typeAnnotation=this.tsParseTypeOrTypePredicateAnnotation(t))},s.tsParseBindingListForSignature=function(){var t=this;return this.parseBindingList(h.parenR).map(function(e){if("Identifier"!==e.type&&"RestElement"!==e.type)throw t.unexpected(e.start,"Name in a signature must be an Identifier.");return e})},s.tsParseTypeMemberSemicolon=function(){this.eat(h.comma)||this.semicolon()},s.tsParseSignatureMember=function(t){var e=this.startNode();return"TSConstructSignatureDeclaration"===t&&this.expect(h._new),this.tsFillSignature(h.colon,e),this.tsParseTypeMemberSemicolon(),this.finishNode(e,t)},s.tsIsUnambiguouslyIndexSignature=function(){return this.next(),this.eat(h.name)&&this.match(h.colon)},s.tsTryParseIndexSignature=function(t){if(this.match(h.bracketL)&&this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this))){this.expect(h.bracketL);var e=this.parseIdentifier();this.expect(h.colon),e.typeAnnotation=this.tsParseTypeAnnotation(!1),this.expect(h.bracketR),t.parameters=[e];var s=this.tsTryParseTypeAnnotation();return s&&(t.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(t,"TSIndexSignature")}},s.tsParsePropertyOrMethodSignature=function(t,e){this.parsePropertyName(t),this.eat(h.question)&&(t.optional=!0);var s=t;if(e||!this.match(h.parenL)&&!this.isRelational("<")){var i=s;e&&(i.readonly=!0);var r=this.tsTryParseTypeAnnotation();return r&&(i.typeAnnotation=r),this.tsParseTypeMemberSemicolon(),this.finishNode(i,"TSPropertySignature")}var a=s;return this.tsFillSignature(h.colon,a),this.tsParseTypeMemberSemicolon(),this.finishNode(a,"TSMethodSignature")},s.tsParseTypeMember=function(){if(this.match(h.parenL)||this.isRelational("<"))return this.tsParseSignatureMember("TSCallSignatureDeclaration");if(this.match(h._new)&&this.tsLookAhead(this.tsIsStartOfConstructSignature.bind(this)))return this.tsParseSignatureMember("TSConstructSignatureDeclaration");var t=this.startNode(),e=!!this.tsParseModifier(["readonly"]),s=this.tsTryParseIndexSignature(t);return s?(e&&(t.readonly=!0),s):this.tsParsePropertyOrMethodSignature(t,e)},s.tsIsStartOfConstructSignature=function(){return this.next(),this.match(h.parenL)||this.isRelational("<")},s.tsParseTypeLiteral=function(){var t=this.startNode();return t.members=this.tsParseObjectTypeMembers(),this.finishNode(t,"TSTypeLiteral")},s.tsParseObjectTypeMembers=function(){this.expect(h.braceL);var t=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(h.braceR),t},s.tsIsStartOfMappedType=function(){return this.next(),this.eat(h.plusMin)?this.isContextual("readonly"):(this.isContextual("readonly")&&this.next(),!!this.match(h.bracketL)&&(this.next(),!!this.tsIsIdentifier()&&(this.next(),this.match(h._in))))},s.tsParseMappedTypeParameter=function(){var t=this.startNode();return t.name=this.parseIdentifierName(t.start),t.constraint=this.tsExpectThenParseType(h._in),this.finishNode(t,"TSTypeParameter")},s.tsParseMappedType=function(){var t=this.startNode();return this.expect(h.braceL),this.match(h.plusMin)?(t.readonly=this.state.value,this.next(),this.expectContextual("readonly")):this.eatContextual("readonly")&&(t.readonly=!0),this.expect(h.bracketL),t.typeParameter=this.tsParseMappedTypeParameter(),this.expect(h.bracketR),this.match(h.plusMin)?(t.optional=this.state.value,this.next(),this.expect(h.question)):this.eat(h.question)&&(t.optional=!0),t.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(h.braceR),this.finishNode(t,"TSMappedType")},s.tsParseTupleType=function(){var t=this.startNode();return t.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseType.bind(this),!0,!1),this.finishNode(t,"TSTupleType")},s.tsParseParenthesizedType=function(){var t=this.startNode();return this.expect(h.parenL),t.typeAnnotation=this.tsParseType(),this.expect(h.parenR),this.finishNode(t,"TSParenthesizedType")},s.tsParseFunctionOrConstructorType=function(t){var e=this.startNode();return"TSConstructorType"===t&&this.expect(h._new),this.tsFillSignature(h.arrow,e),this.finishNode(e,t)},s.tsParseLiteralTypeNode=function(){var t=this,e=this.startNode();return e.literal=function(){switch(t.state.type){case h.num:return t.parseLiteral(t.state.value,"NumericLiteral");case h.string:return t.parseLiteral(t.state.value,"StringLiteral");case h._true:case h._false:return t.parseBooleanLiteral();default:throw t.unexpected()}}(),this.finishNode(e,"TSLiteralType")},s.tsParseNonArrayType=function(){switch(this.state.type){case h.name:case h._void:case h._null:var t=this.match(h._void)?"TSVoidKeyword":this.match(h._null)?"TSNullKeyword":function(t){switch(t){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";default:return}}(this.state.value);if(void 0!==t&&this.lookahead().type!==h.dot){var e=this.startNode();return this.next(),this.finishNode(e,t)}return this.tsParseTypeReference();case h.string:case h.num:case h._true:case h._false:return this.tsParseLiteralTypeNode();case h.plusMin:if("-"===this.state.value){var s=this.startNode();if(this.next(),!this.match(h.num))throw this.unexpected();return s.literal=this.parseLiteral(-this.state.value,"NumericLiteral",s.start,s.loc.start),this.finishNode(s,"TSLiteralType")}break;case h._this:var i=this.tsParseThisTypeNode();return this.isContextual("is")&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(i):i;case h._typeof:return this.tsParseTypeQuery();case h.braceL:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case h.bracketL:return this.tsParseTupleType();case h.parenL:return this.tsParseParenthesizedType()}throw this.unexpected()},s.tsParseArrayTypeOrHigher=function(){for(var t=this.tsParseNonArrayType();!this.hasPrecedingLineBreak()&&this.eat(h.bracketL);)if(this.match(h.bracketR)){var e=this.startNodeAtNode(t);e.elementType=t,this.expect(h.bracketR),t=this.finishNode(e,"TSArrayType")}else{var s=this.startNodeAtNode(t);s.objectType=t,s.indexType=this.tsParseType(),this.expect(h.bracketR),t=this.finishNode(s,"TSIndexedAccessType")}return t},s.tsParseTypeOperator=function(t){var e=this.startNode();return this.expectContextual(t),e.operator=t,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),this.finishNode(e,"TSTypeOperator")},s.tsParseInferType=function(){var t=this.startNode();this.expectContextual("infer");var e=this.startNode();return e.name=this.parseIdentifierName(e.start),t.typeParameter=this.finishNode(e,"TSTypeParameter"),this.finishNode(t,"TSInferType")},s.tsParseTypeOperatorOrHigher=function(){var t=this,e=["keyof","unique"].find(function(e){return t.isContextual(e)});return e?this.tsParseTypeOperator(e):this.isContextual("infer")?this.tsParseInferType():this.tsParseArrayTypeOrHigher()},s.tsParseUnionOrIntersectionType=function(t,e,s){this.eat(s);var i=e();if(this.match(s)){for(var r=[i];this.eat(s);)r.push(e());var a=this.startNodeAtNode(i);a.types=r,i=this.finishNode(a,t)}return i},s.tsParseIntersectionTypeOrHigher=function(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),h.bitwiseAND)},s.tsParseUnionTypeOrHigher=function(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),h.bitwiseOR)},s.tsIsStartOfFunctionType=function(){return!!this.isRelational("<")||this.match(h.parenL)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))},s.tsSkipParameterStart=function(){return!(!this.match(h.name)&&!this.match(h._this)||(this.next(),0))},s.tsIsUnambiguouslyStartOfFunctionType=function(){if(this.next(),this.match(h.parenR)||this.match(h.ellipsis))return!0;if(this.tsSkipParameterStart()){if(this.match(h.colon)||this.match(h.comma)||this.match(h.question)||this.match(h.eq))return!0;if(this.match(h.parenR)&&(this.next(),this.match(h.arrow)))return!0}return!1},s.tsParseTypeOrTypePredicateAnnotation=function(t){var e=this;return this.tsInType(function(){var s=e.startNode();e.expect(t);var i=e.tsIsIdentifier()&&e.tsTryParse(e.tsParseTypePredicatePrefix.bind(e));if(!i)return e.tsParseTypeAnnotation(!1,s);var r=e.tsParseTypeAnnotation(!1),a=e.startNodeAtNode(i);return a.parameterName=i,a.typeAnnotation=r,s.typeAnnotation=e.finishNode(a,"TSTypePredicate"),e.finishNode(s,"TSTypeAnnotation")})},s.tsTryParseTypeOrTypePredicateAnnotation=function(){return this.match(h.colon)?this.tsParseTypeOrTypePredicateAnnotation(h.colon):void 0},s.tsTryParseTypeAnnotation=function(){return this.match(h.colon)?this.tsParseTypeAnnotation():void 0},s.tsTryParseType=function(){return this.tsEatThenParseType(h.colon)},s.tsParseTypePredicatePrefix=function(){var t=this.parseIdentifier();if(this.isContextual("is")&&!this.hasPrecedingLineBreak())return this.next(),t},s.tsParseTypeAnnotation=function(t,e){var s=this;return void 0===t&&(t=!0),void 0===e&&(e=this.startNode()),this.tsInType(function(){t&&s.expect(h.colon),e.typeAnnotation=s.tsParseType()}),this.finishNode(e,"TSTypeAnnotation")},s.tsParseType=function(){it(this.state.inType);var t=this.tsParseNonConditionalType();if(this.hasPrecedingLineBreak()||!this.eat(h._extends))return t;var e=this.startNodeAtNode(t);return e.checkType=t,e.extendsType=this.tsParseNonConditionalType(),this.expect(h.question),e.trueType=this.tsParseType(),this.expect(h.colon),e.falseType=this.tsParseType(),this.finishNode(e,"TSConditionalType")},s.tsParseNonConditionalType=function(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(h._new)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.tsParseUnionTypeOrHigher()},s.tsParseTypeAssertion=function(){var t=this,e=this.startNode();return e.typeAnnotation=this.tsInType(function(){return t.tsParseType()}),this.expectRelational(">"),e.expression=this.parseMaybeUnary(),this.finishNode(e,"TSTypeAssertion")},s.tsTryParseTypeArgumentsInExpression=function(){var t=this;return this.tsTryParseAndCatch(function(){var e=t.tsParseTypeArguments();return t.expect(h.parenL),e})},s.tsParseHeritageClause=function(){return this.tsParseDelimitedList("HeritageClauseElement",this.tsParseExpressionWithTypeArguments.bind(this))},s.tsParseExpressionWithTypeArguments=function(){var t=this.startNode();return t.expression=this.tsParseEntityName(!1),this.isRelational("<")&&(t.typeParameters=this.tsParseTypeArguments()),this.finishNode(t,"TSExpressionWithTypeArguments")},s.tsParseInterfaceDeclaration=function(t){t.id=this.parseIdentifier(),t.typeParameters=this.tsTryParseTypeParameters(),this.eat(h._extends)&&(t.extends=this.tsParseHeritageClause());var e=this.startNode();return e.body=this.tsParseObjectTypeMembers(),t.body=this.finishNode(e,"TSInterfaceBody"),this.finishNode(t,"TSInterfaceDeclaration")},s.tsParseTypeAliasDeclaration=function(t){return t.id=this.parseIdentifier(),t.typeParameters=this.tsTryParseTypeParameters(),t.typeAnnotation=this.tsExpectThenParseType(h.eq),this.semicolon(),this.finishNode(t,"TSTypeAliasDeclaration")},s.tsInType=function(t){var e=this.state.inType;this.state.inType=!0;try{return t()}finally{this.state.inType=e}},s.tsEatThenParseType=function(t){return this.match(t)?this.tsNextThenParseType():void 0},s.tsExpectThenParseType=function(t){var e=this;return this.tsDoThenParseType(function(){return e.expect(t)})},s.tsNextThenParseType=function(){var t=this;return this.tsDoThenParseType(function(){return t.next()})},s.tsDoThenParseType=function(t){var e=this;return this.tsInType(function(){return t(),e.tsParseType()})},s.tsParseEnumMember=function(){var t=this.startNode();return t.id=this.match(h.string)?this.parseLiteral(this.state.value,"StringLiteral"):this.parseIdentifier(!0),this.eat(h.eq)&&(t.initializer=this.parseMaybeAssign()),this.finishNode(t,"TSEnumMember")},s.tsParseEnumDeclaration=function(t,e){return e&&(t.const=!0),t.id=this.parseIdentifier(),this.expect(h.braceL),t.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(h.braceR),this.finishNode(t,"TSEnumDeclaration")},s.tsParseModuleBlock=function(){var t=this.startNode();return this.expect(h.braceL),this.parseBlockOrModuleBlockBody(t.body=[],void 0,!0,h.braceR),this.finishNode(t,"TSModuleBlock")},s.tsParseModuleOrNamespaceDeclaration=function(t){if(t.id=this.parseIdentifier(),this.eat(h.dot)){var e=this.startNode();this.tsParseModuleOrNamespaceDeclaration(e),t.body=e}else t.body=this.tsParseModuleBlock();return this.finishNode(t,"TSModuleDeclaration")},s.tsParseAmbientExternalModuleDeclaration=function(t){return this.isContextual("global")?(t.global=!0,t.id=this.parseIdentifier()):this.match(h.string)?t.id=this.parseExprAtom():this.unexpected(),this.match(h.braceL)?t.body=this.tsParseModuleBlock():this.semicolon(),this.finishNode(t,"TSModuleDeclaration")},s.tsParseImportEqualsDeclaration=function(t,e){return t.isExport=e||!1,t.id=this.parseIdentifier(),this.expect(h.eq),t.moduleReference=this.tsParseModuleReference(),this.semicolon(),this.finishNode(t,"TSImportEqualsDeclaration")},s.tsIsExternalModuleReference=function(){return this.isContextual("require")&&this.lookahead().type===h.parenL},s.tsParseModuleReference=function(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(!1)},s.tsParseExternalModuleReference=function(){var t=this.startNode();if(this.expectContextual("require"),this.expect(h.parenL),!this.match(h.string))throw this.unexpected();return t.expression=this.parseLiteral(this.state.value,"StringLiteral"),this.expect(h.parenR),this.finishNode(t,"TSExternalModuleReference")},s.tsLookAhead=function(t){var e=this.state.clone(),s=t();return this.state=e,s},s.tsTryParseAndCatch=function(t){var e=this.state.clone();try{return t()}catch(t){if(t instanceof SyntaxError)return void(this.state=e);throw t}},s.tsTryParse=function(t){var e=this.state.clone(),s=t();return void 0!==s&&!1!==s?s:void(this.state=e)},s.nodeWithSamePosition=function(t,e){var s=this.startNodeAtNode(t);return s.type=e,s.end=t.end,s.loc.end=t.loc.end,t.leadingComments&&(s.leadingComments=t.leadingComments),t.trailingComments&&(s.trailingComments=t.trailingComments),t.innerComments&&(s.innerComments=t.innerComments),s},s.tsTryParseDeclare=function(t){switch(this.state.type){case h._function:return this.next(),this.parseFunction(t,!0);case h._class:return this.parseClass(t,!0,!1);case h._const:if(this.match(h._const)&&this.isLookaheadContextual("enum"))return this.expect(h._const),this.expectContextual("enum"),this.tsParseEnumDeclaration(t,!0);case h._var:case h._let:return this.parseVarStatement(t,this.state.type);case h.name:var e=this.state.value;return"global"===e?this.tsParseAmbientExternalModuleDeclaration(t):this.tsParseDeclaration(t,e,!0)}},s.tsTryParseExportDeclaration=function(){return this.tsParseDeclaration(this.startNode(),this.state.value,!0)},s.tsParseExpressionStatement=function(t,e){switch(e.name){case"declare":var s=this.tsTryParseDeclare(t);if(s)return s.declare=!0,s;break;case"global":if(this.match(h.braceL)){var i=t;return i.global=!0,i.id=e,i.body=this.tsParseModuleBlock(),this.finishNode(i,"TSModuleDeclaration")}break;default:return this.tsParseDeclaration(t,e.name,!1)}},s.tsParseDeclaration=function(t,e,s){switch(e){case"abstract":if(s||this.match(h._class)){var i=t;return i.abstract=!0,s&&this.next(),this.parseClass(i,!0,!1)}break;case"enum":if(s||this.match(h.name))return s&&this.next(),this.tsParseEnumDeclaration(t,!1);break;case"interface":if(s||this.match(h.name))return s&&this.next(),this.tsParseInterfaceDeclaration(t);break;case"module":if(s&&this.next(),this.match(h.string))return this.tsParseAmbientExternalModuleDeclaration(t);if(s||this.match(h.name))return this.tsParseModuleOrNamespaceDeclaration(t);break;case"namespace":if(s||this.match(h.name))return s&&this.next(),this.tsParseModuleOrNamespaceDeclaration(t);break;case"type":if(s||this.match(h.name))return s&&this.next(),this.tsParseTypeAliasDeclaration(t)}},s.tsTryParseGenericAsyncArrowFunction=function(e,s){var i=this,r=this.tsTryParseAndCatch(function(){var r=i.startNodeAt(e,s);return r.typeParameters=i.tsParseTypeParameters(),t.prototype.parseFunctionParams.call(i,r),r.returnType=i.tsTryParseTypeOrTypePredicateAnnotation(),i.expect(h.arrow),r});if(r)return r.id=null,r.generator=!1,r.expression=!0,r.async=!0,this.parseFunctionBody(r,!0),this.finishNode(r,"ArrowFunctionExpression")},s.tsParseTypeArguments=function(){var t=this,e=this.startNode();return e.params=this.tsInType(function(){return t.expectRelational("<"),t.tsParseDelimitedList("TypeParametersOrArguments",t.tsParseType.bind(t))}),this.expectRelational(">"),this.finishNode(e,"TSTypeParameterInstantiation")},s.tsIsDeclarationStart=function(){if(this.match(h.name))switch(this.state.value){case"abstract":case"declare":case"enum":case"interface":case"module":case"namespace":case"type":return!0}return!1},s.isExportDefaultSpecifier=function(){return!this.tsIsDeclarationStart()&&t.prototype.isExportDefaultSpecifier.call(this)},s.parseAssignableListItem=function(t,e){var s,i=!1;t&&(s=this.parseAccessModifier(),i=!!this.tsParseModifier(["readonly"]));var r=this.parseMaybeDefault();this.parseAssignableListItemTypes(r);var a=this.parseMaybeDefault(r.start,r.loc.start,r);if(s||i){var n=this.startNodeAtNode(a);if(e.length&&(n.decorators=e),s&&(n.accessibility=s),i&&(n.readonly=i),"Identifier"!==a.type&&"AssignmentPattern"!==a.type)throw this.raise(n.start,"A parameter property may not be declared using a binding pattern.");return n.parameter=a,this.finishNode(n,"TSParameterProperty")}return e.length&&(r.decorators=e),a},s.parseFunctionBodyAndFinish=function(e,s,i){!i&&this.match(h.colon)&&(e.returnType=this.tsParseTypeOrTypePredicateAnnotation(h.colon));var r="FunctionDeclaration"===s?"TSDeclareFunction":"ClassMethod"===s?"TSDeclareMethod":void 0;r&&!this.match(h.braceL)&&this.isLineTerminator()?this.finishNode(e,r):t.prototype.parseFunctionBodyAndFinish.call(this,e,s,i)},s.parseSubscript=function(e,s,i,r,a){if(!this.hasPrecedingLineBreak()&&this.match(h.bang)){this.state.exprAllowed=!1,this.next();var n=this.startNodeAt(s,i);return n.expression=e,this.finishNode(n,"TSNonNullExpression")}if(!r&&this.isRelational("<")){if(this.atPossibleAsync(e)){var o=this.tsTryParseGenericAsyncArrowFunction(s,i);if(o)return o}var p=this.startNodeAt(s,i);p.callee=e;var c=this.tsTryParseTypeArgumentsInExpression();if(c)return p.arguments=this.parseCallExpressionArguments(h.parenR,!1),p.typeParameters=c,this.finishCallExpression(p)}return t.prototype.parseSubscript.call(this,e,s,i,r,a)},s.parseNewArguments=function(e){var s=this;if(this.isRelational("<")){var i=this.tsTryParseAndCatch(function(){var t=s.tsParseTypeArguments();return s.match(h.parenL)||s.unexpected(),t});i&&(e.typeParameters=i)}t.prototype.parseNewArguments.call(this,e)},s.parseExprOp=function(e,s,i,r,a){if(st(h._in.binop)>r&&!this.hasPrecedingLineBreak()&&this.isContextual("as")){var n=this.startNodeAt(s,i);return n.expression=e,n.typeAnnotation=this.tsNextThenParseType(),this.finishNode(n,"TSAsExpression"),this.parseExprOp(n,s,i,r,a)}return t.prototype.parseExprOp.call(this,e,s,i,r,a)},s.checkReservedWord=function(t,e,s,i){},s.checkDuplicateExports=function(){},s.parseImport=function(e){return this.match(h.name)&&this.lookahead().type===h.eq?this.tsParseImportEqualsDeclaration(e):t.prototype.parseImport.call(this,e)},s.parseExport=function(e){if(this.match(h._import))return this.expect(h._import),this.tsParseImportEqualsDeclaration(e,!0);if(this.eat(h.eq)){var s=e;return s.expression=this.parseExpression(),this.semicolon(),this.finishNode(s,"TSExportAssignment")}if(this.eatContextual("as")){var i=e;return this.expectContextual("namespace"),i.id=this.parseIdentifier(),this.semicolon(),this.finishNode(i,"TSNamespaceExportDeclaration")}return t.prototype.parseExport.call(this,e)},s.isAbstractClass=function(){return this.isContextual("abstract")&&this.lookahead().type===h._class},s.parseExportDefaultExpression=function(){if(this.isAbstractClass()){var e=this.startNode();return this.next(),this.parseClass(e,!0,!0),e.abstract=!0,e}return t.prototype.parseExportDefaultExpression.call(this)},s.parseStatementContent=function(e,s){if(this.state.type===h._const){var i=this.lookahead();if(i.type===h.name&&"enum"===i.value){var r=this.startNode();return this.expect(h._const),this.expectContextual("enum"),this.tsParseEnumDeclaration(r,!0)}}return t.prototype.parseStatementContent.call(this,e,s)},s.parseAccessModifier=function(){return this.tsParseModifier(["public","protected","private"])},s.parseClassMember=function(e,s,i){var r=this.parseAccessModifier();r&&(s.accessibility=r),t.prototype.parseClassMember.call(this,e,s,i)},s.parseClassMemberWithIsStatic=function(e,s,i,r){var a=s,n=s,o=s,h=!1,p=!1;switch(this.tsParseModifier(["abstract","readonly"])){case"readonly":p=!0,h=!!this.tsParseModifier(["abstract"]);break;case"abstract":h=!0,p=!!this.tsParseModifier(["readonly"])}if(h&&(a.abstract=!0),p&&(o.readonly=!0),!h&&!r&&!a.accessibility){var c=this.tsTryParseIndexSignature(s);if(c)return void e.body.push(c)}if(p)return a.static=r,this.parseClassPropertyName(n),this.parsePostMemberNameModifiers(a),void this.pushClassProperty(e,n);t.prototype.parseClassMemberWithIsStatic.call(this,e,s,i,r)},s.parsePostMemberNameModifiers=function(t){this.eat(h.question)&&(t.optional=!0)},s.parseExpressionStatement=function(e,s){return("Identifier"===s.type?this.tsParseExpressionStatement(e,s):void 0)||t.prototype.parseExpressionStatement.call(this,e,s)},s.shouldParseExportDeclaration=function(){return!!this.tsIsDeclarationStart()||t.prototype.shouldParseExportDeclaration.call(this)},s.parseConditional=function(e,s,i,r,a){if(!a||!this.match(h.question))return t.prototype.parseConditional.call(this,e,s,i,r,a);var n=this.state.clone();try{return t.prototype.parseConditional.call(this,e,s,i,r)}catch(t){if(!(t instanceof SyntaxError))throw t;return this.state=n,a.start=t.pos||this.state.start,e}},s.parseParenItem=function(e,s,i){if(e=t.prototype.parseParenItem.call(this,e,s,i),this.eat(h.question)&&(e.optional=!0),this.match(h.colon)){var r=this.startNodeAt(s,i);return r.expression=e,r.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(r,"TSTypeCastExpression")}return e},s.parseExportDeclaration=function(e){var s,i=this.eatContextual("declare");return this.match(h.name)&&(s=this.tsTryParseExportDeclaration()),s||(s=t.prototype.parseExportDeclaration.call(this,e)),s&&i&&(s.declare=!0),s},s.parseClassId=function(e,s,i){if(s&&!i||!this.isContextual("implements")){t.prototype.parseClassId.apply(this,arguments);var r=this.tsTryParseTypeParameters();r&&(e.typeParameters=r)}},s.parseClassProperty=function(e){!e.optional&&this.eat(h.bang)&&(e.definite=!0);var s=this.tsTryParseTypeAnnotation();return s&&(e.typeAnnotation=s),t.prototype.parseClassProperty.call(this,e)},s.pushClassMethod=function(e,s,i,r,a){var n=this.tsTryParseTypeParameters();n&&(s.typeParameters=n),t.prototype.pushClassMethod.call(this,e,s,i,r,a)},s.pushClassPrivateMethod=function(e,s,i,r){var a=this.tsTryParseTypeParameters();a&&(s.typeParameters=a),t.prototype.pushClassPrivateMethod.call(this,e,s,i,r)},s.parseClassSuper=function(e){t.prototype.parseClassSuper.call(this,e),e.superClass&&this.isRelational("<")&&(e.superTypeParameters=this.tsParseTypeArguments()),this.eatContextual("implements")&&(e.implements=this.tsParseHeritageClause())},s.parseObjPropValue=function(e){var s;if(this.isRelational("<"))throw new Error("TODO");for(var i=arguments.length,r=new Array(i>1?i-1:0),a=1;a<i;a++)r[a-1]=arguments[a];(s=t.prototype.parseObjPropValue).call.apply(s,[this,e].concat(r))},s.parseFunctionParams=function(e,s){var i=this.tsTryParseTypeParameters();i&&(e.typeParameters=i),t.prototype.parseFunctionParams.call(this,e,s)},s.parseVarHead=function(e){t.prototype.parseVarHead.call(this,e),"Identifier"===e.id.type&&this.eat(h.bang)&&(e.definite=!0);var s=this.tsTryParseTypeAnnotation();s&&(e.id.typeAnnotation=s,this.finishNode(e.id,e.id.type))},s.parseAsyncArrowFromCallExpression=function(e,s){return this.match(h.colon)&&(e.returnType=this.tsParseTypeAnnotation()),t.prototype.parseAsyncArrowFromCallExpression.call(this,e,s)},s.parseMaybeAssign=function(){for(var e,s,i,r,a=arguments.length,n=new Array(a),o=0;o<a;o++)n[o]=arguments[o];if(this.match(h.jsxTagStart)){it(this.curContext()===D.j_oTag),it(this.state.context[this.state.context.length-2]===D.j_expr);var p=this.state.clone();try{var c;return(c=t.prototype.parseMaybeAssign).call.apply(c,[this].concat(n))}catch(t){if(!(t instanceof SyntaxError))throw t;this.state=p,it(this.curContext()===D.j_oTag),this.state.context.pop(),it(this.curContext()===D.j_expr),this.state.context.pop(),e=t}}if(void 0===e&&!this.isRelational("<"))return(s=t.prototype.parseMaybeAssign).call.apply(s,[this].concat(n));var l=this.state.clone();try{var u;r=this.tsParseTypeParameters(),"ArrowFunctionExpression"!==(i=(u=t.prototype.parseMaybeAssign).call.apply(u,[this].concat(n))).type&&this.unexpected()}catch(s){var d;if(!(s instanceof SyntaxError))throw s;if(e)throw e;return it(!this.hasPlugin("jsx")),this.state=l,(d=t.prototype.parseMaybeAssign).call.apply(d,[this].concat(n))}return r&&0!==r.params.length&&this.resetStartLocationFromNode(i,r.params[0]),i.typeParameters=r,i},s.parseMaybeUnary=function(e){return!this.hasPlugin("jsx")&&this.eatRelational("<")?this.tsParseTypeAssertion():t.prototype.parseMaybeUnary.call(this,e)},s.parseArrow=function(e){if(this.match(h.colon)){var s=this.state.clone();try{var i=this.tsParseTypeOrTypePredicateAnnotation(h.colon);this.canInsertSemicolon()&&this.unexpected(),this.match(h.arrow)||this.unexpected(),e.returnType=i}catch(t){if(!(t instanceof SyntaxError))throw t;this.state=s}}return t.prototype.parseArrow.call(this,e)},s.parseAssignableListItemTypes=function(t){if(this.eat(h.question)){if("Identifier"!==t.type)throw this.raise(t.start,"A binding pattern parameter cannot be optional in an implementation signature.");t.optional=!0}var e=this.tsTryParseTypeAnnotation();return e&&(t.typeAnnotation=e),this.finishNode(t,t.type)},s.toAssignable=function(e,s,i){switch(e.type){case"TSTypeCastExpression":return t.prototype.toAssignable.call(this,this.typeCastToParameter(e),s,i);case"TSParameterProperty":return t.prototype.toAssignable.call(this,e,s,i);case"TSAsExpression":case"TSNonNullExpression":case"TSTypeAssertion":return e.expression=this.toAssignable(e.expression,s,i),e;default:return t.prototype.toAssignable.call(this,e,s,i)}},s.checkLVal=function(e,s,i,r){switch(e.type){case"TSTypeCastExpression":return;case"TSParameterProperty":return void this.checkLVal(e.parameter,s,i,"parameter property");case"TSAsExpression":case"TSNonNullExpression":case"TSTypeAssertion":return void this.checkLVal(e.expression,s,i,r);default:return void t.prototype.checkLVal.call(this,e,s,i,r)}},s.parseBindingAtom=function(){switch(this.state.type){case h._this:return this.parseIdentifier(!0);default:return t.prototype.parseBindingAtom.call(this)}},s.isClassMethod=function(){return this.isRelational("<")||t.prototype.isClassMethod.call(this)},s.isClassProperty=function(){return this.match(h.bang)||this.match(h.colon)||t.prototype.isClassProperty.call(this)},s.parseMaybeDefault=function(){for(var e,s=arguments.length,i=new Array(s),r=0;r<s;r++)i[r]=arguments[r];var a=(e=t.prototype.parseMaybeDefault).call.apply(e,[this].concat(i));return"AssignmentPattern"===a.type&&a.typeAnnotation&&a.right.start<a.typeAnnotation.start&&this.raise(a.typeAnnotation.start,"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`"),a},s.readToken=function(e){return!this.state.inType||62!==e&&60!==e?t.prototype.readToken.call(this,e):this.finishOp(h.relational,1)},s.toAssignableList=function(e,s,i){for(var r=0;r<e.length;r++){var a=e[r];a&&"TSTypeCastExpression"===a.type&&(e[r]=this.typeCastToParameter(a))}return t.prototype.toAssignableList.call(this,e,s,i)},s.typeCastToParameter=function(t){return t.expression.typeAnnotation=t.typeAnnotation,this.finishNodeAt(t.expression,t.expression.type,t.typeAnnotation.end,t.typeAnnotation.loc.end)},s.toReferencedList=function(t){for(var e=0;e<t.length;e++){var s=t[e];s&&s._exprListItem&&"TsTypeCastExpression"===s.type&&this.raise(s.start,"Did not expect a type annotation here.")}return t},s.shouldParseArrow=function(){return this.match(h.colon)||t.prototype.shouldParseArrow.call(this)},s.shouldParseAsyncArrow=function(){return this.match(h.colon)||t.prototype.shouldParseAsyncArrow.call(this)},s.canHaveLeadingDecorator=function(){return t.prototype.canHaveLeadingDecorator.call(this)||this.isAbstractClass()},e}(t)}};function ot(t,e){var s=et;return t&&t.plugins&&(!function(t){if(rt(t,"decorators")&&rt(t,"decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");if(rt(t,"flow")&&rt(t,"typescript"))throw new Error("Cannot combine flow and typescript plugins.")}(t.plugins),s=function(t){var e=at.filter(function(e){return rt(t,e)}),s=e.join("/"),i=ht[s];if(!i){i=et;for(var r=0;r<e.length;r++){var a=e[r];i=nt[a](i)}ht[s]=i}return i}(t.plugins)),new s(t,e)}var ht={};e.parse=function(t,e){if(!e||"unambiguous"!==e.sourceType)return ot(e,t).parse();e=Object.assign({},e);try{e.sourceType="module";var s=ot(e,t),i=s.parse();return s.sawUnambiguousESM||(i.program.sourceType="script"),i}catch(s){try{return e.sourceType="script",ot(e,t).parse()}catch(t){}throw s}},e.parseExpression=function(t,e){var s=ot(e,t);return s.options.strictMode&&(s.state.strict=!0),s.getExpression()},e.tokTypes=h});e(l);var u=h;function d(e,s,i){var r,a=l,n={sourceType:"module",allowAwaitOutsideFunction:!0,allowImportExportEverywhere:!0,allowReturnOutsideFunction:!0,allowSuperOutsideMethod:!0,plugins:["jsx","flow","doExpressions","objectRestSpread","decorators-legacy","classProperties","exportDefaultFrom","exportNamespaceFrom","asyncGenerators","functionBind","functionSent","dynamicImport","numericSeparator","importMeta","optionalCatchBinding","optionalChaining","classPrivateProperties","pipelineOperator","nullishCoalescingOperator","bigInt","throwExpressions"]},o=!i||"json"!==i.parser&&"json5"!==i.parser?"parse":"parseExpression";try{r=a[o](e,n)}catch(s){try{r=a[o](e,Object.assign({},n,{strictMode:!1}))}catch(e){throw t(s.message.replace(/ \(.*\)/,""),{start:{line:s.loc.line,column:s.loc.column+1}})}}return delete r.tokens,r}function f(e,s){switch(e.type){case"ArrayExpression":return e.elements.forEach(i);case"ObjectExpression":return e.properties.forEach(i);case"ObjectProperty":if(e.computed)throw r("computed");if(e.shorthand)throw r("shorthand");return[e.key,e.value].forEach(i);case"UnaryExpression":switch(e.operator){case"+":case"-":return i(e.argument);default:throw r("operator")}case"Identifier":if(s&&"ObjectProperty"===s.type&&s.key===e)return;throw r();case"NullLiteral":case"BooleanLiteral":case"NumericLiteral":case"StringLiteral":return;default:throw r()}function i(t){return f(t,e)}function r(s){var i=s?"".concat(e.type," with ").concat(s,"=").concat(JSON.stringify(e[s])):e.type;return t("".concat(i," is not allowed in JSON."),{start:{line:e.loc.start.line,column:e.loc.start.column+1}})}}var m=Object.assign({parse:d,astFormat:"estree",hasPragma:u},c);return{parsers:{babylon:m,json:Object.assign({},m,{hasPragma:function(){return!0}}),json5:m,"json-stringify":Object.assign({parse:function(t,e,s){var i=d(t,0,Object.assign({},s,{parser:"json"}));return i.comments.forEach(f),f(i),i},astFormat:"estree-json"},c)}}}); diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/standalone.js.js b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/standalone.js.js deleted file mode 100644 index ad6a732eca..0000000000 --- a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/standalone.js.js +++ /dev/null @@ -1,20786 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.prettier = factory()); -}(this, (function () { 'use strict'; - -var name = "prettier"; -var version$1 = "1.14.0"; -var description = "Prettier is an opinionated code formatter"; -var bin = { - "prettier": "./bin/prettier.js" -}; -var repository = "prettier/prettier"; -var homepage = "https://prettier.io"; -var author = "James Long"; -var license = "MIT"; -var main = "./index.js"; -var engines = { - "node": ">=6" -}; -var dependencies = { - "@babel/code-frame": "7.0.0-beta.46", - "@babel/parser": "7.0.0-beta.49", - "@glimmer/syntax": "0.30.3", - "camelcase": "4.1.0", - "chalk": "2.1.0", - "cjk-regex": "1.0.2", - "cosmiconfig": "3.1.0", - "dashify": "0.2.2", - "dedent": "0.7.0", - "diff": "3.2.0", - "editorconfig": "0.15.0", - "editorconfig-to-prettier": "0.0.6", - "emoji-regex": "6.5.1", - "escape-string-regexp": "1.0.5", - "esutils": "2.0.2", - "find-parent-dir": "0.3.0", - "find-project-root": "1.1.1", - "flow-parser": "0.75.0", - "get-stream": "3.0.0", - "globby": "6.1.0", - "graphql": "0.13.2", - "html-tag-names": "1.1.2", - "ignore": "3.3.7", - "jest-docblock": "23.2.0", - "json-stable-stringify": "1.0.1", - "leven": "2.1.0", - "linguist-languages": "6.2.1-dev.20180706", - "lodash.uniqby": "4.7.0", - "mem": "1.1.0", - "minimatch": "3.0.4", - "minimist": "1.2.0", - "normalize-path": "3.0.0", - "parse5": "3.0.3", - "postcss-less": "1.1.5", - "postcss-media-query-parser": "0.2.3", - "postcss-scss": "1.0.6", - "postcss-selector-parser": "2.2.3", - "postcss-values-parser": "1.5.0", - "remark-parse": "5.0.0", - "resolve": "1.5.0", - "semver": "5.4.1", - "string-width": "2.1.1", - "typescript": "3.0.0-dev.20180626", - "typescript-eslint-parser": "17.0.0", - "unicode-regex": "1.0.1", - "unified": "6.1.6", - "yaml": "1.0.0-rc.7", - "yaml-unist-parser": "1.0.0-rc.2" -}; -var devDependencies = { - "@babel/cli": "7.0.0-beta.49", - "@babel/core": "7.0.0-beta.49", - "@babel/preset-env": "7.0.0-beta.49", - "babel-loader": "8.0.0-beta.3", - "benchmark": "2.1.4", - "builtin-modules": "2.0.0", - "codecov": "2.2.0", - "cross-env": "5.0.5", - "eslint": "4.18.2", - "eslint-config-prettier": "2.9.0", - "eslint-friendly-formatter": "3.0.0", - "eslint-plugin-import": "2.9.0", - "eslint-plugin-prettier": "2.6.0", - "eslint-plugin-react": "7.7.0", - "execa": "0.10.0", - "jest": "23.3.0", - "jest-junit": "5.0.0", - "jest-watch-typeahead": "0.1.0", - "mkdirp": "0.5.1", - "prettier": "1.13.7", - "prettylint": "1.0.0", - "rimraf": "2.6.2", - "rollup": "0.47.6", - "rollup-plugin-alias": "1.4.0", - "rollup-plugin-babel": "4.0.0-beta.4", - "rollup-plugin-commonjs": "8.2.6", - "rollup-plugin-json": "2.1.1", - "rollup-plugin-node-builtins": "2.0.0", - "rollup-plugin-node-globals": "1.1.0", - "rollup-plugin-node-resolve": "2.0.0", - "rollup-plugin-replace": "1.2.1", - "rollup-plugin-uglify": "3.0.0", - "shelljs": "0.8.1", - "snapshot-diff": "0.4.0", - "strip-ansi": "4.0.0", - "tempy": "0.2.1", - "webpack": "3.12.0" -}; -var resolutions = { - "@babel/code-frame": "7.0.0-beta.46" -}; -var scripts = { - "prepublishOnly": "echo \"Error: must publish from dist/\" && exit 1", - "prepare-release": "yarn && yarn build && yarn test:dist", - "test": "jest", - "test:dist": "node ./scripts/test-dist.js", - "test-integration": "jest tests_integration", - "perf-repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", - "perf-repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", - "perf-benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", - "lint": "cross-env EFF_NO_LINK_RULES=true eslint . --format node_modules/eslint-friendly-formatter", - "lint-docs": "prettylint {.,docs,website,website/blog}/*.md", - "build": "node ./scripts/build/build.js", - "build-docs": "node ./scripts/build-docs.js", - "check-deps": "node ./scripts/check-deps.js" -}; -var _package = { - name: name, - version: version$1, - description: description, - bin: bin, - repository: repository, - homepage: homepage, - author: author, - license: license, - main: main, - engines: engines, - dependencies: dependencies, - devDependencies: devDependencies, - resolutions: resolutions, - scripts: scripts -}; - -var _package$1 = Object.freeze({ - name: name, - version: version$1, - description: description, - bin: bin, - repository: repository, - homepage: homepage, - author: author, - license: license, - main: main, - engines: engines, - dependencies: dependencies, - devDependencies: devDependencies, - resolutions: resolutions, - scripts: scripts, - default: _package -}); - -var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - - -function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; -} - -var base = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports['default'] = - /*istanbul ignore end*/ - Diff; - - function Diff() {} - - Diff.prototype = { - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - diff: function diff(oldString, newString) { - /*istanbul ignore start*/ - var - /*istanbul ignore end*/ - options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; - var callback = options.callback; - - if (typeof options === 'function') { - callback = options; - options = {}; - } - - this.options = options; - var self = this; - - function done(value) { - if (callback) { - setTimeout(function () { - callback(undefined, value); - }, 0); - return true; - } else { - return value; - } - } // Allow subclasses to massage the input prior to running - - - oldString = this.castInput(oldString); - newString = this.castInput(newString); - oldString = this.removeEmpty(this.tokenize(oldString)); - newString = this.removeEmpty(this.tokenize(newString)); - var newLen = newString.length, - oldLen = oldString.length; - var editLength = 1; - var maxEditLength = newLen + oldLen; - var bestPath = [{ - newPos: -1, - components: [] - }]; // Seed editLength = 0, i.e. the content starts with the same values - - var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); - - if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { - // Identity per the equality and tokenizer - return done([{ - value: this.join(newString), - count: newString.length - }]); - } // Main worker method. checks all permutations of a given edit length for acceptance. - - - function execEditLength() { - for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { - var basePath = - /*istanbul ignore start*/ - void 0; - - var addPath = bestPath[diagonalPath - 1], - removePath = bestPath[diagonalPath + 1], - _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; - - if (addPath) { - // No one else is going to attempt to use this value, clear it - bestPath[diagonalPath - 1] = undefined; - } - - var canAdd = addPath && addPath.newPos + 1 < newLen, - canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; - - if (!canAdd && !canRemove) { - // If this path is a terminal then prune - bestPath[diagonalPath] = undefined; - continue; - } // Select the diagonal that we want to branch from. We select the prior - // path whose position in the new string is the farthest from the origin - // and does not pass the bounds of the diff graph - - - if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { - basePath = clonePath(removePath); - self.pushComponent(basePath.components, undefined, true); - } else { - basePath = addPath; // No need to clone, we've pulled it from the list - - basePath.newPos++; - self.pushComponent(basePath.components, true, undefined); - } - - _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done - - if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { - return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); - } else { - // Otherwise track this path as a potential candidate and continue. - bestPath[diagonalPath] = basePath; - } - } - - editLength++; - } // Performs the length of edit iteration. Is a bit fugly as this has to support the - // sync and async mode which is never fun. Loops over execEditLength until a value - // is produced. - - - if (callback) { - (function exec() { - setTimeout(function () { - // This should not happen, but we want to be safe. - - /* istanbul ignore next */ - if (editLength > maxEditLength) { - return callback(); - } - - if (!execEditLength()) { - exec(); - } - }, 0); - })(); - } else { - while (editLength <= maxEditLength) { - var ret = execEditLength(); - - if (ret) { - return ret; - } - } - } - }, - - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - pushComponent: function pushComponent(components, added, removed) { - var last = components[components.length - 1]; - - if (last && last.added === added && last.removed === removed) { - // We need to clone here as the component clone operation is just - // as shallow array clone - components[components.length - 1] = { - count: last.count + 1, - added: added, - removed: removed - }; - } else { - components.push({ - count: 1, - added: added, - removed: removed - }); - } - }, - - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { - var newLen = newString.length, - oldLen = oldString.length, - newPos = basePath.newPos, - oldPos = newPos - diagonalPath, - commonCount = 0; - - while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { - newPos++; - oldPos++; - commonCount++; - } - - if (commonCount) { - basePath.components.push({ - count: commonCount - }); - } - - basePath.newPos = newPos; - return oldPos; - }, - - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - equals: function equals(left, right) { - return left === right; - }, - - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - removeEmpty: function removeEmpty(array) { - var ret = []; - - for (var i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } - } - - return ret; - }, - - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - castInput: function castInput(value) { - return value; - }, - - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - tokenize: function tokenize(value) { - return value.split(''); - }, - - /*istanbul ignore start*/ - - /*istanbul ignore end*/ - join: function join(chars) { - return chars.join(''); - } - }; - - function buildValues(diff, components, newString, oldString, useLongestToken) { - var componentPos = 0, - componentLen = components.length, - newPos = 0, - oldPos = 0; - - for (; componentPos < componentLen; componentPos++) { - var component = components[componentPos]; - - if (!component.removed) { - if (!component.added && useLongestToken) { - var value = newString.slice(newPos, newPos + component.count); - value = value.map(function (value, i) { - var oldValue = oldString[oldPos + i]; - return oldValue.length > value.length ? oldValue : value; - }); - component.value = diff.join(value); - } else { - component.value = diff.join(newString.slice(newPos, newPos + component.count)); - } - - newPos += component.count; // Common case - - if (!component.added) { - oldPos += component.count; - } - } else { - component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); - oldPos += component.count; // Reverse add and remove so removes are output first to match common convention - // The diffing algorithm is tied to add then remove output and this is the simplest - // route to get the desired output with minimal overhead. - - if (componentPos && components[componentPos - 1].added) { - var tmp = components[componentPos - 1]; - components[componentPos - 1] = components[componentPos]; - components[componentPos] = tmp; - } - } - } // Special case handle for when one terminal is ignored. For this case we merge the - // terminal into the prior string and drop the change. - - - var lastComponent = components[componentLen - 1]; - - if (componentLen > 1 && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { - components[componentLen - 2].value += lastComponent.value; - components.pop(); - } - - return components; - } - - function clonePath(path) { - return { - newPos: path.newPos, - components: path.components.slice(0) - }; - } -}); -unwrapExports(base); - -var character = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports.characterDiff = undefined; - exports. - /*istanbul ignore end*/ - diffChars = diffChars; - /*istanbul ignore start*/ - - var _base2 = _interopRequireDefault(base); - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - 'default': obj - }; - } - /*istanbul ignore end*/ - - - var characterDiff = - /*istanbul ignore start*/ - exports. - /*istanbul ignore end*/ - characterDiff = new - /*istanbul ignore start*/ - _base2['default'](); - - function diffChars(oldStr, newStr, callback) { - return characterDiff.diff(oldStr, newStr, callback); - } -}); -unwrapExports(character); - -var params = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports. - /*istanbul ignore end*/ - generateOptions = generateOptions; - - function generateOptions(options, defaults) { - if (typeof options === 'function') { - defaults.callback = options; - } else if (options) { - for (var name in options) { - /* istanbul ignore else */ - if (options.hasOwnProperty(name)) { - defaults[name] = options[name]; - } - } - } - - return defaults; - } -}); -unwrapExports(params); - -var word = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports.wordDiff = undefined; - exports. - /*istanbul ignore end*/ - diffWords = diffWords; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffWordsWithSpace = diffWordsWithSpace; - /*istanbul ignore start*/ - - var _base2 = _interopRequireDefault(base); - /*istanbul ignore end*/ - - /*istanbul ignore start*/ - - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - 'default': obj - }; - } - /*istanbul ignore end*/ - // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode - // - // Ranges and exceptions: - // Latin-1 Supplement, 0080–00FF - // - U+00D7 × Multiplication sign - // - U+00F7 ÷ Division sign - // Latin Extended-A, 0100–017F - // Latin Extended-B, 0180–024F - // IPA Extensions, 0250–02AF - // Spacing Modifier Letters, 02B0–02FF - // - U+02C7 ˇ ˇ Caron - // - U+02D8 ˘ ˘ Breve - // - U+02D9 Ë™ ˙ Dot Above - // - U+02DA Ëš ˚ Ring Above - // - U+02DB Ë› ˛ Ogonek - // - U+02DC Ëœ ˜ Small Tilde - // - U+02DD Ë ˝ Double Acute Accent - // Latin Extended Additional, 1E00–1EFF - - - var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; - var reWhitespace = /\S/; - var wordDiff = - /*istanbul ignore start*/ - exports. - /*istanbul ignore end*/ - wordDiff = new - /*istanbul ignore start*/ - _base2['default'](); - - wordDiff.equals = function (left, right) { - return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); - }; - - wordDiff.tokenize = function (value) { - var tokens = value.split(/(\s+|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. - - for (var i = 0; i < tokens.length - 1; i++) { - // If we have an empty string in the next field and we have only word chars before and after, merge - if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { - tokens[i] += tokens[i + 2]; - tokens.splice(i + 1, 2); - i--; - } - } - - return tokens; - }; - - function diffWords(oldStr, newStr, callback) { - var options = - /*istanbul ignore start*/ - (0, params.generateOptions - /*istanbul ignore end*/ - )(callback, { - ignoreWhitespace: true - }); - return wordDiff.diff(oldStr, newStr, options); - } - - function diffWordsWithSpace(oldStr, newStr, callback) { - return wordDiff.diff(oldStr, newStr, callback); - } -}); -unwrapExports(word); - -var line = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports.lineDiff = undefined; - exports. - /*istanbul ignore end*/ - diffLines = diffLines; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffTrimmedLines = diffTrimmedLines; - /*istanbul ignore start*/ - - var _base2 = _interopRequireDefault(base); - /*istanbul ignore end*/ - - /*istanbul ignore start*/ - - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - 'default': obj - }; - } - /*istanbul ignore end*/ - - - var lineDiff = - /*istanbul ignore start*/ - exports. - /*istanbul ignore end*/ - lineDiff = new - /*istanbul ignore start*/ - _base2['default'](); - - lineDiff.tokenize = function (value) { - var retLines = [], - linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line - - if (!linesAndNewlines[linesAndNewlines.length - 1]) { - linesAndNewlines.pop(); - } // Merge the content and line separators into single tokens - - - for (var i = 0; i < linesAndNewlines.length; i++) { - var line = linesAndNewlines[i]; - - if (i % 2 && !this.options.newlineIsToken) { - retLines[retLines.length - 1] += line; - } else { - if (this.options.ignoreWhitespace) { - line = line.trim(); - } - - retLines.push(line); - } - } - - return retLines; - }; - - function diffLines(oldStr, newStr, callback) { - return lineDiff.diff(oldStr, newStr, callback); - } - - function diffTrimmedLines(oldStr, newStr, callback) { - var options = - /*istanbul ignore start*/ - (0, params.generateOptions - /*istanbul ignore end*/ - )(callback, { - ignoreWhitespace: true - }); - return lineDiff.diff(oldStr, newStr, options); - } -}); -unwrapExports(line); - -var sentence = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports.sentenceDiff = undefined; - exports. - /*istanbul ignore end*/ - diffSentences = diffSentences; - /*istanbul ignore start*/ - - var _base2 = _interopRequireDefault(base); - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - 'default': obj - }; - } - /*istanbul ignore end*/ - - - var sentenceDiff = - /*istanbul ignore start*/ - exports. - /*istanbul ignore end*/ - sentenceDiff = new - /*istanbul ignore start*/ - _base2['default'](); - - sentenceDiff.tokenize = function (value) { - return value.split(/(\S.+?[.!?])(?=\s+|$)/); - }; - - function diffSentences(oldStr, newStr, callback) { - return sentenceDiff.diff(oldStr, newStr, callback); - } -}); -unwrapExports(sentence); - -var css = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports.cssDiff = undefined; - exports. - /*istanbul ignore end*/ - diffCss = diffCss; - /*istanbul ignore start*/ - - var _base2 = _interopRequireDefault(base); - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - 'default': obj - }; - } - /*istanbul ignore end*/ - - - var cssDiff = - /*istanbul ignore start*/ - exports. - /*istanbul ignore end*/ - cssDiff = new - /*istanbul ignore start*/ - _base2['default'](); - - cssDiff.tokenize = function (value) { - return value.split(/([{}:;,]|\s+)/); - }; - - function diffCss(oldStr, newStr, callback) { - return cssDiff.diff(oldStr, newStr, callback); - } -}); -unwrapExports(css); - -function _typeof(obj) { - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); -} - -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); -} - -function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); -} - -function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); -} - -function isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } -} - -function _construct(Parent, args, Class) { - if (isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - - return _construct.apply(null, arguments); -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null) return null; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; -} - -function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } - - return _assertThisInitialized(self); -} - -function _taggedTemplateLiteral(strings, raw) { - if (!raw) { - raw = strings.slice(0); - } - - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); -} - -function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; -} - -function _iterableToArrayLimit(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; -} - -function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); -} - -var json = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports.jsonDiff = undefined; - - var _typeof$$1 = typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol" ? function (obj) { - return _typeof(obj); - } : function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : _typeof(obj); - }; - - exports. - /*istanbul ignore end*/ - diffJson = diffJson; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - canonicalize = canonicalize; - /*istanbul ignore start*/ - - var _base2 = _interopRequireDefault$$1(base); - /*istanbul ignore end*/ - - /*istanbul ignore start*/ - - - function _interopRequireDefault$$1(obj) { - return obj && obj.__esModule ? obj : { - 'default': obj - }; - } - /*istanbul ignore end*/ - - - var objectPrototypeToString = Object.prototype.toString; - var jsonDiff = - /*istanbul ignore start*/ - exports. - /*istanbul ignore end*/ - jsonDiff = new - /*istanbul ignore start*/ - _base2['default'](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a - // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: - - jsonDiff.useLongestToken = true; - jsonDiff.tokenize = - /*istanbul ignore start*/ - line.lineDiff. - /*istanbul ignore end*/ - tokenize; - - jsonDiff.castInput = function (value) { - /*istanbul ignore start*/ - var - /*istanbul ignore end*/ - undefinedReplacement = this.options.undefinedReplacement; - return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), function (k, v) { - if (typeof v === 'undefined') { - return undefinedReplacement; - } - - return v; - }, ' '); - }; - - jsonDiff.equals = function (left, right) { - return ( - /*istanbul ignore start*/ - _base2['default']. - /*istanbul ignore end*/ - prototype.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) - ); - }; - - function diffJson(oldObj, newObj, options) { - return jsonDiff.diff(oldObj, newObj, options); - } // This function handles the presence of circular references by bailing out when encountering an - // object that is already on the "stack" of items being processed. - - - function canonicalize(obj, stack, replacementStack) { - stack = stack || []; - replacementStack = replacementStack || []; - var i = - /*istanbul ignore start*/ - void 0; - - for (i = 0; i < stack.length; i += 1) { - if (stack[i] === obj) { - return replacementStack[i]; - } - } - - var canonicalizedObj = - /*istanbul ignore start*/ - void 0; - - if ('[object Array]' === objectPrototypeToString.call(obj)) { - stack.push(obj); - canonicalizedObj = new Array(obj.length); - replacementStack.push(canonicalizedObj); - - for (i = 0; i < obj.length; i += 1) { - canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack); - } - - stack.pop(); - replacementStack.pop(); - return canonicalizedObj; - } - - if (obj && obj.toJSON) { - obj = obj.toJSON(); - } - - if ( - /*istanbul ignore start*/ - (typeof - /*istanbul ignore end*/ - obj === 'undefined' ? 'undefined' : _typeof$$1(obj)) === 'object' && obj !== null) { - stack.push(obj); - canonicalizedObj = {}; - replacementStack.push(canonicalizedObj); - var sortedKeys = [], - key = - /*istanbul ignore start*/ - void 0; - - for (key in obj) { - /* istanbul ignore else */ - if (obj.hasOwnProperty(key)) { - sortedKeys.push(key); - } - } - - sortedKeys.sort(); - - for (i = 0; i < sortedKeys.length; i += 1) { - key = sortedKeys[i]; - canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack); - } - - stack.pop(); - replacementStack.pop(); - } else { - canonicalizedObj = obj; - } - - return canonicalizedObj; - } -}); -unwrapExports(json); - -var array = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports.arrayDiff = undefined; - exports. - /*istanbul ignore end*/ - diffArrays = diffArrays; - /*istanbul ignore start*/ - - var _base2 = _interopRequireDefault(base); - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - 'default': obj - }; - } - /*istanbul ignore end*/ - - - var arrayDiff = - /*istanbul ignore start*/ - exports. - /*istanbul ignore end*/ - arrayDiff = new - /*istanbul ignore start*/ - _base2['default'](); - - arrayDiff.tokenize = arrayDiff.join = function (value) { - return value.slice(); - }; - - function diffArrays(oldArr, newArr, callback) { - return arrayDiff.diff(oldArr, newArr, callback); - } -}); -unwrapExports(array); - -var parse = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports. - /*istanbul ignore end*/ - parsePatch = parsePatch; - - function parsePatch(uniDiff) { - /*istanbul ignore start*/ - var - /*istanbul ignore end*/ - options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], - list = [], - i = 0; - - function parseIndex() { - var index = {}; - list.push(index); // Parse diff metadata - - while (i < diffstr.length) { - var line = diffstr[i]; // File header found, end parsing diff metadata - - if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { - break; - } // Diff index - - - var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); - - if (header) { - index.index = header[1]; - } - - i++; - } // Parse file headers if they are defined. Unified diff requires them, but - // there's no technical issues to have an isolated hunk without file header - - - parseFileHeader(index); - parseFileHeader(index); // Parse hunks - - index.hunks = []; - - while (i < diffstr.length) { - var _line = diffstr[i]; - - if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { - break; - } else if (/^@@/.test(_line)) { - index.hunks.push(parseHunk()); - } else if (_line && options.strict) { - // Ignore unexpected content unless in strict mode - throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); - } else { - i++; - } - } - } // Parses the --- and +++ headers, if none are found, no lines - // are consumed. - - - function parseFileHeader(index) { - var headerPattern = /^(---|\+\+\+)\s+([\S ]*)(?:\t(.*?)\s*)?$/; - var fileHeader = headerPattern.exec(diffstr[i]); - - if (fileHeader) { - var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; - index[keyPrefix + 'FileName'] = fileHeader[2]; - index[keyPrefix + 'Header'] = fileHeader[3]; - i++; - } - } // Parses a hunk - // This assumes that we are at the start of a hunk. - - - function parseHunk() { - var chunkHeaderIndex = i, - chunkHeaderLine = diffstr[i++], - chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); - var hunk = { - oldStart: +chunkHeader[1], - oldLines: +chunkHeader[2] || 1, - newStart: +chunkHeader[3], - newLines: +chunkHeader[4] || 1, - lines: [], - linedelimiters: [] - }; - var addCount = 0, - removeCount = 0; - - for (; i < diffstr.length; i++) { - // Lines starting with '---' could be mistaken for the "remove line" operation - // But they could be the header for the next file. Therefore prune such cases out. - if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { - break; - } - - var operation = diffstr[i][0]; - - if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { - hunk.lines.push(diffstr[i]); - hunk.linedelimiters.push(delimiters[i] || '\n'); - - if (operation === '+') { - addCount++; - } else if (operation === '-') { - removeCount++; - } else if (operation === ' ') { - addCount++; - removeCount++; - } - } else { - break; - } - } // Handle the empty block count case - - - if (!addCount && hunk.newLines === 1) { - hunk.newLines = 0; - } - - if (!removeCount && hunk.oldLines === 1) { - hunk.oldLines = 0; - } // Perform optional sanity checking - - - if (options.strict) { - if (addCount !== hunk.newLines) { - throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); - } - - if (removeCount !== hunk.oldLines) { - throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); - } - } - - return hunk; - } - - while (i < diffstr.length) { - parseIndex(); - } - - return list; - } -}); -unwrapExports(parse); - -var distanceIterator = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - "use strict"; - - exports.__esModule = true; - - exports["default"] = - /*istanbul ignore end*/ - function (start, minLine, maxLine) { - var wantForward = true, - backwardExhausted = false, - forwardExhausted = false, - localOffset = 1; - return function iterator() { - if (wantForward && !forwardExhausted) { - if (backwardExhausted) { - localOffset++; - } else { - wantForward = false; - } // Check if trying to fit beyond text length, and if not, check it fits - // after offset location (or desired location on first iteration) - - - if (start + localOffset <= maxLine) { - return localOffset; - } - - forwardExhausted = true; - } - - if (!backwardExhausted) { - if (!forwardExhausted) { - wantForward = true; - } // Check if trying to fit before text beginning, and if not, check it fits - // before offset location - - - if (minLine <= start - localOffset) { - return -localOffset++; - } - - backwardExhausted = true; - return iterator(); - } // We tried to fit hunk before text beginning and beyond text lenght, then - // hunk can't fit on the text. Return undefined - - }; - }; -}); -unwrapExports(distanceIterator); - -var apply = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports. - /*istanbul ignore end*/ - applyPatch = applyPatch; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - applyPatches = applyPatches; - /*istanbul ignore start*/ - - var _distanceIterator2 = _interopRequireDefault(distanceIterator); - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - 'default': obj - }; - } - /*istanbul ignore end*/ - - - function applyPatch(source, uniDiff) { - /*istanbul ignore start*/ - var - /*istanbul ignore end*/ - options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; - - if (typeof uniDiff === 'string') { - uniDiff = - /*istanbul ignore start*/ - (0, parse.parsePatch - /*istanbul ignore end*/ - )(uniDiff); - } - - if (Array.isArray(uniDiff)) { - if (uniDiff.length > 1) { - throw new Error('applyPatch only works with a single input.'); - } - - uniDiff = uniDiff[0]; - } // Apply the diff to the input - - - var lines = source.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], - hunks = uniDiff.hunks, - compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) - /*istanbul ignore start*/ - { - return ( - /*istanbul ignore end*/ - line === patchContent - ); - }, - errorCount = 0, - fuzzFactor = options.fuzzFactor || 0, - minLine = 0, - offset = 0, - removeEOFNL = - /*istanbul ignore start*/ - void 0 - /*istanbul ignore end*/ - , - addEOFNL = - /*istanbul ignore start*/ - void 0; - /** - * Checks if the hunk exactly fits on the provided location - */ - - - function hunkFits(hunk, toPos) { - for (var j = 0; j < hunk.lines.length; j++) { - var line = hunk.lines[j], - operation = line[0], - content = line.substr(1); - - if (operation === ' ' || operation === '-') { - // Context sanity check - if (!compareLine(toPos + 1, lines[toPos], operation, content)) { - errorCount++; - - if (errorCount > fuzzFactor) { - return false; - } - } - - toPos++; - } - } - - return true; - } // Search best fit offsets for each hunk based on the previous ones - - - for (var i = 0; i < hunks.length; i++) { - var hunk = hunks[i], - maxLine = lines.length - hunk.oldLines, - localOffset = 0, - toPos = offset + hunk.oldStart - 1; - var iterator = - /*istanbul ignore start*/ - (0, _distanceIterator2['default'] - /*istanbul ignore end*/ - )(toPos, minLine, maxLine); - - for (; localOffset !== undefined; localOffset = iterator()) { - if (hunkFits(hunk, toPos + localOffset)) { - hunk.offset = offset += localOffset; - break; - } - } - - if (localOffset === undefined) { - return false; - } // Set lower text limit to end of the current hunk, so next ones don't try - // to fit over already patched text - - - minLine = hunk.offset + hunk.oldStart + hunk.oldLines; - } // Apply patch hunks - - - for (var _i = 0; _i < hunks.length; _i++) { - var _hunk = hunks[_i], - _toPos = _hunk.offset + _hunk.newStart - 1; - - if (_hunk.newLines == 0) { - _toPos++; - } - - for (var j = 0; j < _hunk.lines.length; j++) { - var line = _hunk.lines[j], - operation = line[0], - content = line.substr(1), - delimiter = _hunk.linedelimiters[j]; - - if (operation === ' ') { - _toPos++; - } else if (operation === '-') { - lines.splice(_toPos, 1); - delimiters.splice(_toPos, 1); - /* istanbul ignore else */ - } else if (operation === '+') { - lines.splice(_toPos, 0, content); - delimiters.splice(_toPos, 0, delimiter); - _toPos++; - } else if (operation === '\\') { - var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; - - if (previousOperation === '+') { - removeEOFNL = true; - } else if (previousOperation === '-') { - addEOFNL = true; - } - } - } - } // Handle EOFNL insertion/removal - - - if (removeEOFNL) { - while (!lines[lines.length - 1]) { - lines.pop(); - delimiters.pop(); - } - } else if (addEOFNL) { - lines.push(''); - delimiters.push('\n'); - } - - for (var _k = 0; _k < lines.length - 1; _k++) { - lines[_k] = lines[_k] + delimiters[_k]; - } - - return lines.join(''); - } // Wrapper that supports multiple file patches via callbacks. - - - function applyPatches(uniDiff, options) { - if (typeof uniDiff === 'string') { - uniDiff = - /*istanbul ignore start*/ - (0, parse.parsePatch - /*istanbul ignore end*/ - )(uniDiff); - } - - var currentIndex = 0; - - function processIndex() { - var index = uniDiff[currentIndex++]; - - if (!index) { - return options.complete(); - } - - options.loadFile(index, function (err, data) { - if (err) { - return options.complete(err); - } - - var updatedContent = applyPatch(data, index, options); - options.patched(index, updatedContent, function (err) { - if (err) { - return options.complete(err); - } - - processIndex(); - }); - }); - } - - processIndex(); - } -}); -unwrapExports(apply); - -var create = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports. - /*istanbul ignore end*/ - structuredPatch = structuredPatch; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - createTwoFilesPatch = createTwoFilesPatch; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - createPatch = createPatch; - /*istanbul ignore start*/ - - function _toConsumableArray(arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { - arr2[i] = arr[i]; - } - - return arr2; - } else { - return Array.from(arr); - } - } - /*istanbul ignore end*/ - - - function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - if (!options) { - options = {}; - } - - if (typeof options.context === 'undefined') { - options.context = 4; - } - - var diff = - /*istanbul ignore start*/ - (0, line.diffLines - /*istanbul ignore end*/ - )(oldStr, newStr, options); - diff.push({ - value: '', - lines: [] - }); // Append an empty value to make cleanup easier - - function contextLines(lines) { - return lines.map(function (entry) { - return ' ' + entry; - }); - } - - var hunks = []; - var oldRangeStart = 0, - newRangeStart = 0, - curRange = [], - oldLine = 1, - newLine = 1; - /*istanbul ignore start*/ - - var _loop = function _loop( - /*istanbul ignore end*/ - i) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - current.lines = lines; - - if (current.added || current.removed) { - /*istanbul ignore start*/ - var _curRange; - /*istanbul ignore end*/ - // If we have previous context, start with that - - - if (!oldRangeStart) { - var prev = diff[i - 1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - - if (prev) { - curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } // Output our changes - - /*istanbul ignore start*/ - - - (_curRange = - /*istanbul ignore end*/ - curRange).push. - /*istanbul ignore start*/ - apply - /*istanbul ignore end*/ - ( - /*istanbul ignore start*/ - _curRange - /*istanbul ignore end*/ - , - /*istanbul ignore start*/ - _toConsumableArray( - /*istanbul ignore end*/ - lines.map(function (entry) { - return (current.added ? '+' : '-') + entry; - }))); // Track the updated file position - - - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - // Identical context lines. Track line changes - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= options.context * 2 && i < diff.length - 2) { - /*istanbul ignore start*/ - var _curRange2; - /*istanbul ignore end*/ - // Overlapping - - /*istanbul ignore start*/ - - - (_curRange2 = - /*istanbul ignore end*/ - curRange).push. - /*istanbul ignore start*/ - apply - /*istanbul ignore end*/ - ( - /*istanbul ignore start*/ - _curRange2 - /*istanbul ignore end*/ - , - /*istanbul ignore start*/ - _toConsumableArray( - /*istanbul ignore end*/ - contextLines(lines))); - } else { - /*istanbul ignore start*/ - var _curRange3; - /*istanbul ignore end*/ - // end the range and output - - - var contextSize = Math.min(lines.length, options.context); - /*istanbul ignore start*/ - - (_curRange3 = - /*istanbul ignore end*/ - curRange).push. - /*istanbul ignore start*/ - apply - /*istanbul ignore end*/ - ( - /*istanbul ignore start*/ - _curRange3 - /*istanbul ignore end*/ - , - /*istanbul ignore start*/ - _toConsumableArray( - /*istanbul ignore end*/ - contextLines(lines.slice(0, contextSize)))); - - var hunk = { - oldStart: oldRangeStart, - oldLines: oldLine - oldRangeStart + contextSize, - newStart: newRangeStart, - newLines: newLine - newRangeStart + contextSize, - lines: curRange - }; - - if (i >= diff.length - 2 && lines.length <= options.context) { - // EOF is inside this hunk - var oldEOFNewline = /\n$/.test(oldStr); - var newEOFNewline = /\n$/.test(newStr); - - if (lines.length == 0 && !oldEOFNewline) { - // special case: old has no eol and no trailing context; no-nl can end up before adds - curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); - } else if (!oldEOFNewline || !newEOFNewline) { - curRange.push('\\ No newline at end of file'); - } - } - - hunks.push(hunk); - oldRangeStart = 0; - newRangeStart = 0; - curRange = []; - } - } - - oldLine += lines.length; - newLine += lines.length; - } - }; - - for (var i = 0; i < diff.length; i++) { - /*istanbul ignore start*/ - _loop( - /*istanbul ignore end*/ - i); - } - - return { - oldFileName: oldFileName, - newFileName: newFileName, - oldHeader: oldHeader, - newHeader: newHeader, - hunks: hunks - }; - } - - function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); - var ret = []; - - if (oldFileName == newFileName) { - ret.push('Index: ' + oldFileName); - } - - ret.push('==================================================================='); - ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); - ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); - - for (var i = 0; i < diff.hunks.length; i++) { - var hunk = diff.hunks[i]; - ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); - ret.push.apply(ret, hunk.lines); - } - - return ret.join('\n') + '\n'; - } - - function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { - return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); - } -}); -unwrapExports(create); - -var dmp = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - "use strict"; - - exports.__esModule = true; - exports. - /*istanbul ignore end*/ - convertChangesToDMP = convertChangesToDMP; // See: http://code.google.com/p/google-diff-match-patch/wiki/API - - function convertChangesToDMP(changes) { - var ret = [], - change = - /*istanbul ignore start*/ - void 0 - /*istanbul ignore end*/ - , - operation = - /*istanbul ignore start*/ - void 0; - - for (var i = 0; i < changes.length; i++) { - change = changes[i]; - - if (change.added) { - operation = 1; - } else if (change.removed) { - operation = -1; - } else { - operation = 0; - } - - ret.push([operation, change.value]); - } - - return ret; - } -}); -unwrapExports(dmp); - -var xml = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports. - /*istanbul ignore end*/ - convertChangesToXML = convertChangesToXML; - - function convertChangesToXML(changes) { - var ret = []; - - for (var i = 0; i < changes.length; i++) { - var change = changes[i]; - - if (change.added) { - ret.push('<ins>'); - } else if (change.removed) { - ret.push('<del>'); - } - - ret.push(escapeHTML(change.value)); - - if (change.added) { - ret.push('</ins>'); - } else if (change.removed) { - ret.push('</del>'); - } - } - - return ret.join(''); - } - - function escapeHTML(s) { - var n = s; - n = n.replace(/&/g, '&'); - n = n.replace(/</g, '<'); - n = n.replace(/>/g, '>'); - n = n.replace(/"/g, '"'); - return n; - } -}); -unwrapExports(xml); - -var lib = createCommonjsModule(function (module, exports) { - /*istanbul ignore start*/ - 'use strict'; - - exports.__esModule = true; - exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffArrays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined; - /*istanbul ignore end*/ - - /*istanbul ignore start*/ - - var _base2 = _interopRequireDefault(base); - /*istanbul ignore end*/ - - /*istanbul ignore start*/ - - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - 'default': obj - }; - } - - exports. - /*istanbul ignore end*/ - Diff = _base2['default']; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffChars = character.diffChars; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffWords = word.diffWords; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffWordsWithSpace = word.diffWordsWithSpace; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffLines = line.diffLines; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffTrimmedLines = line.diffTrimmedLines; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffSentences = sentence.diffSentences; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffCss = css.diffCss; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffJson = json.diffJson; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - diffArrays = array.diffArrays; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - structuredPatch = create.structuredPatch; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - createTwoFilesPatch = create.createTwoFilesPatch; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - createPatch = create.createPatch; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - applyPatch = apply.applyPatch; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - applyPatches = apply.applyPatches; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - parsePatch = parse.parsePatch; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - convertChangesToDMP = dmp.convertChangesToDMP; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - convertChangesToXML = xml.convertChangesToXML; - /*istanbul ignore start*/ - - exports. - /*istanbul ignore end*/ - canonicalize = json.canonicalize; - /* See LICENSE file for terms of use */ - - /* - * Text diff implementation. - * - * This library supports the following APIS: - * JsDiff.diffChars: Character by character diff - * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace - * JsDiff.diffLines: Line based diff - * - * JsDiff.diffCss: Diff targeted at CSS content - * - * These methods are based on the implementation proposed in - * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 - */ -}); -unwrapExports(lib); - -/*! - * normalize-path <https://github.com/jonschlinkert/normalize-path> - * - * Copyright (c) 2014-2018, Jon Schlinkert. - * Released under the MIT License. - */ -var normalizePath = function normalizePath(path, stripTrailing) { - if (typeof path !== 'string') { - throw new TypeError('expected path to be a string'); - } - - if (path === '\\' || path === '/') return '/'; - var len = path.length; - if (len <= 1) return path; // ensure that win32 namespaces has two leading slashes, so that the path is - // handled properly by the win32 version of path.parse() after being normalized - // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces - - var prefix = ''; - - if (len > 4 && path[3] === '\\') { - var ch = path[2]; - - if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { - path = path.slice(2); - prefix = '//'; - } - } - - var segs = path.split(/[/\\]+/); - - if (stripTrailing !== false && segs[segs.length - 1] === '') { - segs.pop(); - } - - return prefix + segs.join('/'); -}; - -var ConfigError = -/*#__PURE__*/ -function (_Error) { - _inherits(ConfigError, _Error); - - function ConfigError() { - _classCallCheck(this, ConfigError); - - return _possibleConstructorReturn(this, _getPrototypeOf(ConfigError).apply(this, arguments)); - } - - return ConfigError; -}(_wrapNativeSuper(Error)); - -var DebugError = -/*#__PURE__*/ -function (_Error2) { - _inherits(DebugError, _Error2); - - function DebugError() { - _classCallCheck(this, DebugError); - - return _possibleConstructorReturn(this, _getPrototypeOf(DebugError).apply(this, arguments)); - } - - return DebugError; -}(_wrapNativeSuper(Error)); - -var UndefinedParserError$1 = -/*#__PURE__*/ -function (_Error3) { - _inherits(UndefinedParserError, _Error3); - - function UndefinedParserError() { - _classCallCheck(this, UndefinedParserError); - - return _possibleConstructorReturn(this, _getPrototypeOf(UndefinedParserError).apply(this, arguments)); - } - - return UndefinedParserError; -}(_wrapNativeSuper(Error)); - -var errors = { - ConfigError: ConfigError, - DebugError: DebugError, - UndefinedParserError: UndefinedParserError$1 -}; - -var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; - -// based off https://github.com/defunctzombie/node-process/blob/master/browser.js - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} - -function defaultClearTimeout() { - throw new Error('clearTimeout has not been defined'); -} - -var cachedSetTimeout = defaultSetTimout; -var cachedClearTimeout = defaultClearTimeout; - -if (typeof global$1.setTimeout === 'function') { - cachedSetTimeout = setTimeout; -} - -if (typeof global$1.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; -} - -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } // if setTimeout wasn't available but was latter defined - - - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } -} - -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } // if clearTimeout wasn't available but was latter defined - - - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } -} - -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - - draining = false; - - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - - while (len) { - currentQueue = queue; - queue = []; - - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - - queueIndex = -1; - len = queue.length; - } - - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -function nextTick(fun) { - var args = new Array(arguments.length - 1); - - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - - queue.push(new Item(fun, args)); - - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -} // v8 likes predictible objects - -function Item(fun, array) { - this.fun = fun; - this.array = array; -} - -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; - -var title = 'browser'; -var platform = 'browser'; -var browser = true; -var env = {}; -var argv = []; -var version$2 = ''; // empty string to avoid regexp issues - -var versions = {}; -var release = {}; -var config = {}; - -function noop() {} - -var on = noop; -var addListener = noop; -var once = noop; -var off = noop; -var removeListener = noop; -var removeAllListeners = noop; -var emit = noop; -function binding(name) { - throw new Error('process.binding is not supported'); -} -function cwd() { - return '/'; -} -function chdir(dir) { - throw new Error('process.chdir is not supported'); -} - -function umask() { - return 0; -} // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - -var performance = global$1.performance || {}; - -var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { - return new Date().getTime(); -}; // generate timestamp or delta -// see http://nodejs.org/api/process.html#process_process_hrtime - - -function hrtime(previousTimestamp) { - var clocktime = performanceNow.call(performance) * 1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor(clocktime % 1 * 1e9); - - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - - if (nanoseconds < 0) { - seconds--; - nanoseconds += 1e9; - } - } - - return [seconds, nanoseconds]; -} -var startTime = new Date(); -function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; -} -var process = { - nextTick: nextTick, - title: title, - browser: browser, - env: env, - argv: argv, - version: version$2, - versions: versions, - on: on, - addListener: addListener, - once: once, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime -}; - -var semver = createCommonjsModule(function (module, exports) { - exports = module.exports = SemVer; // The debug function is excluded entirely from the minified version. - - /* nomin */ - - var debug; - /* nomin */ - - if (_typeof(process) === 'object' && - /* nomin */ - process.env && - /* nomin */ - process.env.NODE_DEBUG && - /* nomin */ - /\bsemver\b/i.test(process.env.NODE_DEBUG)) - /* nomin */ - debug = function debug() { - /* nomin */ - var args = Array.prototype.slice.call(arguments, 0); - /* nomin */ - - args.unshift('SEMVER'); - /* nomin */ - - console.log.apply(console, args); - /* nomin */ - }; - /* nomin */ - else - /* nomin */ - debug = function debug() {}; // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - - exports.SEMVER_SPEC_VERSION = '2.0.0'; - var MAX_LENGTH = 256; - var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // The actual regexps go on exports.re - - var re = exports.re = []; - var src = exports.src = []; - var R = 0; // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - var NUMERICIDENTIFIER = R++; - src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; - var NUMERICIDENTIFIERLOOSE = R++; - src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - var NONNUMERICIDENTIFIER = R++; - src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version - // Three dot-separated numeric identifiers. - - var MAINVERSION = R++; - src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')'; - var MAINVERSIONLOOSE = R++; - src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - var PRERELEASEIDENTIFIER = R++; - src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')'; - var PRERELEASEIDENTIFIERLOOSE = R++; - src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - var PRERELEASE = R++; - src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; - var PRERELEASELOOSE = R++; - src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. - - var BUILDIDENTIFIER = R++; - src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. - - var BUILD = R++; - src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. - - var FULL = R++; - var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?'; - src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - - var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?'; - var LOOSE = R++; - src[LOOSE] = '^' + LOOSEPLAIN + '$'; - var GTLT = R++; - src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - - var XRANGEIDENTIFIERLOOSE = R++; - src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; - var XRANGEIDENTIFIER = R++; - src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; - var XRANGEPLAIN = R++; - src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?'; - var XRANGEPLAINLOOSE = R++; - src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?'; - var XRANGE = R++; - src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; - var XRANGELOOSE = R++; - src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Tilde ranges. - // Meaning is "reasonably at or greater than" - - var LONETILDE = R++; - src[LONETILDE] = '(?:~>?)'; - var TILDETRIM = R++; - src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; - re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); - var tildeTrimReplace = '$1~'; - var TILDE = R++; - src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; - var TILDELOOSE = R++; - src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges. - // Meaning is "at least and backwards compatible with" - - var LONECARET = R++; - src[LONECARET] = '(?:\\^)'; - var CARETTRIM = R++; - src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; - re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); - var caretTrimReplace = '$1^'; - var CARET = R++; - src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; - var CARETLOOSE = R++; - src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version" - - var COMPARATORLOOSE = R++; - src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; - var COMPARATOR = R++; - src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - - var COMPARATORTRIM = R++; - src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag - - re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); - var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - - var HYPHENRANGE = R++; - src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$'; - var HYPHENRANGELOOSE = R++; - src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all. - - var STAR = R++; - src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects. - // All are flag-free, unless they were created above with a flag. - - for (var i = 0; i < R; i++) { - debug(i, src[i]); - if (!re[i]) re[i] = new RegExp(src[i]); - } - - exports.parse = parse; - - function parse(version, loose) { - if (version instanceof SemVer) return version; - if (typeof version !== 'string') return null; - if (version.length > MAX_LENGTH) return null; - var r = loose ? re[LOOSE] : re[FULL]; - if (!r.test(version)) return null; - - try { - return new SemVer(version, loose); - } catch (er) { - return null; - } - } - - exports.valid = valid; - - function valid(version, loose) { - var v = parse(version, loose); - return v ? v.version : null; - } - - exports.clean = clean; - - function clean(version, loose) { - var s = parse(version.trim().replace(/^[=v]+/, ''), loose); - return s ? s.version : null; - } - - exports.SemVer = SemVer; - - function SemVer(version, loose) { - if (version instanceof SemVer) { - if (version.loose === loose) return version;else version = version.version; - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version); - } - - if (version.length > MAX_LENGTH) throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters'); - if (!(this instanceof SemVer)) return new SemVer(version, loose); - debug('SemVer', version, loose); - this.loose = loose; - var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); - if (!m) throw new TypeError('Invalid Version: ' + version); - this.raw = version; // these are actually numbers - - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) throw new TypeError('Invalid major version'); - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) throw new TypeError('Invalid minor version'); - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) throw new TypeError('Invalid patch version'); // numberify any prerelease numeric ids - - if (!m[4]) this.prerelease = [];else this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) return num; - } - - return id; - }); - this.build = m[5] ? m[5].split('.') : []; - this.format(); - } - - SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch; - if (this.prerelease.length) this.version += '-' + this.prerelease.join('.'); - return this.version; - }; - - SemVer.prototype.toString = function () { - return this.version; - }; - - SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.loose, other); - if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); - return this.compareMain(other) || this.comparePre(other); - }; - - SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); - return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); - }; - - SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); // NOT having a prerelease is > having one - - if (this.prerelease.length && !other.prerelease.length) return -1;else if (!this.prerelease.length && other.prerelease.length) return 1;else if (!this.prerelease.length && !other.prerelease.length) return 0; - var i = 0; - - do { - var a = this.prerelease[i]; - var b = other.prerelease[i]; - debug('prerelease compare', i, a, b); - if (a === undefined && b === undefined) return 0;else if (b === undefined) return 1;else if (a === undefined) return -1;else if (a === b) continue;else return compareIdentifiers(a, b); - } while (++i); - }; // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - - - SemVer.prototype.inc = function (release$$1, identifier) { - switch (release$$1) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break; - - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break; - - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break; - // If the input is a non-prerelease version, this acts the same as - // prepatch. - - case 'prerelease': - if (this.prerelease.length === 0) this.inc('patch', identifier); - this.inc('pre', identifier); - break; - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) this.major++; - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) this.minor++; - this.patch = 0; - this.prerelease = []; - break; - - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) this.patch++; - this.prerelease = []; - break; - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - - case 'pre': - if (this.prerelease.length === 0) this.prerelease = [0];else { - var i = this.prerelease.length; - - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - - if (i === -1) // didn't increment anything - this.prerelease.push(0); - } - - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) this.prerelease = [identifier, 0]; - } else this.prerelease = [identifier, 0]; - } - - break; - - default: - throw new Error('invalid increment argument: ' + release$$1); - } - - this.format(); - this.raw = this.version; - return this; - }; - - exports.inc = inc; - - function inc(version, release$$1, loose, identifier) { - if (typeof loose === 'string') { - identifier = loose; - loose = undefined; - } - - try { - return new SemVer(version, loose).inc(release$$1, identifier).version; - } catch (er) { - return null; - } - } - - exports.diff = diff; - - function diff(version1, version2) { - if (eq(version1, version2)) { - return null; - } else { - var v1 = parse(version1); - var v2 = parse(version2); - - if (v1.prerelease.length || v2.prerelease.length) { - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return 'pre' + key; - } - } - } - - return 'prerelease'; - } - - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return key; - } - } - } - } - } - - exports.compareIdentifiers = compareIdentifiers; - var numeric = /^[0-9]+$/; - - function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : a > b ? 1 : 0; - } - - exports.rcompareIdentifiers = rcompareIdentifiers; - - function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); - } - - exports.major = major; - - function major(a, loose) { - return new SemVer(a, loose).major; - } - - exports.minor = minor; - - function minor(a, loose) { - return new SemVer(a, loose).minor; - } - - exports.patch = patch; - - function patch(a, loose) { - return new SemVer(a, loose).patch; - } - - exports.compare = compare; - - function compare(a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)); - } - - exports.compareLoose = compareLoose; - - function compareLoose(a, b) { - return compare(a, b, true); - } - - exports.rcompare = rcompare; - - function rcompare(a, b, loose) { - return compare(b, a, loose); - } - - exports.sort = sort; - - function sort(list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose); - }); - } - - exports.rsort = rsort; - - function rsort(list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose); - }); - } - - exports.gt = gt; - - function gt(a, b, loose) { - return compare(a, b, loose) > 0; - } - - exports.lt = lt; - - function lt(a, b, loose) { - return compare(a, b, loose) < 0; - } - - exports.eq = eq; - - function eq(a, b, loose) { - return compare(a, b, loose) === 0; - } - - exports.neq = neq; - - function neq(a, b, loose) { - return compare(a, b, loose) !== 0; - } - - exports.gte = gte; - - function gte(a, b, loose) { - return compare(a, b, loose) >= 0; - } - - exports.lte = lte; - - function lte(a, b, loose) { - return compare(a, b, loose) <= 0; - } - - exports.cmp = cmp; - - function cmp(a, op, b, loose) { - var ret; - - switch (op) { - case '===': - if (_typeof(a) === 'object') a = a.version; - if (_typeof(b) === 'object') b = b.version; - ret = a === b; - break; - - case '!==': - if (_typeof(a) === 'object') a = a.version; - if (_typeof(b) === 'object') b = b.version; - ret = a !== b; - break; - - case '': - case '=': - case '==': - ret = eq(a, b, loose); - break; - - case '!=': - ret = neq(a, b, loose); - break; - - case '>': - ret = gt(a, b, loose); - break; - - case '>=': - ret = gte(a, b, loose); - break; - - case '<': - ret = lt(a, b, loose); - break; - - case '<=': - ret = lte(a, b, loose); - break; - - default: - throw new TypeError('Invalid operator: ' + op); - } - - return ret; - } - - exports.Comparator = Comparator; - - function Comparator(comp, loose) { - if (comp instanceof Comparator) { - if (comp.loose === loose) return comp;else comp = comp.value; - } - - if (!(this instanceof Comparator)) return new Comparator(comp, loose); - debug('comparator', comp, loose); - this.loose = loose; - this.parse(comp); - if (this.semver === ANY) this.value = '';else this.value = this.operator + this.semver.version; - debug('comp', this); - } - - var ANY = {}; - - Comparator.prototype.parse = function (comp) { - var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var m = comp.match(r); - if (!m) throw new TypeError('Invalid comparator: ' + comp); - this.operator = m[1]; - if (this.operator === '=') this.operator = ''; // if it literally is just '>' or '' then allow anything. - - if (!m[2]) this.semver = ANY;else this.semver = new SemVer(m[2], this.loose); - }; - - Comparator.prototype.toString = function () { - return this.value; - }; - - Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.loose); - if (this.semver === ANY) return true; - if (typeof version === 'string') version = new SemVer(version, this.loose); - return cmp(version, this.operator, this.semver, this.loose); - }; - - Comparator.prototype.intersects = function (comp, loose) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required'); - } - - var rangeTmp; - - if (this.operator === '') { - rangeTmp = new Range(comp.value, loose); - return satisfies(this.value, rangeTmp, loose); - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, loose); - return satisfies(comp.semver, rangeTmp, loose); - } - - var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>'); - var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<'); - var sameSemVer = this.semver.version === comp.semver.version; - var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); - var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, loose) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); - var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, loose) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); - return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; - }; - - exports.Range = Range; - - function Range(range, loose) { - if (range instanceof Range) { - if (range.loose === loose) { - return range; - } else { - return new Range(range.raw, loose); - } - } - - if (range instanceof Comparator) { - return new Range(range.value, loose); - } - - if (!(this instanceof Range)) return new Range(range, loose); - this.loose = loose; // First, split based on boolean or || - - this.raw = range; - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()); - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length; - }); - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range); - } - - this.format(); - } - - Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim(); - }).join('||').trim(); - return this.range; - }; - - Range.prototype.toString = function () { - return this.range; - }; - - Range.prototype.parseRange = function (range) { - var loose = this.loose; - range = range.trim(); - debug('range', range, loose); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); - debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3` - - range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3` - - range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces - - range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, loose); - }).join(' ').split(/\s+/); - - if (this.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe); - }); - } - - set = set.map(function (comp) { - return new Comparator(comp, loose); - }); - return set; - }; - - Range.prototype.intersects = function (range, loose) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required'); - } - - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, loose); - }); - }); - }); - }); - }; // Mostly just for testing and legacy API reasons - - - exports.toComparators = toComparators; - - function toComparators(range, loose) { - return new Range(range, loose).set.map(function (comp) { - return comp.map(function (c) { - return c.value; - }).join(' ').trim().split(' '); - }); - } // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - - - function parseComparator(comp, loose) { - debug('comp', comp); - comp = replaceCarets(comp, loose); - debug('caret', comp); - comp = replaceTildes(comp, loose); - debug('tildes', comp); - comp = replaceXRanges(comp, loose); - debug('xrange', comp); - comp = replaceStars(comp, loose); - debug('stars', comp); - return comp; - } - - function isX(id) { - return !id || id.toLowerCase() === 'x' || id === '*'; - } // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 - - - function replaceTildes(comp, loose) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, loose); - }).join(' '); - } - - function replaceTilde(comp, loose) { - var r = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr); - var ret; - if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else if (pr) { - debug('replaceTilde pr', pr); - if (pr.charAt(0) !== '-') pr = '-' + pr; - ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0'; - } else // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; - debug('tilde return', ret); - return ret; - }); - } // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 - // ^1.2.3 --> >=1.2.3 <2.0.0 - // ^1.2.0 --> >=1.2.0 <2.0.0 - - - function replaceCarets(comp, loose) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, loose); - }).join(' '); - } - - function replaceCaret(comp, loose) { - debug('caret', comp, loose); - var r = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr); - var ret; - if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) { - if (M === '0') ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; - } else if (pr) { - debug('replaceCaret pr', pr); - if (pr.charAt(0) !== '-') pr = '-' + pr; - - if (M === '0') { - if (m === '0') ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0'; - } else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + (+M + 1) + '.0.0'; - } else { - debug('no pr'); - - if (M === '0') { - if (m === '0') ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; - } else ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0'; - } - debug('caret return', ret); - return ret; - }); - } - - function replaceXRanges(comp, loose) { - debug('replaceXRanges', comp, loose); - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, loose); - }).join(' '); - } - - function replaceXRange(comp, loose) { - comp = comp.trim(); - var r = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; - if (gtlt === '=' && anyX) gtlt = ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // replace X with 0 - if (xm) m = 0; - if (xp) p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>='; - - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else if (xp) { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) M = +M + 1;else m = +m + 1; - } - - ret = gtlt + M + '.' + m + '.' + p; - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - } - - debug('xRange return', ret); - return ret; - }); - } // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - - - function replaceStars(comp, loose) { - debug('replaceStars', comp, loose); // Looseness is ignored here. star is always as loose as it gets! - - return comp.trim().replace(re[STAR], ''); - } // This function is passed to string.replace(re[HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0 - - - function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { - if (isX(fM)) from = '';else if (isX(fm)) from = '>=' + fM + '.0.0';else if (isX(fp)) from = '>=' + fM + '.' + fm + '.0';else from = '>=' + from; - if (isX(tM)) to = '';else if (isX(tm)) to = '<' + (+tM + 1) + '.0.0';else if (isX(tp)) to = '<' + tM + '.' + (+tm + 1) + '.0';else if (tpr) to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;else to = '<=' + to; - return (from + ' ' + to).trim(); - } // if ANY of the sets match ALL of its comparators, then pass - - - Range.prototype.test = function (version) { - if (!version) return false; - if (typeof version === 'string') version = new SemVer(version, this.loose); - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version)) return true; - } - - return false; - }; - - function testSet(set, version) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) return false; - } - - if (version.prerelease.length) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (var i = 0; i < set.length; i++) { - debug(set[i].semver); - if (set[i].semver === ANY) continue; - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver; - if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) return true; - } - } // Version has a -pre, but it's not one of the ones we like. - - - return false; - } - - return true; - } - - exports.satisfies = satisfies; - - function satisfies(version, range, loose) { - try { - range = new Range(range, loose); - } catch (er) { - return false; - } - - return range.test(version); - } - - exports.maxSatisfying = maxSatisfying; - - function maxSatisfying(versions$$1, range, loose) { - var max = null; - var maxSV = null; - - try { - var rangeObj = new Range(range, loose); - } catch (er) { - return null; - } - - versions$$1.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, loose) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer(max, loose); - } - } - }); - return max; - } - - exports.minSatisfying = minSatisfying; - - function minSatisfying(versions$$1, range, loose) { - var min = null; - var minSV = null; - - try { - var rangeObj = new Range(range, loose); - } catch (er) { - return null; - } - - versions$$1.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, loose) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer(min, loose); - } - } - }); - return min; - } - - exports.validRange = validRange; - - function validRange(range, loose) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, loose).range || '*'; - } catch (er) { - return null; - } - } // Determine if version is less than all the versions possible in the range - - - exports.ltr = ltr; - - function ltr(version, range, loose) { - return outside(version, range, '<', loose); - } // Determine if version is greater than all the versions possible in the range. - - - exports.gtr = gtr; - - function gtr(version, range, loose) { - return outside(version, range, '>', loose); - } - - exports.outside = outside; - - function outside(version, range, hilo, loose) { - version = new SemVer(version, loose); - range = new Range(range, loose); - var gtfn, ltefn, ltfn, comp, ecomp; - - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break; - - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break; - - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } // If it satisifes the range it is not outside - - - if (satisfies(version, range, loose)) { - return false; - } // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i]; - var high = null; - var low = null; - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0'); - } - - high = high || comparator; - low = low || comparator; - - if (gtfn(comparator.semver, high.semver, loose)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, loose)) { - low = comparator; - } - }); // If the edge version comparator has a operator then our version - // isn't outside it - - if (high.operator === comp || high.operator === ecomp) { - return false; - } // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - - - if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; - } - } - - return true; - } - - exports.prerelease = prerelease; - - function prerelease(version, loose) { - var parsed = parse(version, loose); - return parsed && parsed.prerelease.length ? parsed.prerelease : null; - } - - exports.intersects = intersects; - - function intersects(r1, r2, loose) { - r1 = new Range(r1, loose); - r2 = new Range(r2, loose); - return r1.intersects(r2); - } -}); - -var arrayify = function arrayify(object, keyName) { - return Object.keys(object).reduce(function (array, key) { - return array.concat(Object.assign(_defineProperty({}, keyName, key), object[key])); - }, []); -}; - -var dedent_1 = createCommonjsModule(function (module) { - "use strict"; - - function dedent(strings) { - var raw = void 0; - - if (typeof strings === "string") { - // dedent can be used as a plain function - raw = [strings]; - } else { - raw = strings.raw; - } // first, perform interpolation - - - var result = ""; - - for (var i = 0; i < raw.length; i++) { - result += raw[i]. // join lines when there is a suppressed newline - replace(/\\\n[ \t]*/g, ""). // handle escaped backticks - replace(/\\`/g, "`"); - - if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) { - result += arguments.length <= i + 1 ? undefined : arguments[i + 1]; - } - } // now strip indentation - - - var lines = result.split("\n"); - var mindent = null; - lines.forEach(function (l) { - var m = l.match(/^(\s+)\S+/); - - if (m) { - var indent = m[1].length; - - if (!mindent) { - // this is the first indented line - mindent = indent; - } else { - mindent = Math.min(mindent, indent); - } - } - }); - - if (mindent !== null) { - result = lines.map(function (l) { - return l[0] === " " ? l.slice(mindent) : l; - }).join("\n"); - } // dedent eats leading and trailing whitespace too - - - result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too - - return result.replace(/\\n/g, "\n"); - } - - { - module.exports = dedent; - } -}); - -function _templateObject5() { - var data = _taggedTemplateLiteral(["\n Require either '@prettier' or '@format' to be present in the file's first docblock comment\n in order for it to be formatted.\n "]); - - _templateObject5 = function _templateObject5() { - return data; - }; - - return data; -} - -function _templateObject4() { - var data = _taggedTemplateLiteral(["\n Format code starting at a given character offset.\n The range will extend backwards to the start of the first line containing the selected statement.\n This option cannot be used with --cursor-offset.\n "]); - - _templateObject4 = function _templateObject4() { - return data; - }; - - return data; -} - -function _templateObject3() { - var data = _taggedTemplateLiteral(["\n Format code ending at a given character offset (exclusive).\n The range will extend forwards to the end of the selected statement.\n This option cannot be used with --cursor-offset.\n "]); - - _templateObject3 = function _templateObject3() { - return data; - }; - - return data; -} - -function _templateObject2() { - var data = _taggedTemplateLiteral(["\n Custom directory that contains prettier plugins in node_modules subdirectory.\n Overrides default behavior when plugins are searched relatively to the location of Prettier.\n Multiple values are accepted.\n "]); - - _templateObject2 = function _templateObject2() { - return data; - }; - - return data; -} - -function _templateObject() { - var data = _taggedTemplateLiteral(["\n Print (to stderr) where a cursor at the given position would move to after formatting.\n This option cannot be used with --range-start and --range-end.\n "]); - - _templateObject = function _templateObject() { - return data; - }; - - return data; -} - -var CATEGORY_CONFIG = "Config"; -var CATEGORY_EDITOR = "Editor"; -var CATEGORY_FORMAT = "Format"; -var CATEGORY_OTHER = "Other"; -var CATEGORY_OUTPUT = "Output"; -var CATEGORY_GLOBAL = "Global"; -var CATEGORY_SPECIAL = "Special"; -/** - * @typedef {Object} OptionInfo - * @property {string} since - available since version - * @property {string} category - * @property {'int' | 'boolean' | 'choice' | 'path'} type - * @property {boolean} array - indicate it's an array of the specified type - * @property {boolean?} deprecated - deprecated since version - * @property {OptionRedirectInfo?} redirect - redirect deprecated option - * @property {string} description - * @property {string?} oppositeDescription - for `false` option - * @property {OptionValueInfo} default - * @property {OptionRangeInfo?} range - for type int - * @property {OptionChoiceInfo?} choices - for type choice - * @property {(value: any) => boolean} exception - * - * @typedef {number | boolean | string} OptionValue - * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo - * - * @typedef {Object} OptionRedirectInfo - * @property {string} option - * @property {OptionValue} value - * - * @typedef {Object} OptionRangeInfo - * @property {number} start - recommended range start - * @property {number} end - recommended range end - * @property {number} step - recommended range step - * - * @typedef {Object} OptionChoiceInfo - * @property {boolean | string} value - boolean for the option that is originally boolean type - * @property {string?} description - undefined if redirect - * @property {string?} since - undefined if available since the first version of the option - * @property {string?} deprecated - deprecated since version - * @property {OptionValueInfo?} redirect - redirect deprecated value - * - * @property {string?} cliName - * @property {string?} cliCategory - * @property {string?} cliDescription - */ - -/** @type {{ [name: string]: OptionInfo } */ - -var options$2 = { - cursorOffset: { - since: "1.4.0", - category: CATEGORY_SPECIAL, - type: "int", - default: -1, - range: { - start: -1, - end: Infinity, - step: 1 - }, - description: dedent_1(_templateObject()), - cliCategory: CATEGORY_EDITOR - }, - filepath: { - since: "1.4.0", - category: CATEGORY_SPECIAL, - type: "path", - default: undefined, - description: "Specify the input filepath. This will be used to do parser inference.", - cliName: "stdin-filepath", - cliCategory: CATEGORY_OTHER, - cliDescription: "Path to the file to pretend that stdin comes from." - }, - insertPragma: { - since: "1.8.0", - category: CATEGORY_SPECIAL, - type: "boolean", - default: false, - description: "Insert @format pragma into file's first docblock comment.", - cliCategory: CATEGORY_OTHER - }, - parser: { - since: "0.0.10", - category: CATEGORY_GLOBAL, - type: "choice", - default: [{ - since: "0.0.10", - value: "babylon" - }, { - since: "1.13.0", - value: undefined - }], - description: "Which parser to use.", - exception: function exception(value) { - return typeof value === "string" || typeof value === "function"; - }, - choices: [{ - value: "flow", - description: "Flow" - }, { - value: "babylon", - description: "JavaScript" - }, { - value: "typescript", - since: "1.4.0", - description: "TypeScript" - }, { - value: "css", - since: "1.7.1", - description: "CSS" - }, { - value: "postcss", - since: "1.4.0", - description: "CSS/Less/SCSS", - deprecated: "1.7.1", - redirect: "css" - }, { - value: "less", - since: "1.7.1", - description: "Less" - }, { - value: "scss", - since: "1.7.1", - description: "SCSS" - }, { - value: "json", - since: "1.5.0", - description: "JSON" - }, { - value: "json5", - since: "1.13.0", - description: "JSON5" - }, { - value: "json-stringify", - since: "1.13.0", - description: "JSON.stringify" - }, { - value: "graphql", - since: "1.5.0", - description: "GraphQL" - }, { - value: "markdown", - since: "1.8.0", - description: "Markdown" - }, { - value: "vue", - since: "1.10.0", - description: "Vue" - }, { - value: "yaml", - since: "1.14.0", - description: "YAML" - }] - }, - plugins: { - since: "1.10.0", - type: "path", - array: true, - default: [{ - value: [] - }], - category: CATEGORY_GLOBAL, - description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.", - exception: function exception(value) { - return typeof value === "string" || _typeof(value) === "object"; - }, - cliName: "plugin", - cliCategory: CATEGORY_CONFIG - }, - pluginSearchDirs: { - since: "1.13.0", - type: "path", - array: true, - default: [{ - value: [] - }], - category: CATEGORY_GLOBAL, - description: dedent_1(_templateObject2()), - exception: function exception(value) { - return typeof value === "string" || _typeof(value) === "object"; - }, - cliName: "plugin-search-dir", - cliCategory: CATEGORY_CONFIG - }, - printWidth: { - since: "0.0.0", - category: CATEGORY_GLOBAL, - type: "int", - default: 80, - description: "The line length where Prettier will try wrap.", - range: { - start: 0, - end: Infinity, - step: 1 - } - }, - rangeEnd: { - since: "1.4.0", - category: CATEGORY_SPECIAL, - type: "int", - default: Infinity, - range: { - start: 0, - end: Infinity, - step: 1 - }, - description: dedent_1(_templateObject3()), - cliCategory: CATEGORY_EDITOR - }, - rangeStart: { - since: "1.4.0", - category: CATEGORY_SPECIAL, - type: "int", - default: 0, - range: { - start: 0, - end: Infinity, - step: 1 - }, - description: dedent_1(_templateObject4()), - cliCategory: CATEGORY_EDITOR - }, - requirePragma: { - since: "1.7.0", - category: CATEGORY_SPECIAL, - type: "boolean", - default: false, - description: dedent_1(_templateObject5()), - cliCategory: CATEGORY_OTHER - }, - tabWidth: { - type: "int", - category: CATEGORY_GLOBAL, - default: 2, - description: "Number of spaces per indentation level.", - range: { - start: 0, - end: Infinity, - step: 1 - } - }, - useFlowParser: { - since: "0.0.0", - category: CATEGORY_GLOBAL, - type: "boolean", - default: false, - deprecated: "0.0.10", - description: "Use flow parser.", - redirect: { - option: "parser", - value: "flow" - }, - cliName: "flow-parser" - }, - useTabs: { - since: "1.0.0", - category: CATEGORY_GLOBAL, - type: "boolean", - default: false, - description: "Indent with tabs instead of spaces." - } -}; -var coreOptions$1 = { - CATEGORY_CONFIG: CATEGORY_CONFIG, - CATEGORY_EDITOR: CATEGORY_EDITOR, - CATEGORY_FORMAT: CATEGORY_FORMAT, - CATEGORY_OTHER: CATEGORY_OTHER, - CATEGORY_OUTPUT: CATEGORY_OUTPUT, - CATEGORY_GLOBAL: CATEGORY_GLOBAL, - CATEGORY_SPECIAL: CATEGORY_SPECIAL, - options: options$2 -}; - -var require$$0 = ( _package$1 && _package ) || _package$1; - -var currentVersion = require$$0.version; -var coreOptions = coreOptions$1.options; - -function getSupportInfo$2(version, opts) { - opts = Object.assign({ - plugins: [], - showUnreleased: false, - showDeprecated: false, - showInternal: false - }, opts); - - if (!version) { - // pre-release version is smaller than the normal version in semver, - // we need to treat it as the normal one so as to test new features. - version = currentVersion.split("-", 1)[0]; - } - - var plugins = opts.plugins; - var options = arrayify(Object.assign(plugins.reduce(function (currentOptions, plugin) { - return Object.assign(currentOptions, plugin.options); - }, {}), coreOptions), "name").sort(function (a, b) { - return a.name === b.name ? 0 : a.name < b.name ? -1 : 1; - }).filter(filterSince).filter(filterDeprecated).map(mapDeprecated).map(mapInternal).map(function (option) { - var newOption = Object.assign({}, option); - - if (Array.isArray(newOption.default)) { - newOption.default = newOption.default.length === 1 ? newOption.default[0].value : newOption.default.filter(filterSince).sort(function (info1, info2) { - return semver.compare(info2.since, info1.since); - })[0].value; - } - - if (Array.isArray(newOption.choices)) { - newOption.choices = newOption.choices.filter(filterSince).filter(filterDeprecated).map(mapDeprecated); - } - - return newOption; - }).map(function (option) { - var filteredPlugins = plugins.filter(function (plugin) { - return plugin.defaultOptions && plugin.defaultOptions[option.name]; - }); - var pluginDefaults = filteredPlugins.reduce(function (reduced, plugin) { - reduced[plugin.name] = plugin.defaultOptions[option.name]; - return reduced; - }, {}); - return Object.assign(option, { - pluginDefaults: pluginDefaults - }); - }); - var usePostCssParser = semver.lt(version, "1.7.1"); - var languages = plugins.reduce(function (all, plugin) { - return all.concat(plugin.languages || []); - }, []).filter(function (language) { - return language.since ? semver.gte(version, language.since) : language.since !== null; - }).map(function (language) { - // Prevent breaking changes - if (language.name === "Markdown") { - return Object.assign({}, language, { - parsers: ["markdown"] - }); - } - - if (language.name === "TypeScript") { - return Object.assign({}, language, { - parsers: ["typescript"] - }); - } - - if (usePostCssParser && (language.name === "CSS" || language.group === "CSS")) { - return Object.assign({}, language, { - parsers: ["postcss"] - }); - } - - return language; - }); - return { - languages: languages, - options: options - }; - - function filterSince(object) { - return opts.showUnreleased || !("since" in object) || object.since && semver.gte(version, object.since); - } - - function filterDeprecated(object) { - return opts.showDeprecated || !("deprecated" in object) || object.deprecated && semver.lt(version, object.deprecated); - } - - function mapDeprecated(object) { - if (!object.deprecated || opts.showDeprecated) { - return object; - } - - var newObject = Object.assign({}, object); - delete newObject.deprecated; - delete newObject.redirect; - return newObject; - } - - function mapInternal(object) { - if (opts.showInternal) { - return object; - } - - var newObject = Object.assign({}, object); - delete newObject.cliName; - delete newObject.cliCategory; - delete newObject.cliDescription; - return newObject; - } -} - -var support = { - getSupportInfo: getSupportInfo$2 -}; - -/* eslint-disable no-nested-ternary */ -var arr = []; -var charCodeCache = []; - -var leven = function leven(a, b) { - if (a === b) { - return 0; - } - - var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the - // shortest & which one is the longest - - if (a.length > b.length) { - a = b; - b = swap; - } - - var aLen = a.length; - var bLen = b.length; - - if (aLen === 0) { - return bLen; - } - - if (bLen === 0) { - return aLen; - } // Performing suffix trimming: - // We can linearly drop suffix common to both strings since they - // don't increase distance at all - // Note: `~-` is the bitwise way to perform a `- 1` operation - - - while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) { - aLen--; - bLen--; - } - - if (aLen === 0) { - return bLen; - } // Performing prefix trimming - // We can linearly drop prefix common to both strings since they - // don't increase distance at all - - - var start = 0; - - while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) { - start++; - } - - aLen -= start; - bLen -= start; - - if (aLen === 0) { - return bLen; - } - - var bCharCode; - var ret; - var tmp; - var tmp2; - var i = 0; - var j = 0; - - while (i < aLen) { - charCodeCache[start + i] = a.charCodeAt(start + i); - arr[i] = ++i; - } - - while (j < bLen) { - bCharCode = b.charCodeAt(start + j); - tmp = j++; - ret = j; - - for (i = 0; i < aLen; i++) { - tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1; - tmp = arr[i]; - ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2; - } - } - - return ret; -}; - -function apiDescriptor(name, value) { - return arguments.length === 1 ? JSON.stringify(name) : "`{ ".concat(apiDescriptor(name), ": ").concat(JSON.stringify(value), " }`"); -} - -function cliDescriptor(name, value) { - return value === false ? "`--no-".concat(name, "`") : value === true || arguments.length === 1 ? "`--".concat(name, "`") : value === "" ? "`--".concat(name, "` without an argument") : "`--".concat(name, "=").concat(value, "`"); -} - -var optionsDescriptor = { - apiDescriptor: apiDescriptor, - cliDescriptor: cliDescriptor -}; - -function validateOption(value, optionInfo, opts) { - opts = opts || {}; - var descriptor = opts.descriptor || optionsDescriptor.apiDescriptor; - - if (typeof optionInfo.exception === "function" && optionInfo.exception(value)) { - return; - } - - try { - validateOptionType(value, optionInfo); - } catch (error) { - throw new Error("Invalid `".concat(descriptor(optionInfo.name), "` value. ").concat(error.message, ", but received `").concat(JSON.stringify(value), "`.")); - } -} - -function validateOptionType(value, optionInfo) { - if (optionInfo.array) { - if (!Array.isArray(value)) { - throw new Error("Expected an array"); - } - - value.forEach(function (v) { - return validateOptionType(v, Object.assign({}, optionInfo, { - array: false - })); - }); - } else { - switch (optionInfo.type) { - case "int": - validateIntOption(value); - break; - - case "boolean": - validateBooleanOption(value); - break; - - case "choice": - validateChoiceOption(value, optionInfo.choices); - break; - } - } -} - -function validateBooleanOption(value) { - if (typeof value !== "boolean") { - throw new Error("Expected a boolean"); - } -} - -function validateIntOption(value) { - if (!(typeof value === "number" && Math.floor(value) === value && value >= 0 && value !== Infinity)) { - throw new Error("Expected an integer"); - } -} - -function validateChoiceOption(value, choiceInfos) { - if (!choiceInfos.some(function (choiceInfo) { - return choiceInfo.value === value; - })) { - var choices = choiceInfos.filter(function (choiceInfo) { - return !choiceInfo.deprecated; - }).map(function (choiceInfo) { - return JSON.stringify(choiceInfo.value); - }).sort(); - var head = choices.slice(0, -2); - var tail = choices.slice(-2); - throw new Error("Expected ".concat(head.concat(tail.join(" or ")).join(", "))); - } -} - -var optionsValidator = { - validateOption: validateOption -}; - -function normalizeOptions$1(options, optionInfos, opts) { - opts = opts || {}; - var logger = opts.logger === false ? { - warn: function warn() {} - } : opts.logger !== undefined ? opts.logger : console; - var descriptor = opts.descriptor || optionsDescriptor.apiDescriptor; - var passThrough = opts.passThrough || []; - var optionInfoMap = optionInfos.reduce(function (reduced, optionInfo) { - return Object.assign(reduced, _defineProperty({}, optionInfo.name, optionInfo)); - }, {}); - var normalizedOptions = Object.keys(options).reduce(function (newOptions, key) { - var optionInfo = optionInfoMap[key]; - var optionName = key; - var optionValue = options[key]; - - if (!optionInfo) { - if (passThrough === true || passThrough.indexOf(optionName) !== -1) { - newOptions[optionName] = optionValue; - } else { - logger.warn(createUnknownOptionMessage(optionName, optionValue, optionInfos, descriptor)); - } - - return newOptions; - } - - if (!optionInfo.deprecated) { - optionValue = normalizeOption(optionValue, optionInfo); - } else if (typeof optionInfo.redirect === "string") { - logger.warn(createRedirectOptionMessage(optionInfo, descriptor)); - optionName = optionInfo.redirect; - } else if (optionValue) { - logger.warn(createRedirectOptionMessage(optionInfo, descriptor)); - optionValue = optionInfo.redirect.value; - optionName = optionInfo.redirect.option; - } - - if (optionInfo.choices) { - var choiceInfo = optionInfo.choices.find(function (choice) { - return choice.value === optionValue; - }); - - if (choiceInfo && choiceInfo.deprecated) { - logger.warn(createRedirectChoiceMessage(optionInfo, choiceInfo, descriptor)); - optionValue = choiceInfo.redirect; - } - } - - if (optionInfo.array && !Array.isArray(optionValue)) { - optionValue = [optionValue]; - } - - if (optionValue !== optionInfo.default) { - optionsValidator.validateOption(optionValue, optionInfoMap[optionName], { - descriptor: descriptor - }); - } - - newOptions[optionName] = optionValue; - return newOptions; - }, {}); - return normalizedOptions; -} - -function normalizeOption(option, optionInfo) { - return optionInfo.type === "int" ? Number(option) : option; -} - -function createUnknownOptionMessage(key, value, optionInfos, descriptor) { - var messages = ["Ignored unknown option ".concat(descriptor(key, value), ".")]; - var suggestedOptionInfo = optionInfos.find(function (optionInfo) { - return leven(optionInfo.name, key) < 3; - }); - - if (suggestedOptionInfo) { - messages.push("Did you mean ".concat(JSON.stringify(suggestedOptionInfo.name), "?")); - } - - return messages.join(" "); -} - -function createRedirectOptionMessage(optionInfo, descriptor) { - return "".concat(descriptor(optionInfo.name), " is deprecated. Prettier now treats it as ").concat(typeof optionInfo.redirect === "string" ? descriptor(optionInfo.redirect) : descriptor(optionInfo.redirect.option, optionInfo.redirect.value), "."); -} - -function createRedirectChoiceMessage(optionInfo, choiceInfo, descriptor) { - return "".concat(descriptor(optionInfo.name, choiceInfo.value), " is deprecated. Prettier now treats it as ").concat(descriptor(optionInfo.name, choiceInfo.redirect), "."); -} - -function normalizeApiOptions(options, optionInfos, opts) { - return normalizeOptions$1(options, optionInfos, Object.assign({ - descriptor: optionsDescriptor.apiDescriptor - }, opts)); -} - -function normalizeCliOptions(options, optionInfos, opts) { - var args = options["_"] || []; - var newOptions = normalizeOptions$1(Object.keys(options).reduce(function (reduced, key) { - return Object.assign(reduced, key.length === 1 // omit alias - ? null : _defineProperty({}, key, options[key])); - }, {}), optionInfos, Object.assign({ - descriptor: optionsDescriptor.cliDescriptor - }, opts)); - newOptions["_"] = args; - return newOptions; -} - -var optionsNormalizer = { - normalizeApiOptions: normalizeApiOptions, - normalizeCliOptions: normalizeCliOptions -}; - -var _shim_path = {}; - -var _shim_path$1 = Object.freeze({ - default: _shim_path -}); - -var getLast = function getLast(arr) { - return arr.length > 0 ? arr[arr.length - 1] : null; -}; - -function locStart$1(node) { - // Handle nodes with decorators. They should start at the first decorator - if (node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) { - return locStart$1(node.declaration.decorators[0]); - } - - if (node.decorators && node.decorators.length > 0) { - return locStart$1(node.decorators[0]); - } - - if (node.__location) { - return node.__location.startOffset; - } - - if (node.range) { - return node.range[0]; - } - - if (typeof node.start === "number") { - return node.start; - } - - if (node.loc) { - return node.loc.start; - } - - return null; -} - -function locEnd$1(node) { - var endNode = node.nodes && getLast(node.nodes); - - if (endNode && node.source && !node.source.end) { - node = endNode; - } - - if (node.__location) { - return node.__location.endOffset; - } - - var loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null; - - if (node.typeAnnotation) { - return Math.max(loc, locEnd$1(node.typeAnnotation)); - } - - if (node.loc && !loc) { - return node.loc.end; - } - - return loc; -} - -var loc = { - locStart: locStart$1, - locEnd: locEnd$1 -}; - -var jsTokens = createCommonjsModule(function (module, exports) { - // Copyright 2014, 2015, 2016, 2017 Simon Lydell - // License: MIT. (See LICENSE.) - Object.defineProperty(exports, "__esModule", { - value: true - }); // This regex comes from regex.coffee, and is inserted here by generate-index.js - // (run `npm run build`). - - exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyu]{1,5}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; - - exports.matchToToken = function (match) { - var token = { - type: "invalid", - value: match[0] - }; - if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace"; - return token; - }; -}); -unwrapExports(jsTokens); - -var ast = createCommonjsModule(function (module) { - /* - Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com> - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - (function () { - 'use strict'; - - function isExpression(node) { - if (node == null) { - return false; - } - - switch (node.type) { - case 'ArrayExpression': - case 'AssignmentExpression': - case 'BinaryExpression': - case 'CallExpression': - case 'ConditionalExpression': - case 'FunctionExpression': - case 'Identifier': - case 'Literal': - case 'LogicalExpression': - case 'MemberExpression': - case 'NewExpression': - case 'ObjectExpression': - case 'SequenceExpression': - case 'ThisExpression': - case 'UnaryExpression': - case 'UpdateExpression': - return true; - } - - return false; - } - - function isIterationStatement(node) { - if (node == null) { - return false; - } - - switch (node.type) { - case 'DoWhileStatement': - case 'ForInStatement': - case 'ForStatement': - case 'WhileStatement': - return true; - } - - return false; - } - - function isStatement(node) { - if (node == null) { - return false; - } - - switch (node.type) { - case 'BlockStatement': - case 'BreakStatement': - case 'ContinueStatement': - case 'DebuggerStatement': - case 'DoWhileStatement': - case 'EmptyStatement': - case 'ExpressionStatement': - case 'ForInStatement': - case 'ForStatement': - case 'IfStatement': - case 'LabeledStatement': - case 'ReturnStatement': - case 'SwitchStatement': - case 'ThrowStatement': - case 'TryStatement': - case 'VariableDeclaration': - case 'WhileStatement': - case 'WithStatement': - return true; - } - - return false; - } - - function isSourceElement(node) { - return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; - } - - function trailingStatement(node) { - switch (node.type) { - case 'IfStatement': - if (node.alternate != null) { - return node.alternate; - } - - return node.consequent; - - case 'LabeledStatement': - case 'ForStatement': - case 'ForInStatement': - case 'WhileStatement': - case 'WithStatement': - return node.body; - } - - return null; - } - - function isProblematicIfStatement(node) { - var current; - - if (node.type !== 'IfStatement') { - return false; - } - - if (node.alternate == null) { - return false; - } - - current = node.consequent; - - do { - if (current.type === 'IfStatement') { - if (current.alternate == null) { - return true; - } - } - - current = trailingStatement(current); - } while (current); - - return false; - } - - module.exports = { - isExpression: isExpression, - isStatement: isStatement, - isIterationStatement: isIterationStatement, - isSourceElement: isSourceElement, - isProblematicIfStatement: isProblematicIfStatement, - trailingStatement: trailingStatement - }; - })(); - /* vim: set sw=4 ts=4 et tw=80 : */ - -}); - -var code = createCommonjsModule(function (module) { - /* - Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com> - Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com> - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - (function () { - 'use strict'; - - var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`. - - ES5Regex = { - // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierStart: - NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, - // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierPart: - NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ - }; - ES6Regex = { - // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart: - NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/, - // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart: - NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ - }; - - function isDecimalDigit(ch) { - return 0x30 <= ch && ch <= 0x39; // 0..9 - } - - function isHexDigit(ch) { - return 0x30 <= ch && ch <= 0x39 || // 0..9 - 0x61 <= ch && ch <= 0x66 || // a..f - 0x41 <= ch && ch <= 0x46; // A..F - } - - function isOctalDigit(ch) { - return ch >= 0x30 && ch <= 0x37; // 0..7 - } // 7.2 White Space - - - NON_ASCII_WHITESPACES = [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF]; - - function isWhiteSpace(ch) { - return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; - } // 7.3 Line Terminators - - - function isLineTerminator(ch) { - return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; - } // 7.6 Identifier Names and Identifiers - - - function fromCodePoint(cp) { - if (cp <= 0xFFFF) { - return String.fromCharCode(cp); - } - - var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); - var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); - return cu1 + cu2; - } - - IDENTIFIER_START = new Array(0x80); - - for (ch = 0; ch < 0x80; ++ch) { - IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z - ch >= 0x41 && ch <= 0x5A || // A..Z - ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) - } - - IDENTIFIER_PART = new Array(0x80); - - for (ch = 0; ch < 0x80; ++ch) { - IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z - ch >= 0x41 && ch <= 0x5A || // A..Z - ch >= 0x30 && ch <= 0x39 || // 0..9 - ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) - } - - function isIdentifierStartES5(ch) { - return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); - } - - function isIdentifierPartES5(ch) { - return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); - } - - function isIdentifierStartES6(ch) { - return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); - } - - function isIdentifierPartES6(ch) { - return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); - } - - module.exports = { - isDecimalDigit: isDecimalDigit, - isHexDigit: isHexDigit, - isOctalDigit: isOctalDigit, - isWhiteSpace: isWhiteSpace, - isLineTerminator: isLineTerminator, - isIdentifierStartES5: isIdentifierStartES5, - isIdentifierPartES5: isIdentifierPartES5, - isIdentifierStartES6: isIdentifierStartES6, - isIdentifierPartES6: isIdentifierPartES6 - }; - })(); - /* vim: set sw=4 ts=4 et tw=80 : */ - -}); - -var keyword = createCommonjsModule(function (module) { - /* - Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com> - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - (function () { - 'use strict'; - - var code$$1 = code; - - function isStrictModeReservedWordES6(id) { - switch (id) { - case 'implements': - case 'interface': - case 'package': - case 'private': - case 'protected': - case 'public': - case 'static': - case 'let': - return true; - - default: - return false; - } - } - - function isKeywordES5(id, strict) { - // yield should not be treated as keyword under non-strict mode. - if (!strict && id === 'yield') { - return false; - } - - return isKeywordES6(id, strict); - } - - function isKeywordES6(id, strict) { - if (strict && isStrictModeReservedWordES6(id)) { - return true; - } - - switch (id.length) { - case 2: - return id === 'if' || id === 'in' || id === 'do'; - - case 3: - return id === 'var' || id === 'for' || id === 'new' || id === 'try'; - - case 4: - return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum'; - - case 5: - return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super'; - - case 6: - return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import'; - - case 7: - return id === 'default' || id === 'finally' || id === 'extends'; - - case 8: - return id === 'function' || id === 'continue' || id === 'debugger'; - - case 10: - return id === 'instanceof'; - - default: - return false; - } - } - - function isReservedWordES5(id, strict) { - return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); - } - - function isReservedWordES6(id, strict) { - return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); - } - - function isRestrictedWord(id) { - return id === 'eval' || id === 'arguments'; - } - - function isIdentifierNameES5(id) { - var i, iz, ch; - - if (id.length === 0) { - return false; - } - - ch = id.charCodeAt(0); - - if (!code$$1.isIdentifierStartES5(ch)) { - return false; - } - - for (i = 1, iz = id.length; i < iz; ++i) { - ch = id.charCodeAt(i); - - if (!code$$1.isIdentifierPartES5(ch)) { - return false; - } - } - - return true; - } - - function decodeUtf16(lead, trail) { - return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; - } - - function isIdentifierNameES6(id) { - var i, iz, ch, lowCh, check; - - if (id.length === 0) { - return false; - } - - check = code$$1.isIdentifierStartES6; - - for (i = 0, iz = id.length; i < iz; ++i) { - ch = id.charCodeAt(i); - - if (0xD800 <= ch && ch <= 0xDBFF) { - ++i; - - if (i >= iz) { - return false; - } - - lowCh = id.charCodeAt(i); - - if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { - return false; - } - - ch = decodeUtf16(ch, lowCh); - } - - if (!check(ch)) { - return false; - } - - check = code$$1.isIdentifierPartES6; - } - - return true; - } - - function isIdentifierES5(id, strict) { - return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); - } - - function isIdentifierES6(id, strict) { - return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); - } - - module.exports = { - isKeywordES5: isKeywordES5, - isKeywordES6: isKeywordES6, - isReservedWordES5: isReservedWordES5, - isReservedWordES6: isReservedWordES6, - isRestrictedWord: isRestrictedWord, - isIdentifierNameES5: isIdentifierNameES5, - isIdentifierNameES6: isIdentifierNameES6, - isIdentifierES5: isIdentifierES5, - isIdentifierES6: isIdentifierES6 - }; - })(); - /* vim: set sw=4 ts=4 et tw=80 : */ - -}); - -var utils = createCommonjsModule(function (module, exports) { - /* - Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com> - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - (function () { - 'use strict'; - - exports.ast = ast; - exports.code = code; - exports.keyword = keyword; - })(); - /* vim: set sw=4 ts=4 et tw=80 : */ - -}); - -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - -var escapeStringRegexp = function escapeStringRegexp(str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - return str.replace(matchOperatorsRe, '\\$&'); -}; - -var colorName = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; - -var conversions = createCommonjsModule(function (module) { - /* MIT license */ - // NOTE: conversions should only return primitive values (i.e. arrays, or - // values that give correct `typeof` results). - // do not use box values types (i.e. Number(), String(), etc.) - var reverseKeywords = {}; - - for (var key in colorName) { - if (colorName.hasOwnProperty(key)) { - reverseKeywords[colorName[key]] = key; - } - } - - var convert = module.exports = { - rgb: { - channels: 3, - labels: 'rgb' - }, - hsl: { - channels: 3, - labels: 'hsl' - }, - hsv: { - channels: 3, - labels: 'hsv' - }, - hwb: { - channels: 3, - labels: 'hwb' - }, - cmyk: { - channels: 4, - labels: 'cmyk' - }, - xyz: { - channels: 3, - labels: 'xyz' - }, - lab: { - channels: 3, - labels: 'lab' - }, - lch: { - channels: 3, - labels: 'lch' - }, - hex: { - channels: 1, - labels: ['hex'] - }, - keyword: { - channels: 1, - labels: ['keyword'] - }, - ansi16: { - channels: 1, - labels: ['ansi16'] - }, - ansi256: { - channels: 1, - labels: ['ansi256'] - }, - hcg: { - channels: 3, - labels: ['h', 'c', 'g'] - }, - apple: { - channels: 3, - labels: ['r16', 'g16', 'b16'] - }, - gray: { - channels: 1, - labels: ['gray'] - } - }; // hide .channels and .labels properties - - for (var model in convert) { - if (convert.hasOwnProperty(model)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } - - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - var channels = convert[model].channels; - var labels = convert[model].labels; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', { - value: channels - }); - Object.defineProperty(convert[model], 'labels', { - value: labels - }); - } - } - - convert.rgb.hsl = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var min = Math.min(r, g, b); - var max = Math.max(r, g, b); - var delta = max - min; - var h; - var s; - var l; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - - return [h, s * 100, l * 100]; - }; - - convert.rgb.hsv = function (rgb) { - var r = rgb[0]; - var g = rgb[1]; - var b = rgb[2]; - var min = Math.min(r, g, b); - var max = Math.max(r, g, b); - var delta = max - min; - var h; - var s; - var v; - - if (max === 0) { - s = 0; - } else { - s = delta / max * 1000 / 10; - } - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - v = max / 255 * 1000 / 10; - return [h, s, v]; - }; - - convert.rgb.hwb = function (rgb) { - var r = rgb[0]; - var g = rgb[1]; - var b = rgb[2]; - var h = convert.rgb.hsl(rgb)[0]; - var w = 1 / 255 * Math.min(r, Math.min(g, b)); - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - return [h, w * 100, b * 100]; - }; - - convert.rgb.cmyk = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var c; - var m; - var y; - var k; - k = Math.min(1 - r, 1 - g, 1 - b); - c = (1 - r - k) / (1 - k) || 0; - m = (1 - g - k) / (1 - k) || 0; - y = (1 - b - k) / (1 - k) || 0; - return [c * 100, m * 100, y * 100, k * 100]; - }; - /** - * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - * */ - - - function comparativeDistance(x, y) { - return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); - } - - convert.rgb.keyword = function (rgb) { - var reversed = reverseKeywords[rgb]; - - if (reversed) { - return reversed; - } - - var currentClosestDistance = Infinity; - var currentClosestKeyword; - - for (var keyword in colorName) { - if (colorName.hasOwnProperty(keyword)) { - var value = colorName[keyword]; // Compute comparative distance - - var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest - - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - } - - return currentClosestKeyword; - }; - - convert.keyword.rgb = function (keyword) { - return colorName[keyword]; - }; - - convert.rgb.xyz = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; // assume sRGB - - r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; - g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; - b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; - var x = r * 0.4124 + g * 0.3576 + b * 0.1805; - var y = r * 0.2126 + g * 0.7152 + b * 0.0722; - var z = r * 0.0193 + g * 0.1192 + b * 0.9505; - return [x * 100, y * 100, z * 100]; - }; - - convert.rgb.lab = function (rgb) { - var xyz = convert.rgb.xyz(rgb); - var x = xyz[0]; - var y = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b; - x /= 95.047; - y /= 100; - z /= 108.883; - x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; - y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; - z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; - l = 116 * y - 16; - a = 500 * (x - y); - b = 200 * (y - z); - return [l, a, b]; - }; - - convert.hsl.rgb = function (hsl) { - var h = hsl[0] / 360; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var t1; - var t2; - var t3; - var rgb; - var val; - - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - - t1 = 2 * l - t2; - rgb = [0, 0, 0]; - - for (var i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - - if (t3 < 0) { - t3++; - } - - if (t3 > 1) { - t3--; - } - - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } - - rgb[i] = val * 255; - } - - return rgb; - }; - - convert.hsl.hsv = function (hsl) { - var h = hsl[0]; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var smin = s; - var lmin = Math.max(l, 0.01); - var sv; - var v; - l *= 2; - s *= l <= 1 ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - v = (l + s) / 2; - sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); - return [h, sv * 100, v * 100]; - }; - - convert.hsv.rgb = function (hsv) { - var h = hsv[0] / 60; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var hi = Math.floor(h) % 6; - var f = h - Math.floor(h); - var p = 255 * v * (1 - s); - var q = 255 * v * (1 - s * f); - var t = 255 * v * (1 - s * (1 - f)); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - - case 1: - return [q, v, p]; - - case 2: - return [p, v, t]; - - case 3: - return [p, q, v]; - - case 4: - return [t, p, v]; - - case 5: - return [v, p, q]; - } - }; - - convert.hsv.hsl = function (hsv) { - var h = hsv[0]; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var vmin = Math.max(v, 0.01); - var lmin; - var sl; - var l; - l = (2 - s) * v; - lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= lmin <= 1 ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - return [h, sl * 100, l * 100]; - }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb - - - convert.hwb.rgb = function (hwb) { - var h = hwb[0] / 360; - var wh = hwb[1] / 100; - var bl = hwb[2] / 100; - var ratio = wh + bl; - var i; - var v; - var f; - var n; // wh + bl cant be > 1 - - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - - i = Math.floor(6 * h); - v = 1 - bl; - f = 6 * h - i; - - if ((i & 0x01) !== 0) { - f = 1 - f; - } - - n = wh + f * (v - wh); // linear interpolation - - var r; - var g; - var b; - - switch (i) { - default: - case 6: - case 0: - r = v; - g = n; - b = wh; - break; - - case 1: - r = n; - g = v; - b = wh; - break; - - case 2: - r = wh; - g = v; - b = n; - break; - - case 3: - r = wh; - g = n; - b = v; - break; - - case 4: - r = n; - g = wh; - b = v; - break; - - case 5: - r = v; - g = wh; - b = n; - break; - } - - return [r * 255, g * 255, b * 255]; - }; - - convert.cmyk.rgb = function (cmyk) { - var c = cmyk[0] / 100; - var m = cmyk[1] / 100; - var y = cmyk[2] / 100; - var k = cmyk[3] / 100; - var r; - var g; - var b; - r = 1 - Math.min(1, c * (1 - k) + k); - g = 1 - Math.min(1, m * (1 - k) + k); - b = 1 - Math.min(1, y * (1 - k) + k); - return [r * 255, g * 255, b * 255]; - }; - - convert.xyz.rgb = function (xyz) { - var x = xyz[0] / 100; - var y = xyz[1] / 100; - var z = xyz[2] / 100; - var r; - var g; - var b; - r = x * 3.2406 + y * -1.5372 + z * -0.4986; - g = x * -0.9689 + y * 1.8758 + z * 0.0415; - b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB - - r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; - g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; - b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92; - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); - return [r * 255, g * 255, b * 255]; - }; - - convert.xyz.lab = function (xyz) { - var x = xyz[0]; - var y = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b; - x /= 95.047; - y /= 100; - z /= 108.883; - x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; - y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; - z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; - l = 116 * y - 16; - a = 500 * (x - y); - b = 200 * (y - z); - return [l, a, b]; - }; - - convert.lab.xyz = function (lab) { - var l = lab[0]; - var a = lab[1]; - var b = lab[2]; - var x; - var y; - var z; - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; - var y2 = Math.pow(y, 3); - var x2 = Math.pow(x, 3); - var z2 = Math.pow(z, 3); - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; - x *= 95.047; - y *= 100; - z *= 108.883; - return [x, y, z]; - }; - - convert.lab.lch = function (lab) { - var l = lab[0]; - var a = lab[1]; - var b = lab[2]; - var hr; - var h; - var c; - hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - - if (h < 0) { - h += 360; - } - - c = Math.sqrt(a * a + b * b); - return [l, c, h]; - }; - - convert.lch.lab = function (lch) { - var l = lch[0]; - var c = lch[1]; - var h = lch[2]; - var a; - var b; - var hr; - hr = h / 360 * 2 * Math.PI; - a = c * Math.cos(hr); - b = c * Math.sin(hr); - return [l, a, b]; - }; - - convert.rgb.ansi16 = function (args) { - var r = args[0]; - var g = args[1]; - var b = args[2]; - var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization - - value = Math.round(value / 50); - - if (value === 0) { - return 30; - } - - var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); - - if (value === 2) { - ansi += 60; - } - - return ansi; - }; - - convert.hsv.ansi16 = function (args) { - // optimization here; we already know the value and don't need to get - // it converted for us. - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); - }; - - convert.rgb.ansi256 = function (args) { - var r = args[0]; - var g = args[1]; - var b = args[2]; // we use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - - if (r === g && g === b) { - if (r < 8) { - return 16; - } - - if (r > 248) { - return 231; - } - - return Math.round((r - 8) / 247 * 24) + 232; - } - - var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); - return ansi; - }; - - convert.ansi16.rgb = function (args) { - var color = args % 10; // handle greyscale - - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - - color = color / 10.5 * 255; - return [color, color, color]; - } - - var mult = (~~(args > 50) + 1) * 0.5; - var r = (color & 1) * mult * 255; - var g = (color >> 1 & 1) * mult * 255; - var b = (color >> 2 & 1) * mult * 255; - return [r, g, b]; - }; - - convert.ansi256.rgb = function (args) { - // handle greyscale - if (args >= 232) { - var c = (args - 232) * 10 + 8; - return [c, c, c]; - } - - args -= 16; - var rem; - var r = Math.floor(args / 36) / 5 * 255; - var g = Math.floor((rem = args % 36) / 6) / 5 * 255; - var b = rem % 6 / 5 * 255; - return [r, g, b]; - }; - - convert.rgb.hex = function (args) { - var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); - var string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; - }; - - convert.hex.rgb = function (args) { - var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - - if (!match) { - return [0, 0, 0]; - } - - var colorString = match[0]; - - if (match[0].length === 3) { - colorString = colorString.split('').map(function (char) { - return char + char; - }).join(''); - } - - var integer = parseInt(colorString, 16); - var r = integer >> 16 & 0xFF; - var g = integer >> 8 & 0xFF; - var b = integer & 0xFF; - return [r, g, b]; - }; - - convert.rgb.hcg = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var max = Math.max(Math.max(r, g), b); - var min = Math.min(Math.min(r, g), b); - var chroma = max - min; - var grayscale; - var hue; - - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } - - if (chroma <= 0) { - hue = 0; - } else if (max === r) { - hue = (g - b) / chroma % 6; - } else if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma + 4; - } - - hue /= 6; - hue %= 1; - return [hue * 360, chroma * 100, grayscale * 100]; - }; - - convert.hsl.hcg = function (hsl) { - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var c = 1; - var f = 0; - - if (l < 0.5) { - c = 2.0 * s * l; - } else { - c = 2.0 * s * (1.0 - l); - } - - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } - - return [hsl[0], c * 100, f * 100]; - }; - - convert.hsv.hcg = function (hsv) { - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var c = s * v; - var f = 0; - - if (c < 1.0) { - f = (v - c) / (1 - c); - } - - return [hsv[0], c * 100, f * 100]; - }; - - convert.hcg.rgb = function (hcg) { - var h = hcg[0] / 360; - var c = hcg[1] / 100; - var g = hcg[2] / 100; - - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } - - var pure = [0, 0, 0]; - var hi = h % 1 * 6; - var v = hi % 1; - var w = 1 - v; - var mg = 0; - - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; - pure[1] = v; - pure[2] = 0; - break; - - case 1: - pure[0] = w; - pure[1] = 1; - pure[2] = 0; - break; - - case 2: - pure[0] = 0; - pure[1] = 1; - pure[2] = v; - break; - - case 3: - pure[0] = 0; - pure[1] = w; - pure[2] = 1; - break; - - case 4: - pure[0] = v; - pure[1] = 0; - pure[2] = 1; - break; - - default: - pure[0] = 1; - pure[1] = 0; - pure[2] = w; - } - - mg = (1.0 - c) * g; - return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; - }; - - convert.hcg.hsv = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - var v = c + g * (1.0 - c); - var f = 0; - - if (v > 0.0) { - f = c / v; - } - - return [hcg[0], f * 100, v * 100]; - }; - - convert.hcg.hsl = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - var l = g * (1.0 - c) + 0.5 * c; - var s = 0; - - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } - - return [hcg[0], s * 100, l * 100]; - }; - - convert.hcg.hwb = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - var v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; - }; - - convert.hwb.hcg = function (hwb) { - var w = hwb[1] / 100; - var b = hwb[2] / 100; - var v = 1 - b; - var c = v - w; - var g = 0; - - if (c < 1) { - g = (v - c) / (1 - c); - } - - return [hwb[0], c * 100, g * 100]; - }; - - convert.apple.rgb = function (apple) { - return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; - }; - - convert.rgb.apple = function (rgb) { - return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; - }; - - convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; - }; - - convert.gray.hsl = convert.gray.hsv = function (args) { - return [0, 0, args[0]]; - }; - - convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; - }; - - convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; - }; - - convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; - }; - - convert.gray.hex = function (gray) { - var val = Math.round(gray[0] / 100 * 255) & 0xFF; - var integer = (val << 16) + (val << 8) + val; - var string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; - }; - - convert.rgb.gray = function (rgb) { - var val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; - }; -}); - -/* - this function routes a model to all other models. - - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). - - conversions that are not possible simply are not included. -*/ -// https://jsperf.com/object-keys-vs-for-in-with-closure/3 - -var models$1 = Object.keys(conversions); - -function buildGraph() { - var graph = {}; - - for (var len = models$1.length, i = 0; i < len; i++) { - graph[models$1[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - - return graph; -} // https://en.wikipedia.org/wiki/Breadth-first_search - - -function deriveBFS(fromModel) { - var graph = buildGraph(); - var queue = [fromModel]; // unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - var current = queue.pop(); - var adjacents = Object.keys(conversions[current]); - - for (var len = adjacents.length, i = 0; i < len; i++) { - var adjacent = adjacents[i]; - var node = graph[adjacent]; - - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } - - return graph; -} - -function link(from, to) { - return function (args) { - return to(from(args)); - }; -} - -function wrapConversion(toModel, graph) { - var path = [graph[toModel].parent, toModel]; - var fn = conversions[graph[toModel].parent][toModel]; - var cur = graph[toModel].parent; - - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; -} - -var route = function route(fromModel) { - var graph = deriveBFS(fromModel); - var conversion = {}; - var models = Object.keys(graph); - - for (var len = models.length, i = 0; i < len; i++) { - var toModel = models[i]; - var node = graph[toModel]; - - if (node.parent === null) { - // no possible conversion, or this node is the source model. - continue; - } - - conversion[toModel] = wrapConversion(toModel, graph); - } - - return conversion; -}; - -var convert = {}; -var models = Object.keys(conversions); - -function wrapRaw(fn) { - var wrappedFn = function wrappedFn(args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } - - return fn(args); - }; // preserve .conversion property if there is one - - - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -function wrapRounded(fn) { - var wrappedFn = function wrappedFn(args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } - - var result = fn(args); // we're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - - if (_typeof(result) === 'object') { - for (var len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - - return result; - }; // preserve .conversion property if there is one - - - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -models.forEach(function (fromModel) { - convert[fromModel] = {}; - Object.defineProperty(convert[fromModel], 'channels', { - value: conversions[fromModel].channels - }); - Object.defineProperty(convert[fromModel], 'labels', { - value: conversions[fromModel].labels - }); - var routes = route(fromModel); - var routeModels = Object.keys(routes); - routeModels.forEach(function (toModel) { - var fn = routes[toModel]; - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); -var colorConvert = convert; - -var ansiStyles = createCommonjsModule(function (module) { - 'use strict'; - - var wrapAnsi16 = function wrapAnsi16(fn, offset) { - return function () { - var code = fn.apply(colorConvert, arguments); - return "\x1B[".concat(code + offset, "m"); - }; - }; - - var wrapAnsi256 = function wrapAnsi256(fn, offset) { - return function () { - var code = fn.apply(colorConvert, arguments); - return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); - }; - }; - - var wrapAnsi16m = function wrapAnsi16m(fn, offset) { - return function () { - var rgb = fn.apply(colorConvert, arguments); - return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); - }; - }; - - function assembleStyles() { - var codes = new Map(); - var styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; // Fix humans - - styles.color.grey = styles.color.gray; - - var _arr = Object.keys(styles); - - for (var _i = 0; _i < _arr.length; _i++) { - var groupName = _arr[_i]; - var group = styles[groupName]; - - var _arr3 = Object.keys(group); - - for (var _i3 = 0; _i3 < _arr3.length; _i3++) { - var styleName = _arr3[_i3]; - var style = group[styleName]; - styles[styleName] = { - open: "\x1B[".concat(style[0], "m"), - close: "\x1B[".concat(style[1], "m") - }; - group[styleName] = styles[styleName]; - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - } - - var ansi2ansi = function ansi2ansi(n) { - return n; - }; - - var rgb2rgb = function rgb2rgb(r, g, b) { - return [r, g, b]; - }; - - styles.color.close = "\x1B[39m"; - styles.bgColor.close = "\x1B[49m"; - styles.color.ansi = { - ansi: wrapAnsi16(ansi2ansi, 0) - }; - styles.color.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 0) - }; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; - styles.bgColor.ansi = { - ansi: wrapAnsi16(ansi2ansi, 10) - }; - styles.bgColor.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 10) - }; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; - - var _arr2 = Object.keys(colorConvert); - - for (var _i2 = 0; _i2 < _arr2.length; _i2++) { - var key = _arr2[_i2]; - - if (_typeof(colorConvert[key]) !== 'object') { - continue; - } - - var suite = colorConvert[key]; - - if (key === 'ansi16') { - key = 'ansi'; - } - - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } - - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } - - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); - } - } - - return styles; - } // Make the export immutable - - - Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles - }); -}); - -var os = { - EOL: "\n" -}; - -var os$1 = Object.freeze({ - default: os -}); - -var hasFlag = createCommonjsModule(function (module) { - 'use strict'; - - module.exports = function (flag, argv$$1) { - argv$$1 = argv$$1 || process.argv; - var prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; - var pos = argv$$1.indexOf(prefix + flag); - var terminatorPos = argv$$1.indexOf('--'); - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); - }; -}); - -var require$$1$1 = ( os$1 && os ) || os$1; - -var env$1 = process.env; -var forceColor; - -if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { - forceColor = true; -} - -if ('FORCE_COLOR' in env$1) { - forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0; -} - -function translateLevel(level) { - if (level === 0) { - return false; - } - - return { - level: level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} - -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } - - if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } - - var min = forceColor ? 1 : 0; - - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - var osRelease = require$$1$1.release().split('.'); - - if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env$1) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) { - return sign in env$1; - }) || env$1.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env$1) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; - } - - if (env$1.COLORTERM === 'truecolor') { - return 3; - } - - if ('TERM_PROGRAM' in env$1) { - var version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env$1.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env$1.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { - return 1; - } - - if ('COLORTERM' in env$1) { - return 1; - } - - if (env$1.TERM === 'dumb') { - return min; - } - - return min; -} - -function getSupportLevel(stream) { - var level = supportsColor(stream); - return translateLevel(level); -} - -var supportsColor_1 = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) -}; - -var templates = createCommonjsModule(function (module) { - 'use strict'; - - var TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; - var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; - var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; - var ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; - var ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', "\x1B"], ['a', "\x07"]]); - - function unescape(c) { - if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } - - return ESCAPES.get(c) || c; - } - - function parseArguments(name, args) { - var results = []; - var chunks = args.trim().split(/\s*,\s*/g); - var matches; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var chunk = _step.value; - - if (!isNaN(chunk)) { - results.push(Number(chunk)); - } else if (matches = chunk.match(STRING_REGEX)) { - results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) { - return escape ? unescape(escape) : chr; - })); - } else { - throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - return results; - } - - function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; - var results = []; - var matches; - - while ((matches = STYLE_REGEX.exec(style)) !== null) { - var name = matches[1]; - - if (matches[2]) { - var args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } - - return results; - } - - function buildStyle(chalk, styles) { - var enabled = {}; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var layer = _step2.value; - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - - try { - for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var style = _step3.value; - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return != null) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return != null) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - - var current = chalk; - - var _arr = Object.keys(enabled); - - for (var _i = 0; _i < _arr.length; _i++) { - var styleName = _arr[_i]; - - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error("Unknown Chalk style: ".concat(styleName)); - } - - if (enabled[styleName].length > 0) { - current = current[styleName].apply(current, enabled[styleName]); - } else { - current = current[styleName]; - } - } - } - - return current; - } - - module.exports = function (chalk, tmp) { - var styles = []; - var chunks = []; - var chunk = []; // eslint-disable-next-line max-params - - tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) { - if (escapeChar) { - chunk.push(unescape(escapeChar)); - } else if (style) { - var str = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); - styles.push({ - inverse: inverse, - styles: parseStyle(style) - }); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } - - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(chr); - } - }); - chunks.push(chunk.join('')); - - if (styles.length > 0) { - var errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); - throw new Error(errMsg); - } - - return chunks.join(''); - }; -}); - -var chalk = createCommonjsModule(function (module) { - 'use strict'; - - var stdoutColor = supportsColor_1.stdout; - var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping - - var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such - - var skipModels = new Set(['gray']); - var styles = Object.create(null); - - function applyOptions(obj, options) { - options = options || {}; // Detect level if not set manually - - var scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; - } - - function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - var _chalk = {}; - applyOptions(_chalk, options); - - _chalk.template = function () { - var args = [].slice.call(arguments); - return chalkTag.apply(null, [_chalk.template].concat(args)); - }; - - Object.setPrototypeOf(_chalk, Chalk.prototype); - Object.setPrototypeOf(_chalk.template, _chalk); - _chalk.template.constructor = Chalk; - return _chalk.template; - } - - applyOptions(this, options); - } // Use bright blue on Windows as the normal blue color is illegible - - - if (isSimpleWindowsTerm) { - ansiStyles.blue.open = "\x1B[94m"; - } - - var _arr = Object.keys(ansiStyles); - - var _loop = function _loop() { - var key = _arr[_i]; - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - styles[key] = { - get: function get() { - var codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; - }; - - for (var _i = 0; _i < _arr.length; _i++) { - _loop(); - } - - styles.visible = { - get: function get() { - return build.call(this, this._styles || [], true, 'visible'); - } - }; - ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); - - var _arr2 = Object.keys(ansiStyles.color.ansi); - - var _loop2 = function _loop2() { - var model = _arr2[_i2]; - - if (skipModels.has(model)) { - return "continue"; - } - - styles[model] = { - get: function get() { - var level = this.level; - return function () { - var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - var codes = { - open: open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; - }; - - for (var _i2 = 0; _i2 < _arr2.length; _i2++) { - var _ret = _loop2(); - - if (_ret === "continue") continue; - } - - ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); - - var _arr3 = Object.keys(ansiStyles.bgColor.ansi); - - var _loop3 = function _loop3() { - var model = _arr3[_i3]; - - if (skipModels.has(model)) { - return "continue"; - } - - var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get: function get() { - var level = this.level; - return function () { - var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - var codes = { - open: open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; - }; - - for (var _i3 = 0; _i3 < _arr3.length; _i3++) { - var _ret2 = _loop3(); - - if (_ret2 === "continue") continue; - } - - var proto = Object.defineProperties(function () {}, styles); - - function build(_styles, _empty, key) { - var builder = function builder() { - return applyStyle.apply(builder, arguments); - }; - - builder._styles = _styles; - builder._empty = _empty; - var self = this; - Object.defineProperty(builder, 'level', { - enumerable: true, - get: function get() { - return self.level; - }, - set: function set(level) { - self.level = level; - } - }); - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get: function get() { - return self.enabled; - }, - set: function set(enabled) { - self.enabled = enabled; - } - }); // See below for fix regarding invisible grey/dim combination on Windows - - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - - builder.__proto__ = proto; // eslint-disable-line no-proto - - return builder; - } - - function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - var args = arguments; - var argsLen = args.length; - var str = String(arguments[0]); - - if (argsLen === 0) { - return ''; - } - - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (var a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - - - var originalDim = ansiStyles.dim.open; - - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } - - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var code = _step.value; - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - - str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); - } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - ansiStyles.dim.open = originalDim; - return str; - } - - function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } - - var args = [].slice.call(arguments, 2); - var parts = [strings.raw[0]]; - - for (var i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } - - return templates(chalk, parts.join('')); - } - - Object.defineProperties(Chalk.prototype, styles); - module.exports = Chalk(); // eslint-disable-line new-cap - - module.exports.supportsColor = stdoutColor; - module.exports.default = module.exports; // For TypeScript -}); - -var lib$2 = createCommonjsModule(function (module, exports) { - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.shouldHighlight = shouldHighlight; - exports.getChalk = getChalk; - exports.default = highlight; - - function _jsTokens() { - var data = _interopRequireWildcard(jsTokens); - - _jsTokens = function _jsTokens() { - return data; - }; - - return data; - } - - function _esutils() { - var data = _interopRequireDefault(utils); - - _esutils = function _esutils() { - return data; - }; - - return data; - } - - function _chalk() { - var data = _interopRequireDefault(chalk); - - _chalk = function _chalk() { - return data; - }; - - return data; - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } else { - var newObj = {}; - - if (obj != null) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; - - if (desc.get || desc.set) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - } - - newObj.default = obj; - return newObj; - } - } - - function getDefs(chalk$$1) { - return { - keyword: chalk$$1.cyan, - capitalized: chalk$$1.yellow, - jsx_tag: chalk$$1.yellow, - punctuator: chalk$$1.yellow, - number: chalk$$1.magenta, - string: chalk$$1.green, - regex: chalk$$1.magenta, - comment: chalk$$1.grey, - invalid: chalk$$1.white.bgRed.bold - }; - } - - var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; - var JSX_TAG = /^[a-z][\w-]*$/i; - var BRACKET = /^[()[\]{}]$/; - - function getTokenType(match) { - var _match$slice = match.slice(-2), - offset = _match$slice[0], - text = _match$slice[1]; - - var token = (0, _jsTokens().matchToToken)(match); - - if (token.type === "name") { - if (_esutils().default.keyword.isReservedWordES6(token.value)) { - return "keyword"; - } - - if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) { - return "jsx_tag"; - } - - if (token.value[0] !== token.value[0].toLowerCase()) { - return "capitalized"; - } - } - - if (token.type === "punctuator" && BRACKET.test(token.value)) { - return "bracket"; - } - - if (token.type === "invalid" && (token.value === "@" || token.value === "#")) { - return "punctuator"; - } - - return token.type; - } - - function highlightTokens(defs, text) { - return text.replace(_jsTokens().default, function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - var type = getTokenType(args); - var colorize = defs[type]; - - if (colorize) { - return args[0].split(NEWLINE).map(function (str) { - return colorize(str); - }).join("\n"); - } else { - return args[0]; - } - }); - } - - function shouldHighlight(options) { - return _chalk().default.supportsColor || options.forceColor; - } - - function getChalk(options) { - var chalk$$1 = _chalk().default; - - if (options.forceColor) { - chalk$$1 = new (_chalk().default.constructor)({ - enabled: true, - level: 1 - }); - } - - return chalk$$1; - } - - function highlight(code, options) { - if (options === void 0) { - options = {}; - } - - if (shouldHighlight(options)) { - var chalk$$1 = getChalk(options); - var defs = getDefs(chalk$$1); - return highlightTokens(defs, code); - } else { - return code; - } - } -}); -unwrapExports(lib$2); - -var lib$1 = createCommonjsModule(function (module, exports) { - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.codeFrameColumns = codeFrameColumns; - exports.default = _default; - - function _highlight() { - var data = _interopRequireWildcard(lib$2); - - _highlight = function _highlight() { - return data; - }; - - return data; - } - - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } else { - var newObj = {}; - - if (obj != null) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; - - if (desc.get || desc.set) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - } - - newObj.default = obj; - return newObj; - } - } - - var deprecationWarningShown = false; - - function getDefs(chalk) { - return { - gutter: chalk.grey, - marker: chalk.red.bold, - message: chalk.red.bold - }; - } - - var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; - - function getMarkerLines(loc, source, opts) { - var startLoc = Object.assign({}, { - column: 0, - line: -1 - }, loc.start); - var endLoc = Object.assign({}, startLoc, loc.end); - - var _ref = opts || {}, - _ref$linesAbove = _ref.linesAbove, - linesAbove = _ref$linesAbove === void 0 ? 2 : _ref$linesAbove, - _ref$linesBelow = _ref.linesBelow, - linesBelow = _ref$linesBelow === void 0 ? 3 : _ref$linesBelow; - - var startLine = startLoc.line; - var startColumn = startLoc.column; - var endLine = endLoc.line; - var endColumn = endLoc.column; - var start = Math.max(startLine - (linesAbove + 1), 0); - var end = Math.min(source.length, endLine + linesBelow); - - if (startLine === -1) { - start = 0; - } - - if (endLine === -1) { - end = source.length; - } - - var lineDiff = endLine - startLine; - var markerLines = {}; - - if (lineDiff) { - for (var i = 0; i <= lineDiff; i++) { - var lineNumber = i + startLine; - - if (!startColumn) { - markerLines[lineNumber] = true; - } else if (i === 0) { - var sourceLength = source[lineNumber - 1].length; - markerLines[lineNumber] = [startColumn, sourceLength - startColumn]; - } else if (i === lineDiff) { - markerLines[lineNumber] = [0, endColumn]; - } else { - var _sourceLength = source[lineNumber - i].length; - markerLines[lineNumber] = [0, _sourceLength]; - } - } - } else { - if (startColumn === endColumn) { - if (startColumn) { - markerLines[startLine] = [startColumn, 0]; - } else { - markerLines[startLine] = true; - } - } else { - markerLines[startLine] = [startColumn, endColumn - startColumn]; - } - } - - return { - start: start, - end: end, - markerLines: markerLines - }; - } - - function codeFrameColumns(rawLines, loc, opts) { - if (opts === void 0) { - opts = {}; - } - - var highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts); - var chalk = (0, _highlight().getChalk)(opts); - var defs = getDefs(chalk); - - var maybeHighlight = function maybeHighlight(chalkFn, string) { - return highlighted ? chalkFn(string) : string; - }; - - if (highlighted) rawLines = (0, _highlight().default)(rawLines, opts); - var lines = rawLines.split(NEWLINE); - - var _getMarkerLines = getMarkerLines(loc, lines, opts), - start = _getMarkerLines.start, - end = _getMarkerLines.end, - markerLines = _getMarkerLines.markerLines; - - var hasColumns = loc.start && typeof loc.start.column === "number"; - var numberMaxWidth = String(end).length; - var frame = lines.slice(start, end).map(function (line, index) { - var number = start + 1 + index; - var paddedNumber = (" " + number).slice(-numberMaxWidth); - var gutter = " " + paddedNumber + " | "; - var hasMarker = markerLines[number]; - var lastMarkerLine = !markerLines[number + 1]; - - if (hasMarker) { - var markerLine = ""; - - if (Array.isArray(hasMarker)) { - var markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); - var numberOfMarkers = hasMarker[1] || 1; - markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); - - if (lastMarkerLine && opts.message) { - markerLine += " " + maybeHighlight(defs.message, opts.message); - } - } - - return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); - } else { - return " " + maybeHighlight(defs.gutter, gutter) + line; - } - }).join("\n"); - - if (opts.message && !hasColumns) { - frame = "" + " ".repeat(numberMaxWidth + 1) + opts.message + "\n" + frame; - } - - if (highlighted) { - return chalk.reset(frame); - } else { - return frame; - } - } - - function _default(rawLines, lineNumber, colNumber, opts) { - if (opts === void 0) { - opts = {}; - } - - if (!deprecationWarningShown) { - deprecationWarningShown = true; - var message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; - - if (process.emitWarning) { - process.emitWarning(message, "DeprecationWarning"); - } else { - var deprecationError = new Error(message); - deprecationError.name = "DeprecationWarning"; - console.warn(new Error(message)); - } - } - - colNumber = Math.max(colNumber, 0); - var location = { - start: { - column: colNumber, - line: lineNumber - } - }; - return codeFrameColumns(rawLines, location, opts); - } -}); -unwrapExports(lib$1); - -var path = ( _shim_path$1 && _shim_path ) || _shim_path$1; - -var ConfigError$1 = errors.ConfigError; -var locStart = loc.locStart; -var locEnd = loc.locEnd; // Use defineProperties()/getOwnPropertyDescriptor() to prevent -// triggering the parsers getters. - -var ownNames = Object.getOwnPropertyNames; -var ownDescriptor = Object.getOwnPropertyDescriptor; - -function getParsers(options) { - var parsers = {}; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = options.plugins[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var plugin = _step.value; - - if (!plugin.parsers) { - continue; - } - - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = ownNames(plugin.parsers)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var name = _step2.value; - Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name)); - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return != null) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - return parsers; -} - -function resolveParser$1(opts, parsers) { - parsers = parsers || getParsers(opts); - - if (typeof opts.parser === "function") { - // Custom parser API always works with JavaScript. - return { - parse: opts.parser, - astFormat: "estree", - locStart: locStart, - locEnd: locEnd - }; - } - - if (typeof opts.parser === "string") { - if (parsers.hasOwnProperty(opts.parser)) { - return parsers[opts.parser]; - } - - try { - return { - parse: require(path.resolve(process.cwd(), opts.parser)), - astFormat: "estree", - locStart: locStart, - locEnd: locEnd - }; - } catch (err) { - /* istanbul ignore next */ - throw new ConfigError$1("Couldn't resolve parser \"".concat(opts.parser, "\"")); - } - } -} - -function parse$2(text, opts) { - var parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call - // the parsers getters when actually calling the parser `parse` function. - - var parsersForCustomParserApi = Object.keys(parsers).reduce(function (object, parserName) { - return Object.defineProperty(object, parserName, { - enumerable: true, - get: function get() { - return parsers[parserName].parse; - } - }); - }, {}); - var parser = resolveParser$1(opts, parsers); - - try { - if (parser.preprocess) { - text = parser.preprocess(text, opts); - } - - return { - text: text, - ast: parser.parse(text, parsersForCustomParserApi, opts) - }; - } catch (error) { - var loc$$1 = error.loc; - - if (loc$$1) { - var codeFrame = lib$1; - error.codeFrame = codeFrame.codeFrameColumns(text, loc$$1, { - highlightCode: true - }); - error.message += "\n" + error.codeFrame; - throw error; - } - /* istanbul ignore next */ - - - throw error.stack; - } -} - -var parser = { - parse: parse$2, - resolveParser: resolveParser$1 -}; - -var UndefinedParserError = errors.UndefinedParserError; -var getSupportInfo$1 = support.getSupportInfo; -var resolveParser = parser.resolveParser; -var hiddenDefaults = { - astFormat: "estree", - printer: {}, - originalText: undefined, - locStart: null, - locEnd: null -}; // Copy options and fill in default values. - -function normalize(options, opts) { - opts = opts || {}; - var rawOptions = Object.assign({}, options); - var supportOptions = getSupportInfo$1(null, { - plugins: options.plugins, - showUnreleased: true, - showDeprecated: true - }).options; - var defaults = supportOptions.reduce(function (reduced, optionInfo) { - return Object.assign(reduced, _defineProperty({}, optionInfo.name, optionInfo.default)); - }, Object.assign({}, hiddenDefaults)); - - if (!rawOptions.parser) { - if (!rawOptions.filepath) { - var logger = opts.logger || console; - logger.warn("No parser and no filepath given, using 'babylon' the parser now " + "but this will throw an error in the future. " + "Please specify a parser or a filepath so one can be inferred."); - rawOptions.parser = "babylon"; - } else { - rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins); - - if (!rawOptions.parser) { - throw new UndefinedParserError("No parser could be inferred for file: ".concat(rawOptions.filepath)); - } - } - } - - var parser$$1 = resolveParser(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(function (x) { - return x.name === "parser"; - })], { - passThrough: true, - logger: false - })); - rawOptions.astFormat = parser$$1.astFormat; - rawOptions.locEnd = parser$$1.locEnd; - rawOptions.locStart = parser$$1.locStart; - var plugin = getPlugin(rawOptions); - rawOptions.printer = plugin.printers[rawOptions.astFormat]; - var pluginDefaults = supportOptions.filter(function (optionInfo) { - return optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name]; - }).reduce(function (reduced, optionInfo) { - return Object.assign(reduced, _defineProperty({}, optionInfo.name, optionInfo.pluginDefaults[plugin.name])); - }, {}); - var mixedDefaults = Object.assign({}, defaults, pluginDefaults); - Object.keys(mixedDefaults).forEach(function (k) { - if (rawOptions[k] == null) { - rawOptions[k] = mixedDefaults[k]; - } - }); - - if (rawOptions.parser === "json") { - rawOptions.trailingComma = "none"; - } - - return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({ - passThrough: Object.keys(hiddenDefaults) - }, opts)); -} - -function getPlugin(options) { - var astFormat = options.astFormat; - - if (!astFormat) { - throw new Error("getPlugin() requires astFormat to be set"); - } - - var printerPlugin = options.plugins.find(function (plugin) { - return plugin.printers && plugin.printers[astFormat]; - }); - - if (!printerPlugin) { - throw new Error("Couldn't find plugin for AST format \"".concat(astFormat, "\"")); - } - - return printerPlugin; -} - -function inferParser(filepath, plugins) { - var filepathParts = normalizePath(filepath).split("/"); - var filename = filepathParts[filepathParts.length - 1].toLowerCase(); - var language = getSupportInfo$1(null, { - plugins: plugins - }).languages.find(function (language) { - return language.since !== null && (language.extensions && language.extensions.some(function (extension) { - return filename.endsWith(extension); - }) || language.filenames && language.filenames.find(function (name) { - return name.toLowerCase() === filename; - })); - }); - return language && language.parsers[0]; -} - -var options = { - normalize: normalize, - hiddenDefaults: hiddenDefaults, - inferParser: inferParser -}; - -function massageAST(ast, options, parent) { - if (Array.isArray(ast)) { - return ast.map(function (e) { - return massageAST(e, options, parent); - }).filter(function (e) { - return e; - }); - } - - if (!ast || _typeof(ast) !== "object") { - return ast; - } - - var newObj = {}; - - var _arr = Object.keys(ast); - - for (var _i = 0; _i < _arr.length; _i++) { - var key = _arr[_i]; - - if (typeof ast[key] !== "function") { - newObj[key] = massageAST(ast[key], options, ast); - } - } - - if (options.printer.massageAstNode) { - var result = options.printer.massageAstNode(ast, newObj, parent); - - if (result === null) { - return undefined; - } - - if (result) { - return result; - } - } - - return newObj; -} - -var massageAst = massageAST; - -function assert() {} - -assert.ok = function () {}; - -assert.strictEqual = function () {}; - - - -var assert$2 = Object.freeze({ - default: assert -}); - -function concat$1(parts) { - return { - type: "concat", - parts: parts - }; -} - -function indent$1(contents) { - return { - type: "indent", - contents: contents - }; -} - -function align(n, contents) { - return { - type: "align", - contents: contents, - n: n - }; -} - -function group(contents, opts) { - opts = opts || {}; - - return { - type: "group", - id: opts.id, - contents: contents, - break: !!opts.shouldBreak, - expandedStates: opts.expandedStates - }; -} - -function dedentToRoot(contents) { - return align(-Infinity, contents); -} - -function markAsRoot(contents) { - return align({ - type: "root" - }, contents); -} - -function dedent$1(contents) { - return align(-1, contents); -} - -function conditionalGroup(states, opts) { - return group(states[0], Object.assign(opts || {}, { - expandedStates: states - })); -} - -function fill(parts) { - return { - type: "fill", - parts: parts - }; -} - -function ifBreak(breakContents, flatContents, opts) { - opts = opts || {}; - - return { - type: "if-break", - breakContents: breakContents, - flatContents: flatContents, - groupId: opts.groupId - }; -} - -function lineSuffix$1(contents) { - return { - type: "line-suffix", - contents: contents - }; -} - -var lineSuffixBoundary = { - type: "line-suffix-boundary" -}; -var breakParent$1 = { - type: "break-parent" -}; -var line$2 = { - type: "line" -}; -var softline = { - type: "line", - soft: true -}; -var hardline$1 = concat$1([{ - type: "line", - hard: true -}, breakParent$1]); -var literalline = concat$1([{ - type: "line", - hard: true, - literal: true -}, breakParent$1]); -var cursor$1 = { - type: "cursor", - placeholder: Symbol("cursor") -}; - -function join$1(sep, arr) { - var res = []; - - for (var i = 0; i < arr.length; i++) { - if (i !== 0) { - res.push(sep); - } - - res.push(arr[i]); - } - - return concat$1(res); -} - -function addAlignmentToDoc(doc, size, tabWidth) { - var aligned = doc; - - if (size > 0) { - // Use indent to add tabs for all the levels of tabs we need - for (var i = 0; i < Math.floor(size / tabWidth); ++i) { - aligned = indent$1(aligned); - } // Use align for all the spaces that are needed - - - aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current - // indentation, so we use -Infinity to reset the indentation to 0 - - aligned = align(-Infinity, aligned); - } - - return aligned; -} - -var docBuilders = { - concat: concat$1, - join: join$1, - line: line$2, - softline: softline, - hardline: hardline$1, - literalline: literalline, - group: group, - conditionalGroup: conditionalGroup, - fill: fill, - lineSuffix: lineSuffix$1, - lineSuffixBoundary: lineSuffixBoundary, - cursor: cursor$1, - breakParent: breakParent$1, - ifBreak: ifBreak, - indent: indent$1, - align: align, - addAlignmentToDoc: addAlignmentToDoc, - markAsRoot: markAsRoot, - dedentToRoot: dedentToRoot, - dedent: dedent$1 -}; - -var ansiRegex = createCommonjsModule(function (module) { - 'use strict'; - - module.exports = function () { - var pattern = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)", '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'].join('|'); - return new RegExp(pattern, 'g'); - }; -}); - -var stripAnsi = function stripAnsi(input) { - return typeof input === 'string' ? input.replace(ansiRegex(), '') : input; -}; - -var isFullwidthCodePoint = createCommonjsModule(function (module) { - 'use strict'; - /* eslint-disable yoda */ - - module.exports = function (x) { - if (Number.isNaN(x)) { - return false; - } // code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - - - if (x >= 0x1100 && (x <= 0x115f || // Hangul Jamo - x === 0x2329 || // LEFT-POINTING ANGLE BRACKET - x === 0x232a || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - 0x2e80 <= x && x <= 0x3247 && x !== 0x303f || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - 0x3250 <= x && x <= 0x4dbf || // CJK Unified Ideographs .. Yi Radicals - 0x4e00 <= x && x <= 0xa4c6 || // Hangul Jamo Extended-A - 0xa960 <= x && x <= 0xa97c || // Hangul Syllables - 0xac00 <= x && x <= 0xd7a3 || // CJK Compatibility Ideographs - 0xf900 <= x && x <= 0xfaff || // Vertical Forms - 0xfe10 <= x && x <= 0xfe19 || // CJK Compatibility Forms .. Small Form Variants - 0xfe30 <= x && x <= 0xfe6b || // Halfwidth and Fullwidth Forms - 0xff01 <= x && x <= 0xff60 || 0xffe0 <= x && x <= 0xffe6 || // Kana Supplement - 0x1b000 <= x && x <= 0x1b001 || // Enclosed Ideographic Supplement - 0x1f200 <= x && x <= 0x1f251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - 0x20000 <= x && x <= 0x3fffd)) { - return true; - } - - return false; - }; -}); - -var stringWidth = createCommonjsModule(function (module) { - 'use strict'; - - module.exports = function (str) { - if (typeof str !== 'string' || str.length === 0) { - return 0; - } - - str = stripAnsi(str); - var width = 0; - - for (var i = 0; i < str.length; i++) { - var code = str.codePointAt(i); // Ignore control characters - - if (code <= 0x1F || code >= 0x7F && code <= 0x9F) { - continue; - } // Ignore combining characters - - - if (code >= 0x300 && code <= 0x36F) { - continue; - } // Surrogates - - - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; - }; -}); - -var emojiRegex$1 = function emojiRegex() { - // https://mathiasbynens.be/notes/es-unicode-property-escapes#emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\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])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92])|(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]\uFE0F|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]))|\uD83D\uDC69\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])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92])|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDD1-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])?|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF8]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD4C\uDD50-\uDD6B\uDD80-\uDD97\uDDC0\uDDD0-\uDDE6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267B\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF8]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD4C\uDD50-\uDD6B\uDD80-\uDD97\uDDC0\uDDD0-\uDDE6])\uFE0F/g; -}; - -var punctuation_ranges = [// http://www.unicode.org/charts/PDF/U3000.pdf CJK Symbols and Punctuation -[0x3000, 0x303f], // http://www.unicode.org/charts/PDF/UAC00.pdf Hangul Syllables -[0xac00, 0xd7af], // http://www.unicode.org/charts/PDF/UFE10.pdf Vertical Forms -[0xfe10, 0xfe1f], // http://www.unicode.org/charts/PDF/UFE30.pdf CJK Compatibility Forms -// http://www.unicode.org/charts/PDF/UFE50.pdf Small Form Variants -[0xfe30, 0xfe6f], // http://www.unicode.org/charts/PDF/UFF00.pdf Halfwidth and Fullwidth Forms -[0xff00, 0xff60], [0xffe0, 0xffef]]; -var character_ranges = [// http://www.unicode.org/charts/PDF/U1100.pdf Hangul Jamo -[0x1100, 0x11ff], // http://www.unicode.org/charts/PDF/U2E80.pdf CJK Radicals Supplement -// http://www.unicode.org/charts/PDF/U2F00.pdf Kangxi Radicals -[0x2e80, 0x2fdf], // http://www.unicode.org/charts/PDF/U3040.pdf Hiragana -// http://www.unicode.org/charts/PDF/U30A0.pdf Katakana -// http://www.unicode.org/charts/PDF/U3100.pdf Bopomofo -// http://www.unicode.org/charts/PDF/U3130.pdf Hangul Compatibility Jamo -[0x3040, 0x318f], // http://www.unicode.org/charts/PDF/U3200.pdf Enclosed CJK Letters and Months -// http://www.unicode.org/charts/PDF/U3300.pdf CJK Compatibility -// http://www.unicode.org/charts/PDF/U3400.pdf CJK Unified Ideographs Extension A -[0x3200, 0x4dbf], // http://www.unicode.org/charts/PDF/U4E00.pdf CJK Unified Ideographs (Han) -[0x4e00, 0x9fff], // http://www.unicode.org/charts/PDF/UA960.pdf Hangul Jamo Extended-A -[0xa960, 0xa97f], // http://www.unicode.org/charts/PDF/UF900.pdf CJK Compatibility Ideographs -[0xf900, 0xfaff]]; - -function get_regex() { - return create_regex(character_ranges.concat(punctuation_ranges)); -} // istanbul ignore next -// tslint:disable-next-line:no-namespace - - -(function (get_regex) { - function punctuations() { - return create_regex(punctuation_ranges); - } - - get_regex.punctuations = punctuations; - - function characters() { - return create_regex(character_ranges); - } - - get_regex.characters = characters; -})(get_regex || (get_regex = {})); - -function create_regex(ranges) { - return new RegExp("[" + ranges.map(get_bracket_content).reduce(function (a, b) { - return a + b; - }) + "]", 'g'); -} - -function get_bracket_content(range) { - return get_escaped_unicode(range[0]) + "-" + get_escaped_unicode(range[1]); -} - -function get_escaped_unicode(num) { - return "\\u" + num.toString(16); -} - -var lib$3 = get_regex; - -var data_generated = createCommonjsModule(function (module, exports) { - "use strict"; - - exports.__esModule = true; - - exports.get_data = function () { - return { - "Pc": [[95, 95], [8255, 8256], [8276, 8276], [65075, 65076], [65101, 65103], [65343, 65343]], - "Pe": [[41, 41], [93, 93], [125, 125], [3899, 3899], [3901, 3901], [5788, 5788], [8262, 8262], [8318, 8318], [8334, 8334], [8969, 8969], [8971, 8971], [9002, 9002], [10089, 10089], [10091, 10091], [10093, 10093], [10095, 10095], [10097, 10097], [10099, 10099], [10101, 10101], [10182, 10182], [10215, 10215], [10217, 10217], [10219, 10219], [10221, 10221], [10223, 10223], [10628, 10628], [10630, 10630], [10632, 10632], [10634, 10634], [10636, 10636], [10638, 10638], [10640, 10640], [10642, 10642], [10644, 10644], [10646, 10646], [10648, 10648], [10713, 10713], [10715, 10715], [10749, 10749], [11811, 11811], [11813, 11813], [11815, 11815], [11817, 11817], [12297, 12297], [12299, 12299], [12301, 12301], [12303, 12303], [12305, 12305], [12309, 12309], [12311, 12311], [12313, 12313], [12315, 12315], [12318, 12319], [64830, 64830], [65048, 65048], [65078, 65078], [65080, 65080], [65082, 65082], [65084, 65084], [65086, 65086], [65088, 65088], [65090, 65090], [65092, 65092], [65096, 65096], [65114, 65114], [65116, 65116], [65118, 65118], [65289, 65289], [65341, 65341], [65373, 65373], [65376, 65376], [65379, 65379]], - "Ps": [[40, 40], [91, 91], [123, 123], [3898, 3898], [3900, 3900], [5787, 5787], [8218, 8218], [8222, 8222], [8261, 8261], [8317, 8317], [8333, 8333], [8968, 8968], [8970, 8970], [9001, 9001], [10088, 10088], [10090, 10090], [10092, 10092], [10094, 10094], [10096, 10096], [10098, 10098], [10100, 10100], [10181, 10181], [10214, 10214], [10216, 10216], [10218, 10218], [10220, 10220], [10222, 10222], [10627, 10627], [10629, 10629], [10631, 10631], [10633, 10633], [10635, 10635], [10637, 10637], [10639, 10639], [10641, 10641], [10643, 10643], [10645, 10645], [10647, 10647], [10712, 10712], [10714, 10714], [10748, 10748], [11810, 11810], [11812, 11812], [11814, 11814], [11816, 11816], [11842, 11842], [12296, 12296], [12298, 12298], [12300, 12300], [12302, 12302], [12304, 12304], [12308, 12308], [12310, 12310], [12312, 12312], [12314, 12314], [12317, 12317], [64831, 64831], [65047, 65047], [65077, 65077], [65079, 65079], [65081, 65081], [65083, 65083], [65085, 65085], [65087, 65087], [65089, 65089], [65091, 65091], [65095, 65095], [65113, 65113], [65115, 65115], [65117, 65117], [65288, 65288], [65339, 65339], [65371, 65371], [65375, 65375], [65378, 65378]], - "Lm": [[688, 705], [710, 721], [736, 740], [748, 748], [750, 750], [884, 884], [890, 890], [1369, 1369], [1600, 1600], [1765, 1766], [2036, 2037], [2042, 2042], [2074, 2074], [2084, 2084], [2088, 2088], [2417, 2417], [3654, 3654], [3782, 3782], [4348, 4348], [6103, 6103], [6211, 6211], [6823, 6823], [7288, 7293], [7468, 7530], [7544, 7544], [7579, 7615], [8305, 8305], [8319, 8319], [8336, 8348], [11388, 11389], [11631, 11631], [11823, 11823], [12293, 12293], [12337, 12341], [12347, 12347], [12445, 12446], [12540, 12542], [40981, 40981], [42232, 42237], [42508, 42508], [42623, 42623], [42652, 42653], [42775, 42783], [42864, 42864], [42888, 42888], [43000, 43001], [43471, 43471], [43494, 43494], [43632, 43632], [43741, 43741], [43763, 43764], [43868, 43871], [65392, 65392], [65438, 65439]], - "Mc": [[2307, 2307], [2363, 2363], [2366, 2368], [2377, 2380], [2382, 2383], [2434, 2435], [2494, 2496], [2503, 2504], [2507, 2508], [2519, 2519], [2563, 2563], [2622, 2624], [2691, 2691], [2750, 2752], [2761, 2761], [2763, 2764], [2818, 2819], [2878, 2878], [2880, 2880], [2887, 2888], [2891, 2892], [2903, 2903], [3006, 3007], [3009, 3010], [3014, 3016], [3018, 3020], [3031, 3031], [3073, 3075], [3137, 3140], [3202, 3203], [3262, 3262], [3264, 3268], [3271, 3272], [3274, 3275], [3285, 3286], [3330, 3331], [3390, 3392], [3398, 3400], [3402, 3404], [3415, 3415], [3458, 3459], [3535, 3537], [3544, 3551], [3570, 3571], [3902, 3903], [3967, 3967], [4139, 4140], [4145, 4145], [4152, 4152], [4155, 4156], [4182, 4183], [4194, 4196], [4199, 4205], [4227, 4228], [4231, 4236], [4239, 4239], [4250, 4252], [6070, 6070], [6078, 6085], [6087, 6088], [6435, 6438], [6441, 6443], [6448, 6449], [6451, 6456], [6681, 6682], [6741, 6741], [6743, 6743], [6753, 6753], [6755, 6756], [6765, 6770], [6916, 6916], [6965, 6965], [6971, 6971], [6973, 6977], [6979, 6980], [7042, 7042], [7073, 7073], [7078, 7079], [7082, 7082], [7143, 7143], [7146, 7148], [7150, 7150], [7154, 7155], [7204, 7211], [7220, 7221], [7393, 7393], [7410, 7411], [7415, 7415], [12334, 12335], [43043, 43044], [43047, 43047], [43136, 43137], [43188, 43203], [43346, 43347], [43395, 43395], [43444, 43445], [43450, 43451], [43453, 43456], [43567, 43568], [43571, 43572], [43597, 43597], [43643, 43643], [43645, 43645], [43755, 43755], [43758, 43759], [43765, 43765], [44003, 44004], [44006, 44007], [44009, 44010], [44012, 44012]], - "Zp": [[8233, 8233]], - "Sc": [[36, 36], [162, 165], [1423, 1423], [1547, 1547], [2546, 2547], [2555, 2555], [2801, 2801], [3065, 3065], [3647, 3647], [6107, 6107], [8352, 8383], [43064, 43064], [65020, 65020], [65129, 65129], [65284, 65284], [65504, 65505], [65509, 65510]], - "Me": [[1160, 1161], [6846, 6846], [8413, 8416], [8418, 8420], [42608, 42610]], - "Sk": [[94, 94], [96, 96], [168, 168], [175, 175], [180, 180], [184, 184], [706, 709], [722, 735], [741, 747], [749, 749], [751, 767], [885, 885], [900, 901], [8125, 8125], [8127, 8129], [8141, 8143], [8157, 8159], [8173, 8175], [8189, 8190], [12443, 12444], [42752, 42774], [42784, 42785], [42889, 42890], [43867, 43867], [64434, 64449], [65342, 65342], [65344, 65344], [65507, 65507]], - "Cs": [[55296, 55296], [56191, 56192], [56319, 56320], [57343, 57343]], - "Nl": [[5870, 5872], [8544, 8578], [8581, 8584], [12295, 12295], [12321, 12329], [12344, 12346], [42726, 42735]], - "So": [[166, 166], [169, 169], [174, 174], [176, 176], [1154, 1154], [1421, 1422], [1550, 1551], [1758, 1758], [1769, 1769], [1789, 1790], [2038, 2038], [2554, 2554], [2928, 2928], [3059, 3064], [3066, 3066], [3199, 3199], [3407, 3407], [3449, 3449], [3841, 3843], [3859, 3859], [3861, 3863], [3866, 3871], [3892, 3892], [3894, 3894], [3896, 3896], [4030, 4037], [4039, 4044], [4046, 4047], [4053, 4056], [4254, 4255], [5008, 5017], [6464, 6464], [6622, 6655], [7009, 7018], [7028, 7036], [8448, 8449], [8451, 8454], [8456, 8457], [8468, 8468], [8470, 8471], [8478, 8483], [8485, 8485], [8487, 8487], [8489, 8489], [8494, 8494], [8506, 8507], [8522, 8522], [8524, 8525], [8527, 8527], [8586, 8587], [8597, 8601], [8604, 8607], [8609, 8610], [8612, 8613], [8615, 8621], [8623, 8653], [8656, 8657], [8659, 8659], [8661, 8691], [8960, 8967], [8972, 8991], [8994, 9000], [9003, 9083], [9085, 9114], [9140, 9179], [9186, 9254], [9280, 9290], [9372, 9449], [9472, 9654], [9656, 9664], [9666, 9719], [9728, 9838], [9840, 10087], [10132, 10175], [10240, 10495], [11008, 11055], [11077, 11078], [11085, 11123], [11126, 11157], [11160, 11193], [11197, 11208], [11210, 11218], [11244, 11247], [11493, 11498], [11904, 11929], [11931, 12019], [12032, 12245], [12272, 12283], [12292, 12292], [12306, 12307], [12320, 12320], [12342, 12343], [12350, 12351], [12688, 12689], [12694, 12703], [12736, 12771], [12800, 12830], [12842, 12871], [12880, 12880], [12896, 12927], [12938, 12976], [12992, 13054], [13056, 13311], [19904, 19967], [42128, 42182], [43048, 43051], [43062, 43063], [43065, 43065], [43639, 43641], [65021, 65021], [65508, 65508], [65512, 65512], [65517, 65518], [65532, 65533]], - "Lt": [[453, 453], [456, 456], [459, 459], [498, 498], [8072, 8079], [8088, 8095], [8104, 8111], [8124, 8124], [8140, 8140], [8188, 8188]], - "Zl": [[8232, 8232]], - "Lo": [[170, 170], [186, 186], [443, 443], [448, 451], [660, 660], [1488, 1514], [1520, 1522], [1568, 1599], [1601, 1610], [1646, 1647], [1649, 1747], [1749, 1749], [1774, 1775], [1786, 1788], [1791, 1791], [1808, 1808], [1810, 1839], [1869, 1957], [1969, 1969], [1994, 2026], [2048, 2069], [2112, 2136], [2144, 2154], [2208, 2228], [2230, 2237], [2308, 2361], [2365, 2365], [2384, 2384], [2392, 2401], [2418, 2432], [2437, 2444], [2447, 2448], [2451, 2472], [2474, 2480], [2482, 2482], [2486, 2489], [2493, 2493], [2510, 2510], [2524, 2525], [2527, 2529], [2544, 2545], [2556, 2556], [2565, 2570], [2575, 2576], [2579, 2600], [2602, 2608], [2610, 2611], [2613, 2614], [2616, 2617], [2649, 2652], [2654, 2654], [2674, 2676], [2693, 2701], [2703, 2705], [2707, 2728], [2730, 2736], [2738, 2739], [2741, 2745], [2749, 2749], [2768, 2768], [2784, 2785], [2809, 2809], [2821, 2828], [2831, 2832], [2835, 2856], [2858, 2864], [2866, 2867], [2869, 2873], [2877, 2877], [2908, 2909], [2911, 2913], [2929, 2929], [2947, 2947], [2949, 2954], [2958, 2960], [2962, 2965], [2969, 2970], [2972, 2972], [2974, 2975], [2979, 2980], [2984, 2986], [2990, 3001], [3024, 3024], [3077, 3084], [3086, 3088], [3090, 3112], [3114, 3129], [3133, 3133], [3160, 3162], [3168, 3169], [3200, 3200], [3205, 3212], [3214, 3216], [3218, 3240], [3242, 3251], [3253, 3257], [3261, 3261], [3294, 3294], [3296, 3297], [3313, 3314], [3333, 3340], [3342, 3344], [3346, 3386], [3389, 3389], [3406, 3406], [3412, 3414], [3423, 3425], [3450, 3455], [3461, 3478], [3482, 3505], [3507, 3515], [3517, 3517], [3520, 3526], [3585, 3632], [3634, 3635], [3648, 3653], [3713, 3714], [3716, 3716], [3719, 3720], [3722, 3722], [3725, 3725], [3732, 3735], [3737, 3743], [3745, 3747], [3749, 3749], [3751, 3751], [3754, 3755], [3757, 3760], [3762, 3763], [3773, 3773], [3776, 3780], [3804, 3807], [3840, 3840], [3904, 3911], [3913, 3948], [3976, 3980], [4096, 4138], [4159, 4159], [4176, 4181], [4186, 4189], [4193, 4193], [4197, 4198], [4206, 4208], [4213, 4225], [4238, 4238], [4304, 4346], [4349, 4680], [4682, 4685], [4688, 4694], [4696, 4696], [4698, 4701], [4704, 4744], [4746, 4749], [4752, 4784], [4786, 4789], [4792, 4798], [4800, 4800], [4802, 4805], [4808, 4822], [4824, 4880], [4882, 4885], [4888, 4954], [4992, 5007], [5121, 5740], [5743, 5759], [5761, 5786], [5792, 5866], [5873, 5880], [5888, 5900], [5902, 5905], [5920, 5937], [5952, 5969], [5984, 5996], [5998, 6000], [6016, 6067], [6108, 6108], [6176, 6210], [6212, 6263], [6272, 6276], [6279, 6312], [6314, 6314], [6320, 6389], [6400, 6430], [6480, 6509], [6512, 6516], [6528, 6571], [6576, 6601], [6656, 6678], [6688, 6740], [6917, 6963], [6981, 6987], [7043, 7072], [7086, 7087], [7098, 7141], [7168, 7203], [7245, 7247], [7258, 7287], [7401, 7404], [7406, 7409], [7413, 7414], [8501, 8504], [11568, 11623], [11648, 11670], [11680, 11686], [11688, 11694], [11696, 11702], [11704, 11710], [11712, 11718], [11720, 11726], [11728, 11734], [11736, 11742], [12294, 12294], [12348, 12348], [12353, 12438], [12447, 12447], [12449, 12538], [12543, 12543], [12549, 12590], [12593, 12686], [12704, 12730], [12784, 12799], [13312, 13312], [19893, 19893], [19968, 19968], [40938, 40938], [40960, 40980], [40982, 42124], [42192, 42231], [42240, 42507], [42512, 42527], [42538, 42539], [42606, 42606], [42656, 42725], [42895, 42895], [42999, 42999], [43003, 43009], [43011, 43013], [43015, 43018], [43020, 43042], [43072, 43123], [43138, 43187], [43250, 43255], [43259, 43259], [43261, 43261], [43274, 43301], [43312, 43334], [43360, 43388], [43396, 43442], [43488, 43492], [43495, 43503], [43514, 43518], [43520, 43560], [43584, 43586], [43588, 43595], [43616, 43631], [43633, 43638], [43642, 43642], [43646, 43695], [43697, 43697], [43701, 43702], [43705, 43709], [43712, 43712], [43714, 43714], [43739, 43740], [43744, 43754], [43762, 43762], [43777, 43782], [43785, 43790], [43793, 43798], [43808, 43814], [43816, 43822], [43968, 44002], [44032, 44032], [55203, 55203], [55216, 55238], [55243, 55291], [63744, 64109], [64112, 64217], [64285, 64285], [64287, 64296], [64298, 64310], [64312, 64316], [64318, 64318], [64320, 64321], [64323, 64324], [64326, 64433], [64467, 64829], [64848, 64911], [64914, 64967], [65008, 65019], [65136, 65140], [65142, 65276], [65382, 65391], [65393, 65437], [65440, 65470], [65474, 65479], [65482, 65487], [65490, 65495], [65498, 65500]], - "Mn": [[768, 879], [1155, 1159], [1425, 1469], [1471, 1471], [1473, 1474], [1476, 1477], [1479, 1479], [1552, 1562], [1611, 1631], [1648, 1648], [1750, 1756], [1759, 1764], [1767, 1768], [1770, 1773], [1809, 1809], [1840, 1866], [1958, 1968], [2027, 2035], [2070, 2073], [2075, 2083], [2085, 2087], [2089, 2093], [2137, 2139], [2260, 2273], [2275, 2306], [2362, 2362], [2364, 2364], [2369, 2376], [2381, 2381], [2385, 2391], [2402, 2403], [2433, 2433], [2492, 2492], [2497, 2500], [2509, 2509], [2530, 2531], [2561, 2562], [2620, 2620], [2625, 2626], [2631, 2632], [2635, 2637], [2641, 2641], [2672, 2673], [2677, 2677], [2689, 2690], [2748, 2748], [2753, 2757], [2759, 2760], [2765, 2765], [2786, 2787], [2810, 2815], [2817, 2817], [2876, 2876], [2879, 2879], [2881, 2884], [2893, 2893], [2902, 2902], [2914, 2915], [2946, 2946], [3008, 3008], [3021, 3021], [3072, 3072], [3134, 3136], [3142, 3144], [3146, 3149], [3157, 3158], [3170, 3171], [3201, 3201], [3260, 3260], [3263, 3263], [3270, 3270], [3276, 3277], [3298, 3299], [3328, 3329], [3387, 3388], [3393, 3396], [3405, 3405], [3426, 3427], [3530, 3530], [3538, 3540], [3542, 3542], [3633, 3633], [3636, 3642], [3655, 3662], [3761, 3761], [3764, 3769], [3771, 3772], [3784, 3789], [3864, 3865], [3893, 3893], [3895, 3895], [3897, 3897], [3953, 3966], [3968, 3972], [3974, 3975], [3981, 3991], [3993, 4028], [4038, 4038], [4141, 4144], [4146, 4151], [4153, 4154], [4157, 4158], [4184, 4185], [4190, 4192], [4209, 4212], [4226, 4226], [4229, 4230], [4237, 4237], [4253, 4253], [4957, 4959], [5906, 5908], [5938, 5940], [5970, 5971], [6002, 6003], [6068, 6069], [6071, 6077], [6086, 6086], [6089, 6099], [6109, 6109], [6155, 6157], [6277, 6278], [6313, 6313], [6432, 6434], [6439, 6440], [6450, 6450], [6457, 6459], [6679, 6680], [6683, 6683], [6742, 6742], [6744, 6750], [6752, 6752], [6754, 6754], [6757, 6764], [6771, 6780], [6783, 6783], [6832, 6845], [6912, 6915], [6964, 6964], [6966, 6970], [6972, 6972], [6978, 6978], [7019, 7027], [7040, 7041], [7074, 7077], [7080, 7081], [7083, 7085], [7142, 7142], [7144, 7145], [7149, 7149], [7151, 7153], [7212, 7219], [7222, 7223], [7376, 7378], [7380, 7392], [7394, 7400], [7405, 7405], [7412, 7412], [7416, 7417], [7616, 7673], [7675, 7679], [8400, 8412], [8417, 8417], [8421, 8432], [11503, 11505], [11647, 11647], [11744, 11775], [12330, 12333], [12441, 12442], [42607, 42607], [42612, 42621], [42654, 42655], [42736, 42737], [43010, 43010], [43014, 43014], [43019, 43019], [43045, 43046], [43204, 43205], [43232, 43249], [43302, 43309], [43335, 43345], [43392, 43394], [43443, 43443], [43446, 43449], [43452, 43452], [43493, 43493], [43561, 43566], [43569, 43570], [43573, 43574], [43587, 43587], [43596, 43596], [43644, 43644], [43696, 43696], [43698, 43700], [43703, 43704], [43710, 43711], [43713, 43713], [43756, 43757], [43766, 43766], [44005, 44005], [44008, 44008], [44013, 44013], [64286, 64286], [65024, 65039], [65056, 65071]], - "Po": [[33, 35], [37, 39], [42, 42], [44, 44], [46, 47], [58, 59], [63, 64], [92, 92], [161, 161], [167, 167], [182, 183], [191, 191], [894, 894], [903, 903], [1370, 1375], [1417, 1417], [1472, 1472], [1475, 1475], [1478, 1478], [1523, 1524], [1545, 1546], [1548, 1549], [1563, 1563], [1566, 1567], [1642, 1645], [1748, 1748], [1792, 1805], [2039, 2041], [2096, 2110], [2142, 2142], [2404, 2405], [2416, 2416], [2557, 2557], [2800, 2800], [3572, 3572], [3663, 3663], [3674, 3675], [3844, 3858], [3860, 3860], [3973, 3973], [4048, 4052], [4057, 4058], [4170, 4175], [4347, 4347], [4960, 4968], [5741, 5742], [5867, 5869], [5941, 5942], [6100, 6102], [6104, 6106], [6144, 6149], [6151, 6154], [6468, 6469], [6686, 6687], [6816, 6822], [6824, 6829], [7002, 7008], [7164, 7167], [7227, 7231], [7294, 7295], [7360, 7367], [7379, 7379], [8214, 8215], [8224, 8231], [8240, 8248], [8251, 8254], [8257, 8259], [8263, 8273], [8275, 8275], [8277, 8286], [11513, 11516], [11518, 11519], [11632, 11632], [11776, 11777], [11782, 11784], [11787, 11787], [11790, 11798], [11800, 11801], [11803, 11803], [11806, 11807], [11818, 11822], [11824, 11833], [11836, 11839], [11841, 11841], [11843, 11849], [12289, 12291], [12349, 12349], [12539, 12539], [42238, 42239], [42509, 42511], [42611, 42611], [42622, 42622], [42738, 42743], [43124, 43127], [43214, 43215], [43256, 43258], [43260, 43260], [43310, 43311], [43359, 43359], [43457, 43469], [43486, 43487], [43612, 43615], [43742, 43743], [43760, 43761], [44011, 44011], [65040, 65046], [65049, 65049], [65072, 65072], [65093, 65094], [65097, 65100], [65104, 65106], [65108, 65111], [65119, 65121], [65128, 65128], [65130, 65131], [65281, 65283], [65285, 65287], [65290, 65290], [65292, 65292], [65294, 65295], [65306, 65307], [65311, 65312], [65340, 65340], [65377, 65377], [65380, 65381]], - "Co": [[57344, 57344], [63743, 63743]], - "Sm": [[43, 43], [60, 62], [124, 124], [126, 126], [172, 172], [177, 177], [215, 215], [247, 247], [1014, 1014], [1542, 1544], [8260, 8260], [8274, 8274], [8314, 8316], [8330, 8332], [8472, 8472], [8512, 8516], [8523, 8523], [8592, 8596], [8602, 8603], [8608, 8608], [8611, 8611], [8614, 8614], [8622, 8622], [8654, 8655], [8658, 8658], [8660, 8660], [8692, 8959], [8992, 8993], [9084, 9084], [9115, 9139], [9180, 9185], [9655, 9655], [9665, 9665], [9720, 9727], [9839, 9839], [10176, 10180], [10183, 10213], [10224, 10239], [10496, 10626], [10649, 10711], [10716, 10747], [10750, 11007], [11056, 11076], [11079, 11084], [64297, 64297], [65122, 65122], [65124, 65126], [65291, 65291], [65308, 65310], [65372, 65372], [65374, 65374], [65506, 65506], [65513, 65516]], - "Pf": [[187, 187], [8217, 8217], [8221, 8221], [8250, 8250], [11779, 11779], [11781, 11781], [11786, 11786], [11789, 11789], [11805, 11805], [11809, 11809]], - "Cc": [[0, 31], [127, 159]], - "Pi": [[171, 171], [8216, 8216], [8219, 8220], [8223, 8223], [8249, 8249], [11778, 11778], [11780, 11780], [11785, 11785], [11788, 11788], [11804, 11804], [11808, 11808]], - "Lu": [[65, 90], [192, 214], [216, 222], [256, 256], [258, 258], [260, 260], [262, 262], [264, 264], [266, 266], [268, 268], [270, 270], [272, 272], [274, 274], [276, 276], [278, 278], [280, 280], [282, 282], [284, 284], [286, 286], [288, 288], [290, 290], [292, 292], [294, 294], [296, 296], [298, 298], [300, 300], [302, 302], [304, 304], [306, 306], [308, 308], [310, 310], [313, 313], [315, 315], [317, 317], [319, 319], [321, 321], [323, 323], [325, 325], [327, 327], [330, 330], [332, 332], [334, 334], [336, 336], [338, 338], [340, 340], [342, 342], [344, 344], [346, 346], [348, 348], [350, 350], [352, 352], [354, 354], [356, 356], [358, 358], [360, 360], [362, 362], [364, 364], [366, 366], [368, 368], [370, 370], [372, 372], [374, 374], [376, 377], [379, 379], [381, 381], [385, 386], [388, 388], [390, 391], [393, 395], [398, 401], [403, 404], [406, 408], [412, 413], [415, 416], [418, 418], [420, 420], [422, 423], [425, 425], [428, 428], [430, 431], [433, 435], [437, 437], [439, 440], [444, 444], [452, 452], [455, 455], [458, 458], [461, 461], [463, 463], [465, 465], [467, 467], [469, 469], [471, 471], [473, 473], [475, 475], [478, 478], [480, 480], [482, 482], [484, 484], [486, 486], [488, 488], [490, 490], [492, 492], [494, 494], [497, 497], [500, 500], [502, 504], [506, 506], [508, 508], [510, 510], [512, 512], [514, 514], [516, 516], [518, 518], [520, 520], [522, 522], [524, 524], [526, 526], [528, 528], [530, 530], [532, 532], [534, 534], [536, 536], [538, 538], [540, 540], [542, 542], [544, 544], [546, 546], [548, 548], [550, 550], [552, 552], [554, 554], [556, 556], [558, 558], [560, 560], [562, 562], [570, 571], [573, 574], [577, 577], [579, 582], [584, 584], [586, 586], [588, 588], [590, 590], [880, 880], [882, 882], [886, 886], [895, 895], [902, 902], [904, 906], [908, 908], [910, 911], [913, 929], [931, 939], [975, 975], [978, 980], [984, 984], [986, 986], [988, 988], [990, 990], [992, 992], [994, 994], [996, 996], [998, 998], [1000, 1000], [1002, 1002], [1004, 1004], [1006, 1006], [1012, 1012], [1015, 1015], [1017, 1018], [1021, 1071], [1120, 1120], [1122, 1122], [1124, 1124], [1126, 1126], [1128, 1128], [1130, 1130], [1132, 1132], [1134, 1134], [1136, 1136], [1138, 1138], [1140, 1140], [1142, 1142], [1144, 1144], [1146, 1146], [1148, 1148], [1150, 1150], [1152, 1152], [1162, 1162], [1164, 1164], [1166, 1166], [1168, 1168], [1170, 1170], [1172, 1172], [1174, 1174], [1176, 1176], [1178, 1178], [1180, 1180], [1182, 1182], [1184, 1184], [1186, 1186], [1188, 1188], [1190, 1190], [1192, 1192], [1194, 1194], [1196, 1196], [1198, 1198], [1200, 1200], [1202, 1202], [1204, 1204], [1206, 1206], [1208, 1208], [1210, 1210], [1212, 1212], [1214, 1214], [1216, 1217], [1219, 1219], [1221, 1221], [1223, 1223], [1225, 1225], [1227, 1227], [1229, 1229], [1232, 1232], [1234, 1234], [1236, 1236], [1238, 1238], [1240, 1240], [1242, 1242], [1244, 1244], [1246, 1246], [1248, 1248], [1250, 1250], [1252, 1252], [1254, 1254], [1256, 1256], [1258, 1258], [1260, 1260], [1262, 1262], [1264, 1264], [1266, 1266], [1268, 1268], [1270, 1270], [1272, 1272], [1274, 1274], [1276, 1276], [1278, 1278], [1280, 1280], [1282, 1282], [1284, 1284], [1286, 1286], [1288, 1288], [1290, 1290], [1292, 1292], [1294, 1294], [1296, 1296], [1298, 1298], [1300, 1300], [1302, 1302], [1304, 1304], [1306, 1306], [1308, 1308], [1310, 1310], [1312, 1312], [1314, 1314], [1316, 1316], [1318, 1318], [1320, 1320], [1322, 1322], [1324, 1324], [1326, 1326], [1329, 1366], [4256, 4293], [4295, 4295], [4301, 4301], [5024, 5109], [7680, 7680], [7682, 7682], [7684, 7684], [7686, 7686], [7688, 7688], [7690, 7690], [7692, 7692], [7694, 7694], [7696, 7696], [7698, 7698], [7700, 7700], [7702, 7702], [7704, 7704], [7706, 7706], [7708, 7708], [7710, 7710], [7712, 7712], [7714, 7714], [7716, 7716], [7718, 7718], [7720, 7720], [7722, 7722], [7724, 7724], [7726, 7726], [7728, 7728], [7730, 7730], [7732, 7732], [7734, 7734], [7736, 7736], [7738, 7738], [7740, 7740], [7742, 7742], [7744, 7744], [7746, 7746], [7748, 7748], [7750, 7750], [7752, 7752], [7754, 7754], [7756, 7756], [7758, 7758], [7760, 7760], [7762, 7762], [7764, 7764], [7766, 7766], [7768, 7768], [7770, 7770], [7772, 7772], [7774, 7774], [7776, 7776], [7778, 7778], [7780, 7780], [7782, 7782], [7784, 7784], [7786, 7786], [7788, 7788], [7790, 7790], [7792, 7792], [7794, 7794], [7796, 7796], [7798, 7798], [7800, 7800], [7802, 7802], [7804, 7804], [7806, 7806], [7808, 7808], [7810, 7810], [7812, 7812], [7814, 7814], [7816, 7816], [7818, 7818], [7820, 7820], [7822, 7822], [7824, 7824], [7826, 7826], [7828, 7828], [7838, 7838], [7840, 7840], [7842, 7842], [7844, 7844], [7846, 7846], [7848, 7848], [7850, 7850], [7852, 7852], [7854, 7854], [7856, 7856], [7858, 7858], [7860, 7860], [7862, 7862], [7864, 7864], [7866, 7866], [7868, 7868], [7870, 7870], [7872, 7872], [7874, 7874], [7876, 7876], [7878, 7878], [7880, 7880], [7882, 7882], [7884, 7884], [7886, 7886], [7888, 7888], [7890, 7890], [7892, 7892], [7894, 7894], [7896, 7896], [7898, 7898], [7900, 7900], [7902, 7902], [7904, 7904], [7906, 7906], [7908, 7908], [7910, 7910], [7912, 7912], [7914, 7914], [7916, 7916], [7918, 7918], [7920, 7920], [7922, 7922], [7924, 7924], [7926, 7926], [7928, 7928], [7930, 7930], [7932, 7932], [7934, 7934], [7944, 7951], [7960, 7965], [7976, 7983], [7992, 7999], [8008, 8013], [8025, 8025], [8027, 8027], [8029, 8029], [8031, 8031], [8040, 8047], [8120, 8123], [8136, 8139], [8152, 8155], [8168, 8172], [8184, 8187], [8450, 8450], [8455, 8455], [8459, 8461], [8464, 8466], [8469, 8469], [8473, 8477], [8484, 8484], [8486, 8486], [8488, 8488], [8490, 8493], [8496, 8499], [8510, 8511], [8517, 8517], [8579, 8579], [11264, 11310], [11360, 11360], [11362, 11364], [11367, 11367], [11369, 11369], [11371, 11371], [11373, 11376], [11378, 11378], [11381, 11381], [11390, 11392], [11394, 11394], [11396, 11396], [11398, 11398], [11400, 11400], [11402, 11402], [11404, 11404], [11406, 11406], [11408, 11408], [11410, 11410], [11412, 11412], [11414, 11414], [11416, 11416], [11418, 11418], [11420, 11420], [11422, 11422], [11424, 11424], [11426, 11426], [11428, 11428], [11430, 11430], [11432, 11432], [11434, 11434], [11436, 11436], [11438, 11438], [11440, 11440], [11442, 11442], [11444, 11444], [11446, 11446], [11448, 11448], [11450, 11450], [11452, 11452], [11454, 11454], [11456, 11456], [11458, 11458], [11460, 11460], [11462, 11462], [11464, 11464], [11466, 11466], [11468, 11468], [11470, 11470], [11472, 11472], [11474, 11474], [11476, 11476], [11478, 11478], [11480, 11480], [11482, 11482], [11484, 11484], [11486, 11486], [11488, 11488], [11490, 11490], [11499, 11499], [11501, 11501], [11506, 11506], [42560, 42560], [42562, 42562], [42564, 42564], [42566, 42566], [42568, 42568], [42570, 42570], [42572, 42572], [42574, 42574], [42576, 42576], [42578, 42578], [42580, 42580], [42582, 42582], [42584, 42584], [42586, 42586], [42588, 42588], [42590, 42590], [42592, 42592], [42594, 42594], [42596, 42596], [42598, 42598], [42600, 42600], [42602, 42602], [42604, 42604], [42624, 42624], [42626, 42626], [42628, 42628], [42630, 42630], [42632, 42632], [42634, 42634], [42636, 42636], [42638, 42638], [42640, 42640], [42642, 42642], [42644, 42644], [42646, 42646], [42648, 42648], [42650, 42650], [42786, 42786], [42788, 42788], [42790, 42790], [42792, 42792], [42794, 42794], [42796, 42796], [42798, 42798], [42802, 42802], [42804, 42804], [42806, 42806], [42808, 42808], [42810, 42810], [42812, 42812], [42814, 42814], [42816, 42816], [42818, 42818], [42820, 42820], [42822, 42822], [42824, 42824], [42826, 42826], [42828, 42828], [42830, 42830], [42832, 42832], [42834, 42834], [42836, 42836], [42838, 42838], [42840, 42840], [42842, 42842], [42844, 42844], [42846, 42846], [42848, 42848], [42850, 42850], [42852, 42852], [42854, 42854], [42856, 42856], [42858, 42858], [42860, 42860], [42862, 42862], [42873, 42873], [42875, 42875], [42877, 42878], [42880, 42880], [42882, 42882], [42884, 42884], [42886, 42886], [42891, 42891], [42893, 42893], [42896, 42896], [42898, 42898], [42902, 42902], [42904, 42904], [42906, 42906], [42908, 42908], [42910, 42910], [42912, 42912], [42914, 42914], [42916, 42916], [42918, 42918], [42920, 42920], [42922, 42926], [42928, 42932], [42934, 42934], [65313, 65338]], - "Pd": [[45, 45], [1418, 1418], [1470, 1470], [5120, 5120], [6150, 6150], [8208, 8213], [11799, 11799], [11802, 11802], [11834, 11835], [11840, 11840], [12316, 12316], [12336, 12336], [12448, 12448], [65073, 65074], [65112, 65112], [65123, 65123], [65293, 65293]], - "Cf": [[173, 173], [1536, 1541], [1564, 1564], [1757, 1757], [1807, 1807], [2274, 2274], [6158, 6158], [8203, 8207], [8234, 8238], [8288, 8292], [8294, 8303], [65279, 65279], [65529, 65531]], - "Nd": [[48, 57], [1632, 1641], [1776, 1785], [1984, 1993], [2406, 2415], [2534, 2543], [2662, 2671], [2790, 2799], [2918, 2927], [3046, 3055], [3174, 3183], [3302, 3311], [3430, 3439], [3558, 3567], [3664, 3673], [3792, 3801], [3872, 3881], [4160, 4169], [4240, 4249], [6112, 6121], [6160, 6169], [6470, 6479], [6608, 6617], [6784, 6793], [6800, 6809], [6992, 7001], [7088, 7097], [7232, 7241], [7248, 7257], [42528, 42537], [43216, 43225], [43264, 43273], [43472, 43481], [43504, 43513], [43600, 43609], [44016, 44025], [65296, 65305]], - "Ll": [[97, 122], [181, 181], [223, 246], [248, 255], [257, 257], [259, 259], [261, 261], [263, 263], [265, 265], [267, 267], [269, 269], [271, 271], [273, 273], [275, 275], [277, 277], [279, 279], [281, 281], [283, 283], [285, 285], [287, 287], [289, 289], [291, 291], [293, 293], [295, 295], [297, 297], [299, 299], [301, 301], [303, 303], [305, 305], [307, 307], [309, 309], [311, 312], [314, 314], [316, 316], [318, 318], [320, 320], [322, 322], [324, 324], [326, 326], [328, 329], [331, 331], [333, 333], [335, 335], [337, 337], [339, 339], [341, 341], [343, 343], [345, 345], [347, 347], [349, 349], [351, 351], [353, 353], [355, 355], [357, 357], [359, 359], [361, 361], [363, 363], [365, 365], [367, 367], [369, 369], [371, 371], [373, 373], [375, 375], [378, 378], [380, 380], [382, 384], [387, 387], [389, 389], [392, 392], [396, 397], [402, 402], [405, 405], [409, 411], [414, 414], [417, 417], [419, 419], [421, 421], [424, 424], [426, 427], [429, 429], [432, 432], [436, 436], [438, 438], [441, 442], [445, 447], [454, 454], [457, 457], [460, 460], [462, 462], [464, 464], [466, 466], [468, 468], [470, 470], [472, 472], [474, 474], [476, 477], [479, 479], [481, 481], [483, 483], [485, 485], [487, 487], [489, 489], [491, 491], [493, 493], [495, 496], [499, 499], [501, 501], [505, 505], [507, 507], [509, 509], [511, 511], [513, 513], [515, 515], [517, 517], [519, 519], [521, 521], [523, 523], [525, 525], [527, 527], [529, 529], [531, 531], [533, 533], [535, 535], [537, 537], [539, 539], [541, 541], [543, 543], [545, 545], [547, 547], [549, 549], [551, 551], [553, 553], [555, 555], [557, 557], [559, 559], [561, 561], [563, 569], [572, 572], [575, 576], [578, 578], [583, 583], [585, 585], [587, 587], [589, 589], [591, 659], [661, 687], [881, 881], [883, 883], [887, 887], [891, 893], [912, 912], [940, 974], [976, 977], [981, 983], [985, 985], [987, 987], [989, 989], [991, 991], [993, 993], [995, 995], [997, 997], [999, 999], [1001, 1001], [1003, 1003], [1005, 1005], [1007, 1011], [1013, 1013], [1016, 1016], [1019, 1020], [1072, 1119], [1121, 1121], [1123, 1123], [1125, 1125], [1127, 1127], [1129, 1129], [1131, 1131], [1133, 1133], [1135, 1135], [1137, 1137], [1139, 1139], [1141, 1141], [1143, 1143], [1145, 1145], [1147, 1147], [1149, 1149], [1151, 1151], [1153, 1153], [1163, 1163], [1165, 1165], [1167, 1167], [1169, 1169], [1171, 1171], [1173, 1173], [1175, 1175], [1177, 1177], [1179, 1179], [1181, 1181], [1183, 1183], [1185, 1185], [1187, 1187], [1189, 1189], [1191, 1191], [1193, 1193], [1195, 1195], [1197, 1197], [1199, 1199], [1201, 1201], [1203, 1203], [1205, 1205], [1207, 1207], [1209, 1209], [1211, 1211], [1213, 1213], [1215, 1215], [1218, 1218], [1220, 1220], [1222, 1222], [1224, 1224], [1226, 1226], [1228, 1228], [1230, 1231], [1233, 1233], [1235, 1235], [1237, 1237], [1239, 1239], [1241, 1241], [1243, 1243], [1245, 1245], [1247, 1247], [1249, 1249], [1251, 1251], [1253, 1253], [1255, 1255], [1257, 1257], [1259, 1259], [1261, 1261], [1263, 1263], [1265, 1265], [1267, 1267], [1269, 1269], [1271, 1271], [1273, 1273], [1275, 1275], [1277, 1277], [1279, 1279], [1281, 1281], [1283, 1283], [1285, 1285], [1287, 1287], [1289, 1289], [1291, 1291], [1293, 1293], [1295, 1295], [1297, 1297], [1299, 1299], [1301, 1301], [1303, 1303], [1305, 1305], [1307, 1307], [1309, 1309], [1311, 1311], [1313, 1313], [1315, 1315], [1317, 1317], [1319, 1319], [1321, 1321], [1323, 1323], [1325, 1325], [1327, 1327], [1377, 1415], [5112, 5117], [7296, 7304], [7424, 7467], [7531, 7543], [7545, 7578], [7681, 7681], [7683, 7683], [7685, 7685], [7687, 7687], [7689, 7689], [7691, 7691], [7693, 7693], [7695, 7695], [7697, 7697], [7699, 7699], [7701, 7701], [7703, 7703], [7705, 7705], [7707, 7707], [7709, 7709], [7711, 7711], [7713, 7713], [7715, 7715], [7717, 7717], [7719, 7719], [7721, 7721], [7723, 7723], [7725, 7725], [7727, 7727], [7729, 7729], [7731, 7731], [7733, 7733], [7735, 7735], [7737, 7737], [7739, 7739], [7741, 7741], [7743, 7743], [7745, 7745], [7747, 7747], [7749, 7749], [7751, 7751], [7753, 7753], [7755, 7755], [7757, 7757], [7759, 7759], [7761, 7761], [7763, 7763], [7765, 7765], [7767, 7767], [7769, 7769], [7771, 7771], [7773, 7773], [7775, 7775], [7777, 7777], [7779, 7779], [7781, 7781], [7783, 7783], [7785, 7785], [7787, 7787], [7789, 7789], [7791, 7791], [7793, 7793], [7795, 7795], [7797, 7797], [7799, 7799], [7801, 7801], [7803, 7803], [7805, 7805], [7807, 7807], [7809, 7809], [7811, 7811], [7813, 7813], [7815, 7815], [7817, 7817], [7819, 7819], [7821, 7821], [7823, 7823], [7825, 7825], [7827, 7827], [7829, 7837], [7839, 7839], [7841, 7841], [7843, 7843], [7845, 7845], [7847, 7847], [7849, 7849], [7851, 7851], [7853, 7853], [7855, 7855], [7857, 7857], [7859, 7859], [7861, 7861], [7863, 7863], [7865, 7865], [7867, 7867], [7869, 7869], [7871, 7871], [7873, 7873], [7875, 7875], [7877, 7877], [7879, 7879], [7881, 7881], [7883, 7883], [7885, 7885], [7887, 7887], [7889, 7889], [7891, 7891], [7893, 7893], [7895, 7895], [7897, 7897], [7899, 7899], [7901, 7901], [7903, 7903], [7905, 7905], [7907, 7907], [7909, 7909], [7911, 7911], [7913, 7913], [7915, 7915], [7917, 7917], [7919, 7919], [7921, 7921], [7923, 7923], [7925, 7925], [7927, 7927], [7929, 7929], [7931, 7931], [7933, 7933], [7935, 7943], [7952, 7957], [7968, 7975], [7984, 7991], [8000, 8005], [8016, 8023], [8032, 8039], [8048, 8061], [8064, 8071], [8080, 8087], [8096, 8103], [8112, 8116], [8118, 8119], [8126, 8126], [8130, 8132], [8134, 8135], [8144, 8147], [8150, 8151], [8160, 8167], [8178, 8180], [8182, 8183], [8458, 8458], [8462, 8463], [8467, 8467], [8495, 8495], [8500, 8500], [8505, 8505], [8508, 8509], [8518, 8521], [8526, 8526], [8580, 8580], [11312, 11358], [11361, 11361], [11365, 11366], [11368, 11368], [11370, 11370], [11372, 11372], [11377, 11377], [11379, 11380], [11382, 11387], [11393, 11393], [11395, 11395], [11397, 11397], [11399, 11399], [11401, 11401], [11403, 11403], [11405, 11405], [11407, 11407], [11409, 11409], [11411, 11411], [11413, 11413], [11415, 11415], [11417, 11417], [11419, 11419], [11421, 11421], [11423, 11423], [11425, 11425], [11427, 11427], [11429, 11429], [11431, 11431], [11433, 11433], [11435, 11435], [11437, 11437], [11439, 11439], [11441, 11441], [11443, 11443], [11445, 11445], [11447, 11447], [11449, 11449], [11451, 11451], [11453, 11453], [11455, 11455], [11457, 11457], [11459, 11459], [11461, 11461], [11463, 11463], [11465, 11465], [11467, 11467], [11469, 11469], [11471, 11471], [11473, 11473], [11475, 11475], [11477, 11477], [11479, 11479], [11481, 11481], [11483, 11483], [11485, 11485], [11487, 11487], [11489, 11489], [11491, 11492], [11500, 11500], [11502, 11502], [11507, 11507], [11520, 11557], [11559, 11559], [11565, 11565], [42561, 42561], [42563, 42563], [42565, 42565], [42567, 42567], [42569, 42569], [42571, 42571], [42573, 42573], [42575, 42575], [42577, 42577], [42579, 42579], [42581, 42581], [42583, 42583], [42585, 42585], [42587, 42587], [42589, 42589], [42591, 42591], [42593, 42593], [42595, 42595], [42597, 42597], [42599, 42599], [42601, 42601], [42603, 42603], [42605, 42605], [42625, 42625], [42627, 42627], [42629, 42629], [42631, 42631], [42633, 42633], [42635, 42635], [42637, 42637], [42639, 42639], [42641, 42641], [42643, 42643], [42645, 42645], [42647, 42647], [42649, 42649], [42651, 42651], [42787, 42787], [42789, 42789], [42791, 42791], [42793, 42793], [42795, 42795], [42797, 42797], [42799, 42801], [42803, 42803], [42805, 42805], [42807, 42807], [42809, 42809], [42811, 42811], [42813, 42813], [42815, 42815], [42817, 42817], [42819, 42819], [42821, 42821], [42823, 42823], [42825, 42825], [42827, 42827], [42829, 42829], [42831, 42831], [42833, 42833], [42835, 42835], [42837, 42837], [42839, 42839], [42841, 42841], [42843, 42843], [42845, 42845], [42847, 42847], [42849, 42849], [42851, 42851], [42853, 42853], [42855, 42855], [42857, 42857], [42859, 42859], [42861, 42861], [42863, 42863], [42865, 42872], [42874, 42874], [42876, 42876], [42879, 42879], [42881, 42881], [42883, 42883], [42885, 42885], [42887, 42887], [42892, 42892], [42894, 42894], [42897, 42897], [42899, 42901], [42903, 42903], [42905, 42905], [42907, 42907], [42909, 42909], [42911, 42911], [42913, 42913], [42915, 42915], [42917, 42917], [42919, 42919], [42921, 42921], [42933, 42933], [42935, 42935], [43002, 43002], [43824, 43866], [43872, 43877], [43888, 43967], [64256, 64262], [64275, 64279], [65345, 65370]], - "No": [[178, 179], [185, 185], [188, 190], [2548, 2553], [2930, 2935], [3056, 3058], [3192, 3198], [3416, 3422], [3440, 3448], [3882, 3891], [4969, 4988], [6128, 6137], [6618, 6618], [8304, 8304], [8308, 8313], [8320, 8329], [8528, 8543], [8585, 8585], [9312, 9371], [9450, 9471], [10102, 10131], [11517, 11517], [12690, 12693], [12832, 12841], [12872, 12879], [12881, 12895], [12928, 12937], [12977, 12991], [43056, 43061]], - "Zs": [[32, 32], [160, 160], [5760, 5760], [8192, 8202], [8239, 8239], [8287, 8287], [12288, 12288]] - }; - }; -}); -unwrapExports(data_generated); - -var utils$2 = createCommonjsModule(function (module, exports) { - "use strict"; - - exports.__esModule = true; - - function normalize_ranges(ranges) { - return ranges.sort(function (_a, _b) { - var start1 = _a[0]; - var start2 = _b[0]; - return start1 - start2; - }).reduce(function (current, tuple, index) { - if (index === 0) { - return [tuple]; - } - - var _a = current[current.length - 1], - last_start = _a[0], - last_end = _a[1]; - var start = tuple[0], - end = tuple[1]; - return last_end + 1 === start ? current.slice(0, -1).concat([[last_start, end]]) : current.concat([tuple]); - }, []); - } - - exports.normalize_ranges = normalize_ranges; - - function build_regex(ranges, flag) { - var pattern = ranges.map(function (_a) { - var start = _a[0], - end = _a[1]; - return start === end ? "\\u" + get_hex(start) : "\\u" + get_hex(start) + "-\\u" + get_hex(end); - }).join(''); - return new RegExp("[" + pattern + "]", flag); - } - - exports.build_regex = build_regex; - - function get_hex(char_code) { - var hex = char_code.toString(16); - - while (hex.length < 4) { - hex = "0" + hex; - } - - return hex; - } -}); -unwrapExports(utils$2); - -var lib$5 = function lib(categories, flag) { - var data = data_generated.get_data(); - var ranges = categories.reduce(function (current, category) { - return current.concat(data[category]); - }, []); - return utils$2.build_regex(utils$2.normalize_ranges(ranges), flag); -}; - -var emojiRegex = emojiRegex$1(); // eslint-disable-next-line no-control-regex - -var notAsciiRegex = /[^\x20-\x7F]/; -var cjkPattern = lib$3().source; // http://spec.commonmark.org/0.25/#ascii-punctuation-character - -var asciiPunctuationCharRange = escapeStringRegexp("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"); // http://spec.commonmark.org/0.25/#punctuation-character - -var punctuationCharRange = "".concat(asciiPunctuationCharRange).concat(lib$5(["Pc", "Pd", "Pe", "Pf", "Pi", "Po", "Ps"]).source.slice(1, -1)); // remove bracket expression `[` and `]` - -var punctuationRegex = new RegExp("[".concat(punctuationCharRange, "]")); - -function isExportDeclaration(node) { - if (node) { - switch (node.type) { - case "ExportDefaultDeclaration": - case "ExportDefaultSpecifier": - case "DeclareExportDeclaration": - case "ExportNamedDeclaration": - case "ExportAllDeclaration": - return true; - } - } - - return false; -} - -function getParentExportDeclaration(path) { - var parentNode = path.getParentNode(); - - if (path.getName() === "declaration" && isExportDeclaration(parentNode)) { - return parentNode; - } - - return null; -} - -function getPenultimate(arr) { - if (arr.length > 1) { - return arr[arr.length - 2]; - } - - return null; -} - -function getLast$3(arr) { - if (arr.length > 0) { - return arr[arr.length - 1]; - } - - return null; -} - -function skip(chars) { - return function (text, index, opts) { - var backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having - // to check for failures (did someone say monads?). - - if (index === false) { - return false; - } - - var length = text.length; - var cursor = index; - - while (cursor >= 0 && cursor < length) { - var c = text.charAt(cursor); - - if (chars instanceof RegExp) { - if (!chars.test(c)) { - return cursor; - } - } else if (chars.indexOf(c) === -1) { - return cursor; - } - - backwards ? cursor-- : cursor++; - } - - if (cursor === -1 || cursor === length) { - // If we reached the beginning or end of the file, return the - // out-of-bounds cursor. It's up to the caller to handle this - // correctly. We don't want to indicate `false` though if it - // actually skipped valid characters. - return cursor; - } - - return false; - }; -} - -var skipWhitespace = skip(/\s/); -var skipSpaces = skip(" \t"); -var skipToLineEnd = skip(",; \t"); -var skipEverythingButNewLine = skip(/[^\r\n]/); - -function skipInlineComment(text, index) { - if (index === false) { - return false; - } - - if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") { - for (var i = index + 2; i < text.length; ++i) { - if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") { - return i + 2; - } - } - } - - return index; -} - -function skipTrailingComment(text, index) { - if (index === false) { - return false; - } - - if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") { - return skipEverythingButNewLine(text, index); - } - - return index; -} // This one doesn't use the above helper function because it wants to -// test \r\n in order and `skip` doesn't support ordering and we only -// want to skip one newline. It's simple to implement. - - -function skipNewline$1(text, index, opts) { - var backwards = opts && opts.backwards; - - if (index === false) { - return false; - } - - var atIndex = text.charAt(index); - - if (backwards) { - if (text.charAt(index - 1) === "\r" && atIndex === "\n") { - return index - 2; - } - - if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { - return index - 1; - } - } else { - if (atIndex === "\r" && text.charAt(index + 1) === "\n") { - return index + 2; - } - - if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { - return index + 1; - } - } - - return index; -} - -function hasNewline$1(text, index, opts) { - opts = opts || {}; - var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); - var idx2 = skipNewline$1(text, idx, opts); - return idx !== idx2; -} - -function hasNewlineInRange(text, start, end) { - for (var i = start; i < end; ++i) { - if (text.charAt(i) === "\n") { - return true; - } - } - - return false; -} // Note: this function doesn't ignore leading comments unlike isNextLineEmpty - - -function isPreviousLineEmpty$1(text, node, locStart) { - var idx = locStart(node) - 1; - idx = skipSpaces(text, idx, { - backwards: true - }); - idx = skipNewline$1(text, idx, { - backwards: true - }); - idx = skipSpaces(text, idx, { - backwards: true - }); - var idx2 = skipNewline$1(text, idx, { - backwards: true - }); - return idx !== idx2; -} - -function isNextLineEmptyAfterIndex(text, index) { - var oldIdx = null; - var idx = index; - - while (idx !== oldIdx) { - // We need to skip all the potential trailing inline comments - oldIdx = idx; - idx = skipToLineEnd(text, idx); - idx = skipInlineComment(text, idx); - idx = skipSpaces(text, idx); - } - - idx = skipTrailingComment(text, idx); - idx = skipNewline$1(text, idx); - return hasNewline$1(text, idx); -} - -function isNextLineEmpty(text, node, locEnd) { - return isNextLineEmptyAfterIndex(text, locEnd(node)); -} - -function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) { - var oldIdx = null; - var idx = locEnd(node); - - while (idx !== oldIdx) { - oldIdx = idx; - idx = skipSpaces(text, idx); - idx = skipInlineComment(text, idx); - idx = skipTrailingComment(text, idx); - idx = skipNewline$1(text, idx); - } - - return idx; -} - -function getNextNonSpaceNonCommentCharacter(text, node, locEnd) { - return text.charAt(getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)); -} - -function hasSpaces(text, index, opts) { - opts = opts || {}; - var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); - return idx !== index; -} - -function setLocStart(node, index) { - if (node.range) { - node.range[0] = index; - } else { - node.start = index; - } -} - -function setLocEnd(node, index) { - if (node.range) { - node.range[1] = index; - } else { - node.end = index; - } -} - -var PRECEDENCE = {}; -[["|>"], ["||", "??"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach(function (tier, i) { - tier.forEach(function (op) { - PRECEDENCE[op] = i; - }); -}); - -function getPrecedence(op) { - return PRECEDENCE[op]; -} - -var equalityOperators = { - "==": true, - "!=": true, - "===": true, - "!==": true -}; -var additiveOperators = { - "+": true, - "-": true -}; -var multiplicativeOperators = { - "*": true, - "/": true, - "%": true -}; -var bitshiftOperators = { - ">>": true, - ">>>": true, - "<<": true -}; - -function shouldFlatten(parentOp, nodeOp) { - if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) { - // x + y % z --> (x + y) % z - if (nodeOp === "%" && !additiveOperators[parentOp]) { - return true; - } - - return false; - } // ** is right-associative - // x ** y ** z --> x ** (y ** z) - - - if (parentOp === "**") { - return false; - } // x == y == z --> (x == y) == z - - - if (equalityOperators[parentOp] && equalityOperators[nodeOp]) { - return false; - } // x * y % z --> (x * y) % z - - - if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) { - return false; - } // x * y / z --> (x * y) / z - // x / y * z --> (x / y) * z - - - if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) { - return false; - } // x << y << z --> (x << y) << z - - - if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) { - return false; - } - - return true; -} - -function isBitwiseOperator(operator) { - return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&"; -} // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr -// holds) `function`, `class`, or `do {}`. Will be overzealous if there's -// already necessary grouping parentheses. - - -function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) { - node = getLeftMost(node); - - switch (node.type) { - // Hack. Remove after https://github.com/eslint/typescript-eslint-parser/issues/331 - case "ObjectPattern": - return !forbidFunctionClassAndDoExpr; - - case "FunctionExpression": - case "ClassExpression": - case "DoExpression": - return forbidFunctionClassAndDoExpr; - - case "ObjectExpression": - return true; - - case "MemberExpression": - return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); - - case "TaggedTemplateExpression": - if (node.tag.type === "FunctionExpression") { - // IIFEs are always already parenthesized - return false; - } - - return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr); - - case "CallExpression": - if (node.callee.type === "FunctionExpression") { - // IIFEs are always already parenthesized - return false; - } - - return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr); - - case "ConditionalExpression": - return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr); - - case "UpdateExpression": - return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr); - - case "BindExpression": - return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); - - case "SequenceExpression": - return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr); - - case "TSAsExpression": - return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr); - - default: - return false; - } -} - -function getLeftMost(node) { - if (node.left) { - return getLeftMost(node.left); - } - - return node; -} - -function getAlignmentSize(value, tabWidth, startIndex) { - startIndex = startIndex || 0; - var size = 0; - - for (var i = startIndex; i < value.length; ++i) { - if (value[i] === "\t") { - // Tabs behave in a way that they are aligned to the nearest - // multiple of tabWidth: - // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4 - // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ... - size = size + tabWidth - size % tabWidth; - } else { - size++; - } - } - - return size; -} - -function getIndentSize(value, tabWidth) { - var lastNewlineIndex = value.lastIndexOf("\n"); - - if (lastNewlineIndex === -1) { - return 0; - } - - return getAlignmentSize( // All the leading whitespaces - value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth); -} - -function printString(raw, options, isDirectiveLiteral) { - // `rawContent` is the string exactly like it appeared in the input source - // code, without its enclosing quotes. - var rawContent = raw.slice(1, -1); - var double = { - quote: '"', - regex: /"/g - }; - var single = { - quote: "'", - regex: /'/g - }; - var preferred = options.singleQuote ? single : double; - var alternate = preferred === single ? double : single; - var shouldUseAlternateQuote = false; - var canChangeDirectiveQuotes = false; // If `rawContent` contains at least one of the quote preferred for enclosing - // the string, we might want to enclose with the alternate quote instead, to - // minimize the number of escaped quotes. - // Also check for the alternate quote, to determine if we're allowed to swap - // the quotes on a DirectiveLiteral. - - if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) { - var numPreferredQuotes = (rawContent.match(preferred.regex) || []).length; - var numAlternateQuotes = (rawContent.match(alternate.regex) || []).length; - shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes; - } else { - canChangeDirectiveQuotes = true; - } - - var enclosingQuote = options.parser === "json" ? double.quote : shouldUseAlternateQuote ? alternate.quote : preferred.quote; // Directives are exact code unit sequences, which means that you can't - // change the escape sequences they use. - // See https://github.com/prettier/prettier/issues/1555 - // and https://tc39.github.io/ecma262/#directive-prologue - - if (isDirectiveLiteral) { - if (canChangeDirectiveQuotes) { - return enclosingQuote + rawContent + enclosingQuote; - } - - return raw; - } // It might sound unnecessary to use `makeString` even if the string already - // is enclosed with `enclosingQuote`, but it isn't. The string could contain - // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes - // sure that we consistently output the minimum amount of escaped quotes. - - - return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss")); -} - -function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) { - var otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double). - - var regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to - // enclose `rawContent` with `enclosingQuote`. - - var newContent = rawContent.replace(regex, function (match, escaped, quote) { - // If we matched an escape, and the escaped character is a quote of the - // other type than we intend to enclose the string with, there's no need for - // it to be escaped, so return it _without_ the backslash. - if (escaped === otherQuote) { - return escaped; - } // If we matched an unescaped quote and it is of the _same_ type as we - // intend to enclose the string with, it must be escaped, so return it with - // a backslash. - - - if (quote === enclosingQuote) { - return "\\" + quote; - } - - if (quote) { - return quote; - } // Unescape any unnecessarily escaped character. - // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27 - - - return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped; - }); - return enclosingQuote + newContent + enclosingQuote; -} - -function printNumber(rawNumber) { - return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation. - .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0). - .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit. - .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes. - .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot. - .replace(/\.(?=e|$)/, ""); -} - -function getMaxContinuousCount(str, target) { - var results = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g")); - - if (results === null) { - return 0; - } - - return results.reduce(function (maxCount, result) { - return Math.max(maxCount, result.length / target.length); - }, 0); -} -/** - * split text into whitespaces and words - * @param {string} text - * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>} - */ - - -function splitText(text, options) { - var KIND_NON_CJK = "non-cjk"; - var KIND_CJK_CHARACTER = "cjk-character"; - var KIND_CJK_PUNCTUATION = "cjk-punctuation"; - var nodes = []; - (options.proseWrap === "preserve" ? text : text.replace(new RegExp("(".concat(cjkPattern, ")\n(").concat(cjkPattern, ")"), "g"), "$1$2")).split(/([ \t\n]+)/).forEach(function (token, index, tokens) { - // whitespace - if (index % 2 === 1) { - nodes.push({ - type: "whitespace", - value: /\n/.test(token) ? "\n" : " " - }); - return; - } // word separated by whitespace - - - if ((index === 0 || index === tokens.length - 1) && token === "") { - return; - } - - token.split(new RegExp("(".concat(cjkPattern, ")"))).forEach(function (innerToken, innerIndex, innerTokens) { - if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") { - return; - } // non-CJK word - - - if (innerIndex % 2 === 0) { - if (innerToken !== "") { - appendNode({ - type: "word", - value: innerToken, - kind: KIND_NON_CJK, - hasLeadingPunctuation: punctuationRegex.test(innerToken[0]), - hasTrailingPunctuation: punctuationRegex.test(getLast$3(innerToken)) - }); - } - - return; - } // CJK character - - - appendNode(punctuationRegex.test(innerToken) ? { - type: "word", - value: innerToken, - kind: KIND_CJK_PUNCTUATION, - hasLeadingPunctuation: true, - hasTrailingPunctuation: true - } : { - type: "word", - value: innerToken, - kind: KIND_CJK_CHARACTER, - hasLeadingPunctuation: false, - hasTrailingPunctuation: false - }); - }); - }); - return nodes; - - function appendNode(node) { - var lastNode = getLast$3(nodes); - - if (lastNode && lastNode.type === "word") { - if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJK_CHARACTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJK_CHARACTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) { - nodes.push({ - type: "whitespace", - value: " " - }); - } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace - ![lastNode.value, node.value].some(function (value) { - return /\u3000/.test(value); - })) { - nodes.push({ - type: "whitespace", - value: "" - }); - } - } - - nodes.push(node); - - function isBetween(kind1, kind2) { - return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1; - } - } -} - -function getStringWidth$1(text) { - if (!text) { - return 0; - } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width` - - - if (!notAsciiRegex.test(text)) { - return text.length; - } // emojis are considered 2-char width for consistency - // see https://github.com/sindresorhus/string-width/issues/11 - // for the reason why not implemented in `string-width` - - - return stringWidth(text.replace(emojiRegex, " ")); -} - -function hasIgnoreComment(path) { - var node = path.getValue(); - return hasNodeIgnoreComment(node); -} - -function hasNodeIgnoreComment(node) { - return node && node.comments && node.comments.length > 0 && node.comments.some(function (comment) { - return comment.value.trim() === "prettier-ignore"; - }); -} - -function matchAncestorTypes(path, types, index) { - index = index || 0; - types = types.slice(); - - while (types.length) { - var parent = path.getParentNode(index); - var type = types.shift(); - - if (!parent || parent.type !== type) { - return false; - } - - index++; - } - - return true; -} - -function addCommentHelper(node, comment) { - var comments = node.comments || (node.comments = []); - comments.push(comment); - comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment - // We already "print" it via the raw text, we don't need to re-print it as a - // comment - - if (node.type === "JSXText") { - comment.printed = true; - } -} - -function addLeadingComment$1(node, comment) { - comment.leading = true; - comment.trailing = false; - addCommentHelper(node, comment); -} - -function addDanglingComment$1(node, comment) { - comment.leading = false; - comment.trailing = false; - addCommentHelper(node, comment); -} - -function addTrailingComment$1(node, comment) { - comment.leading = false; - comment.trailing = true; - addCommentHelper(node, comment); -} - -function isWithinParentArrayProperty(path, propertyName) { - var node = path.getValue(); - var parent = path.getParentNode(); - - if (parent == null) { - return false; - } - - if (!Array.isArray(parent[propertyName])) { - return false; - } - - var key = path.getName(); - return parent[propertyName][key] === node; -} - -var util = { - punctuationRegex: punctuationRegex, - punctuationCharRange: punctuationCharRange, - getStringWidth: getStringWidth$1, - splitText: splitText, - getMaxContinuousCount: getMaxContinuousCount, - getPrecedence: getPrecedence, - shouldFlatten: shouldFlatten, - isBitwiseOperator: isBitwiseOperator, - isExportDeclaration: isExportDeclaration, - getParentExportDeclaration: getParentExportDeclaration, - getPenultimate: getPenultimate, - getLast: getLast$3, - getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex, - getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter, - skipWhitespace: skipWhitespace, - skipSpaces: skipSpaces, - skipNewline: skipNewline$1, - isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex, - isNextLineEmpty: isNextLineEmpty, - isPreviousLineEmpty: isPreviousLineEmpty$1, - hasNewline: hasNewline$1, - hasNewlineInRange: hasNewlineInRange, - hasSpaces: hasSpaces, - setLocStart: setLocStart, - setLocEnd: setLocEnd, - startsWithNoLookaheadToken: startsWithNoLookaheadToken, - getAlignmentSize: getAlignmentSize, - getIndentSize: getIndentSize, - printString: printString, - printNumber: printNumber, - hasIgnoreComment: hasIgnoreComment, - hasNodeIgnoreComment: hasNodeIgnoreComment, - makeString: makeString, - matchAncestorTypes: matchAncestorTypes, - addLeadingComment: addLeadingComment$1, - addDanglingComment: addDanglingComment$1, - addTrailingComment: addTrailingComment$1, - isWithinParentArrayProperty: isWithinParentArrayProperty -}; - -var getStringWidth = util.getStringWidth; -var concat$2 = docBuilders.concat; -var fill$1 = docBuilders.fill; -var cursor$2 = docBuilders.cursor; -/** @type {{[groupId: PropertyKey]: MODE}} */ - -var groupModeMap; -var MODE_BREAK = 1; -var MODE_FLAT = 2; - -function rootIndent() { - return { - value: "", - length: 0, - queue: [] - }; -} - -function makeIndent(ind, options) { - return generateInd(ind, { - type: "indent" - }, options); -} - -function makeAlign(ind, n, options) { - return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, { - type: "dedent" - }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, { - root: ind - }) : typeof n === "string" ? generateInd(ind, { - type: "stringAlign", - n: n - }, options) : generateInd(ind, { - type: "numberAlign", - n: n - }, options); -} - -function generateInd(ind, newPart, options) { - var queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart); - var value = ""; - var length = 0; - var lastTabs = 0; - var lastSpaces = 0; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = queue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var part = _step.value; - - switch (part.type) { - case "indent": - flush(); - - if (options.useTabs) { - addTabs(1); - } else { - addSpaces(options.tabWidth); - } - - break; - - case "stringAlign": - flush(); - value += part.n; - length += part.n.length; - break; - - case "numberAlign": - lastTabs += 1; - lastSpaces += part.n; - break; - - /* istanbul ignore next */ - - default: - throw new Error("Unexpected type '".concat(part.type, "'")); - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - flushSpaces(); - return Object.assign({}, ind, { - value: value, - length: length, - queue: queue - }); - - function addTabs(count) { - value += "\t".repeat(count); - length += options.tabWidth * count; - } - - function addSpaces(count) { - value += " ".repeat(count); - length += count; - } - - function flush() { - if (options.useTabs) { - flushTabs(); - } else { - flushSpaces(); - } - } - - function flushTabs() { - if (lastTabs > 0) { - addTabs(lastTabs); - } - - resetLast(); - } - - function flushSpaces() { - if (lastSpaces > 0) { - addSpaces(lastSpaces); - } - - resetLast(); - } - - function resetLast() { - lastTabs = 0; - lastSpaces = 0; - } -} - -function fits(next, restCommands, width, options, mustBeFlat) { - var restIdx = restCommands.length; - var cmds = [next]; - - while (width >= 0) { - if (cmds.length === 0) { - if (restIdx === 0) { - return true; - } - - cmds.push(restCommands[restIdx - 1]); - restIdx--; - continue; - } - - var x = cmds.pop(); - var ind = x[0]; - var mode = x[1]; - var doc = x[2]; - - if (typeof doc === "string") { - width -= getStringWidth(doc); - } else { - switch (doc.type) { - case "concat": - for (var i = doc.parts.length - 1; i >= 0; i--) { - cmds.push([ind, mode, doc.parts[i]]); - } - - break; - - case "indent": - cmds.push([makeIndent(ind, options), mode, doc.contents]); - break; - - case "align": - cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); - break; - - case "group": - if (mustBeFlat && doc.break) { - return false; - } - - cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]); - - if (doc.id) { - groupModeMap[doc.id] = cmds[cmds.length - 1][1]; - } - - break; - - case "fill": - for (var _i = doc.parts.length - 1; _i >= 0; _i--) { - cmds.push([ind, mode, doc.parts[_i]]); - } - - break; - - case "if-break": - { - var groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; - - if (groupMode === MODE_BREAK) { - if (doc.breakContents) { - cmds.push([ind, mode, doc.breakContents]); - } - } - - if (groupMode === MODE_FLAT) { - if (doc.flatContents) { - cmds.push([ind, mode, doc.flatContents]); - } - } - - break; - } - - case "line": - switch (mode) { - // fallthrough - case MODE_FLAT: - if (!doc.hard) { - if (!doc.soft) { - width -= 1; - } - - break; - } - - return true; - - case MODE_BREAK: - return true; - } - - break; - } - } - } - - return false; -} - -function printDocToString(doc, options) { - groupModeMap = {}; - var width = options.printWidth; - var newLine = options.newLine || "\n"; - var pos = 0; // cmds is basically a stack. We've turned a recursive call into a - // while loop which is much faster. The while loop below adds new - // cmds to the array instead of recursively calling `print`. - - var cmds = [[rootIndent(), MODE_BREAK, doc]]; - var out = []; - var shouldRemeasure = false; - var lineSuffix = []; - - while (cmds.length !== 0) { - var x = cmds.pop(); - var ind = x[0]; - var mode = x[1]; - var _doc = x[2]; - - if (typeof _doc === "string") { - out.push(_doc); - pos += getStringWidth(_doc); - } else { - switch (_doc.type) { - case "cursor": - out.push(cursor$2.placeholder); - break; - - case "concat": - for (var i = _doc.parts.length - 1; i >= 0; i--) { - cmds.push([ind, mode, _doc.parts[i]]); - } - - break; - - case "indent": - cmds.push([makeIndent(ind, options), mode, _doc.contents]); - break; - - case "align": - cmds.push([makeAlign(ind, _doc.n, options), mode, _doc.contents]); - break; - - case "group": - switch (mode) { - case MODE_FLAT: - if (!shouldRemeasure) { - cmds.push([ind, _doc.break ? MODE_BREAK : MODE_FLAT, _doc.contents]); - break; - } - - // fallthrough - - case MODE_BREAK: - { - shouldRemeasure = false; - var next = [ind, MODE_FLAT, _doc.contents]; - var rem = width - pos; - - if (!_doc.break && fits(next, cmds, rem, options)) { - cmds.push(next); - } else { - // Expanded states are a rare case where a document - // can manually provide multiple representations of - // itself. It provides an array of documents - // going from the least expanded (most flattened) - // representation first to the most expanded. If a - // group has these, we need to manually go through - // these states and find the first one that fits. - if (_doc.expandedStates) { - var mostExpanded = _doc.expandedStates[_doc.expandedStates.length - 1]; - - if (_doc.break) { - cmds.push([ind, MODE_BREAK, mostExpanded]); - break; - } else { - for (var _i2 = 1; _i2 < _doc.expandedStates.length + 1; _i2++) { - if (_i2 >= _doc.expandedStates.length) { - cmds.push([ind, MODE_BREAK, mostExpanded]); - break; - } else { - var state = _doc.expandedStates[_i2]; - var cmd = [ind, MODE_FLAT, state]; - - if (fits(cmd, cmds, rem, options)) { - cmds.push(cmd); - break; - } - } - } - } - } else { - cmds.push([ind, MODE_BREAK, _doc.contents]); - } - } - - break; - } - } - - if (_doc.id) { - groupModeMap[_doc.id] = cmds[cmds.length - 1][1]; - } - - break; - // Fills each line with as much code as possible before moving to a new - // line with the same indentation. - // - // Expects doc.parts to be an array of alternating content and - // whitespace. The whitespace contains the linebreaks. - // - // For example: - // ["I", line, "love", line, "monkeys"] - // or - // [{ type: group, ... }, softline, { type: group, ... }] - // - // It uses this parts structure to handle three main layout cases: - // * The first two content items fit on the same line without - // breaking - // -> output the first content item and the whitespace "flat". - // * Only the first content item fits on the line without breaking - // -> output the first content item "flat" and the whitespace with - // "break". - // * Neither content item fits on the line without breaking - // -> output the first content item and the whitespace with "break". - - case "fill": - { - var _rem = width - pos; - - var parts = _doc.parts; - - if (parts.length === 0) { - break; - } - - var content = parts[0]; - var contentFlatCmd = [ind, MODE_FLAT, content]; - var contentBreakCmd = [ind, MODE_BREAK, content]; - var contentFits = fits(contentFlatCmd, [], _rem, options, true); - - if (parts.length === 1) { - if (contentFits) { - cmds.push(contentFlatCmd); - } else { - cmds.push(contentBreakCmd); - } - - break; - } - - var whitespace = parts[1]; - var whitespaceFlatCmd = [ind, MODE_FLAT, whitespace]; - var whitespaceBreakCmd = [ind, MODE_BREAK, whitespace]; - - if (parts.length === 2) { - if (contentFits) { - cmds.push(whitespaceFlatCmd); - cmds.push(contentFlatCmd); - } else { - cmds.push(whitespaceBreakCmd); - cmds.push(contentBreakCmd); - } - - break; - } // At this point we've handled the first pair (context, separator) - // and will create a new fill doc for the rest of the content. - // Ideally we wouldn't mutate the array here but coping all the - // elements to a new array would make this algorithm quadratic, - // which is unusable for large arrays (e.g. large texts in JSX). - - - parts.splice(0, 2); - var remainingCmd = [ind, mode, fill$1(parts)]; - var secondContent = parts[0]; - var firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$2([content, whitespace, secondContent])]; - var firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], _rem, options, true); - - if (firstAndSecondContentFits) { - cmds.push(remainingCmd); - cmds.push(whitespaceFlatCmd); - cmds.push(contentFlatCmd); - } else if (contentFits) { - cmds.push(remainingCmd); - cmds.push(whitespaceBreakCmd); - cmds.push(contentFlatCmd); - } else { - cmds.push(remainingCmd); - cmds.push(whitespaceBreakCmd); - cmds.push(contentBreakCmd); - } - - break; - } - - case "if-break": - { - var groupMode = _doc.groupId ? groupModeMap[_doc.groupId] : mode; - - if (groupMode === MODE_BREAK) { - if (_doc.breakContents) { - cmds.push([ind, mode, _doc.breakContents]); - } - } - - if (groupMode === MODE_FLAT) { - if (_doc.flatContents) { - cmds.push([ind, mode, _doc.flatContents]); - } - } - - break; - } - - case "line-suffix": - lineSuffix.push([ind, mode, _doc.contents]); - break; - - case "line-suffix-boundary": - if (lineSuffix.length > 0) { - cmds.push([ind, mode, { - type: "line", - hard: true - }]); - } - - break; - - case "line": - switch (mode) { - case MODE_FLAT: - if (!_doc.hard) { - if (!_doc.soft) { - out.push(" "); - pos += 1; - } - - break; - } else { - // This line was forced into the output even if we - // were in flattened mode, so we need to tell the next - // group that no matter what, it needs to remeasure - // because the previous measurement didn't accurately - // capture the entire expression (this is necessary - // for nested groups) - shouldRemeasure = true; - } - - // fallthrough - - case MODE_BREAK: - if (lineSuffix.length) { - cmds.push([ind, mode, _doc]); - [].push.apply(cmds, lineSuffix.reverse()); - lineSuffix = []; - break; - } - - if (_doc.literal) { - if (ind.root) { - out.push(newLine, ind.root.value); - pos = ind.root.length; - } else { - out.push(newLine); - pos = 0; - } - } else { - if (out.length > 0) { - // Trim whitespace at the end of line - while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[^\S\n]*$/)) { - out.pop(); - } - - if (out.length && typeof out[out.length - 1] === "string") { - out[out.length - 1] = out[out.length - 1].replace(/[^\S\n]*$/, ""); - } - } - - out.push(newLine + ind.value); - pos = ind.length; - } - - break; - } - - break; - - default: - } - } - } - - var cursorPlaceholderIndex = out.indexOf(cursor$2.placeholder); - - if (cursorPlaceholderIndex !== -1) { - var otherCursorPlaceholderIndex = out.indexOf(cursor$2.placeholder, cursorPlaceholderIndex + 1); - var beforeCursor = out.slice(0, cursorPlaceholderIndex).join(""); - var aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join(""); - var afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join(""); - return { - formatted: beforeCursor + aroundCursor + afterCursor, - cursorNodeStart: beforeCursor.length, - cursorNodeText: aroundCursor - }; - } - - return { - formatted: out.join("") - }; -} - -var docPrinter = { - printDocToString: printDocToString -}; - -var traverseDocOnExitStackMarker = {}; - -function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { - var docsStack = [doc]; - - while (docsStack.length !== 0) { - var _doc = docsStack.pop(); - - if (_doc === traverseDocOnExitStackMarker) { - onExit(docsStack.pop()); - continue; - } - - var shouldRecurse = true; - - if (onEnter) { - if (onEnter(_doc) === false) { - shouldRecurse = false; - } - } - - if (onExit) { - docsStack.push(_doc); - docsStack.push(traverseDocOnExitStackMarker); - } - - if (shouldRecurse) { - // When there are multiple parts to process, - // the parts need to be pushed onto the stack in reverse order, - // so that they are processed in the original order - // when the stack is popped. - if (_doc.type === "concat" || _doc.type === "fill") { - for (var ic = _doc.parts.length, i = ic - 1; i >= 0; --i) { - docsStack.push(_doc.parts[i]); - } - } else if (_doc.type === "if-break") { - if (_doc.flatContents) { - docsStack.push(_doc.flatContents); - } - - if (_doc.breakContents) { - docsStack.push(_doc.breakContents); - } - } else if (_doc.type === "group" && _doc.expandedStates) { - if (shouldTraverseConditionalGroups) { - for (var _ic = _doc.expandedStates.length, _i = _ic - 1; _i >= 0; --_i) { - docsStack.push(_doc.expandedStates[_i]); - } - } else { - docsStack.push(_doc.contents); - } - } else if (_doc.contents) { - docsStack.push(_doc.contents); - } - } - } -} - -function mapDoc(doc, cb) { - if (doc.type === "concat" || doc.type === "fill") { - var parts = doc.parts.map(function (part) { - return mapDoc(part, cb); - }); - return cb(Object.assign({}, doc, { - parts: parts - })); - } else if (doc.type === "if-break") { - var breakContents = doc.breakContents && mapDoc(doc.breakContents, cb); - var flatContents = doc.flatContents && mapDoc(doc.flatContents, cb); - return cb(Object.assign({}, doc, { - breakContents: breakContents, - flatContents: flatContents - })); - } else if (doc.contents) { - var contents = mapDoc(doc.contents, cb); - return cb(Object.assign({}, doc, { - contents: contents - })); - } - - return cb(doc); -} - -function findInDoc(doc, fn, defaultValue) { - var result = defaultValue; - var hasStopped = false; - - function findInDocOnEnterFn(doc) { - var maybeResult = fn(doc); - - if (maybeResult !== undefined) { - hasStopped = true; - result = maybeResult; - } - - if (hasStopped) { - return false; - } - } - - traverseDoc(doc, findInDocOnEnterFn); - return result; -} - -function isEmpty(n) { - return typeof n === "string" && n.length === 0; -} - -function isLineNextFn(doc) { - if (typeof doc === "string") { - return false; - } - - if (doc.type === "line") { - return true; - } -} - -function isLineNext(doc) { - return findInDoc(doc, isLineNextFn, false); -} - -function willBreakFn(doc) { - if (doc.type === "group" && doc.break) { - return true; - } - - if (doc.type === "line" && doc.hard) { - return true; - } - - if (doc.type === "break-parent") { - return true; - } -} - -function willBreak(doc) { - return findInDoc(doc, willBreakFn, false); -} - -function breakParentGroup(groupStack) { - if (groupStack.length > 0) { - var parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because - // the user is expected to manually handle what breaks. - - if (!parentGroup.expandedStates) { - parentGroup.break = true; - } - } - - return null; -} - -function propagateBreaks(doc) { - var alreadyVisitedSet = new Set(); - var groupStack = []; - - function propagateBreaksOnEnterFn(doc) { - if (doc.type === "break-parent") { - breakParentGroup(groupStack); - } - - if (doc.type === "group") { - groupStack.push(doc); - - if (alreadyVisitedSet.has(doc)) { - return false; - } - - alreadyVisitedSet.add(doc); - } - } - - function propagateBreaksOnExitFn(doc) { - if (doc.type === "group") { - var group = groupStack.pop(); - - if (group.break) { - breakParentGroup(groupStack); - } - } - } - - traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn, - /* shouldTraverseConditionalGroups */ - true); -} - -function removeLinesFn(doc) { - // Force this doc into flat mode by statically converting all - // lines into spaces (or soft lines into nothing). Hard lines - // should still output because there's too great of a chance - // of breaking existing assumptions otherwise. - if (doc.type === "line" && !doc.hard) { - return doc.soft ? "" : " "; - } else if (doc.type === "if-break") { - return doc.flatContents || ""; - } - - return doc; -} - -function removeLines(doc) { - return mapDoc(doc, removeLinesFn); -} - -function stripTrailingHardline(doc) { - // HACK remove ending hardline, original PR: #1984 - if (doc.type === "concat" && doc.parts.length === 2 && doc.parts[1].type === "concat" && doc.parts[1].parts.length === 2 && doc.parts[1].parts[0].hard && doc.parts[1].parts[1].type === "break-parent") { - return doc.parts[0]; - } - - return doc; -} - -var docUtils = { - isEmpty: isEmpty, - willBreak: willBreak, - isLineNext: isLineNext, - traverseDoc: traverseDoc, - mapDoc: mapDoc, - propagateBreaks: propagateBreaks, - removeLines: removeLines, - stripTrailingHardline: stripTrailingHardline -}; - -function flattenDoc(doc) { - if (doc.type === "concat") { - var res = []; - - for (var i = 0; i < doc.parts.length; ++i) { - var doc2 = doc.parts[i]; - - if (typeof doc2 !== "string" && doc2.type === "concat") { - [].push.apply(res, flattenDoc(doc2).parts); - } else { - var flattened = flattenDoc(doc2); - - if (flattened !== "") { - res.push(flattened); - } - } - } - - return Object.assign({}, doc, { - parts: res - }); - } else if (doc.type === "if-break") { - return Object.assign({}, doc, { - breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null, - flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null - }); - } else if (doc.type === "group") { - return Object.assign({}, doc, { - contents: flattenDoc(doc.contents), - expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates - }); - } else if (doc.contents) { - return Object.assign({}, doc, { - contents: flattenDoc(doc.contents) - }); - } - - return doc; -} - -function printDoc(doc) { - if (typeof doc === "string") { - return JSON.stringify(doc); - } - - if (doc.type === "line") { - if (doc.literalline) { - return "literalline"; - } - - if (doc.hard) { - return "hardline"; - } - - if (doc.soft) { - return "softline"; - } - - return "line"; - } - - if (doc.type === "break-parent") { - return "breakParent"; - } - - if (doc.type === "concat") { - return "[" + doc.parts.map(printDoc).join(", ") + "]"; - } - - if (doc.type === "indent") { - return "indent(" + printDoc(doc.contents) + ")"; - } - - if (doc.type === "align") { - 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) + ")"; - } - - if (doc.type === "if-break") { - return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")"; - } - - if (doc.type === "group") { - if (doc.expandedStates) { - return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])"; - } - - return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")"; - } - - if (doc.type === "fill") { - return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")"; - } - - if (doc.type === "line-suffix") { - return "lineSuffix(" + printDoc(doc.contents) + ")"; - } - - if (doc.type === "line-suffix-boundary") { - return "lineSuffixBoundary"; - } - - throw new Error("Unknown doc type " + doc.type); -} - -var docDebug = { - printDocToDebug: function printDocToDebug(doc) { - return printDoc(flattenDoc(doc)); - } -}; - -var doc = { - builders: docBuilders, - printer: docPrinter, - utils: docUtils, - debug: docDebug -}; - -var mapDoc$1 = doc.utils.mapDoc; - -function isNextLineEmpty$1(text, node, options) { - return util.isNextLineEmpty(text, node, options.locEnd); -} - -function isPreviousLineEmpty$2(text, node, options) { - return util.isPreviousLineEmpty(text, node, options.locStart); -} - -function getNextNonSpaceNonCommentCharacterIndex$1(text, node, options) { - return util.getNextNonSpaceNonCommentCharacterIndex(text, node, options.locEnd); -} - -var utilShared = { - isNextLineEmpty: isNextLineEmpty$1, - isNextLineEmptyAfterIndex: util.isNextLineEmptyAfterIndex, - isPreviousLineEmpty: isPreviousLineEmpty$2, - getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, - mapDoc: mapDoc$1, - // TODO: remove in 2.0, we already exposed it in docUtils - makeString: util.makeString, - addLeadingComment: util.addLeadingComment, - addDanglingComment: util.addDanglingComment, - addTrailingComment: util.addTrailingComment -}; - -var assert$3 = ( assert$2 && assert ) || assert$2; - -var _require$$0$builders = doc.builders; -var concat = _require$$0$builders.concat; -var hardline = _require$$0$builders.hardline; -var breakParent = _require$$0$builders.breakParent; -var indent = _require$$0$builders.indent; -var lineSuffix = _require$$0$builders.lineSuffix; -var join = _require$$0$builders.join; -var cursor = _require$$0$builders.cursor; -var hasNewline = util.hasNewline; -var skipNewline = util.skipNewline; -var isPreviousLineEmpty = util.isPreviousLineEmpty; -var addLeadingComment = utilShared.addLeadingComment; -var addDanglingComment = utilShared.addDanglingComment; -var addTrailingComment = utilShared.addTrailingComment; -var childNodesCacheKey = Symbol("child-nodes"); - -function getSortedChildNodes(node, options, resultArray) { - if (!node) { - return; - } - - var printer = options.printer, - locStart = options.locStart, - locEnd = options.locEnd; - - if (resultArray) { - if (node && printer.canAttachComment && printer.canAttachComment(node)) { - // This reverse insertion sort almost always takes constant - // time because we almost always (maybe always?) append the - // nodes in order anyway. - var i; - - for (i = resultArray.length - 1; i >= 0; --i) { - if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) { - break; - } - } - - resultArray.splice(i + 1, 0, node); - return; - } - } else if (node[childNodesCacheKey]) { - return node[childNodesCacheKey]; - } - - var childNodes; - - if (printer.getCommentChildNodes) { - childNodes = printer.getCommentChildNodes(node); - } else if (node && _typeof(node) === "object") { - childNodes = Object.keys(node).filter(function (n) { - return n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode"; - }).map(function (n) { - return node[n]; - }); - } - - if (!childNodes) { - return; - } - - if (!resultArray) { - Object.defineProperty(node, childNodesCacheKey, { - value: resultArray = [], - enumerable: false - }); - } - - childNodes.forEach(function (childNode) { - getSortedChildNodes(childNode, options, resultArray); - }); - return resultArray; -} // As efficiently as possible, decorate the comment object with -// .precedingNode, .enclosingNode, and/or .followingNode properties, at -// least one of which is guaranteed to be defined. - - -function decorateComment(node, comment, options) { - var locStart = options.locStart, - locEnd = options.locEnd; - var childNodes = getSortedChildNodes(node, options); - var precedingNode; - var followingNode; // Time to dust off the old binary search robes and wizard hat. - - var left = 0; - var right = childNodes.length; - - while (left < right) { - var middle = left + right >> 1; - var child = childNodes[middle]; - - if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) { - // The comment is completely contained by this child node. - comment.enclosingNode = child; - decorateComment(child, comment, options); - return; // Abandon the binary search at this level. - } - - if (locEnd(child) - locStart(comment) <= 0) { - // This child node falls completely before the comment. - // Because we will never consider this node or any nodes - // before it again, this node must be the closest preceding - // node we have encountered so far. - precedingNode = child; - left = middle + 1; - continue; - } - - if (locEnd(comment) - locStart(child) <= 0) { - // This child node falls completely after the comment. - // Because we will never consider this node or any nodes after - // it again, this node must be the closest following node we - // have encountered so far. - followingNode = child; - right = middle; - continue; - } - /* istanbul ignore next */ - - - throw new Error("Comment location overlaps with node location"); - } // We don't want comments inside of different expressions inside of the same - // template literal to move to another expression. - - - if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") { - var quasis = comment.enclosingNode.quasis; - var commentIndex = findExpressionIndexForComment(quasis, comment, options); - - if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) { - precedingNode = null; - } - - if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) { - followingNode = null; - } - } - - if (precedingNode) { - comment.precedingNode = precedingNode; - } - - if (followingNode) { - comment.followingNode = followingNode; - } -} - -function attach(comments, ast, text, options) { - if (!Array.isArray(comments)) { - return; - } - - var tiesToBreak = []; - var locStart = options.locStart, - locEnd = options.locEnd; - comments.forEach(function (comment, i) { - if ((options.parser === "json" || options.parser === "json5") && locStart(comment) - locStart(ast) <= 0) { - addLeadingComment(ast, comment); - return; - } - - decorateComment(ast, comment, options); - var precedingNode = comment.precedingNode, - enclosingNode = comment.enclosingNode, - followingNode = comment.followingNode; - var pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : function () { - return false; - }; - var pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : function () { - return false; - }; - var pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : function () { - return false; - }; - var isLastComment = comments.length - 1 === i; - - if (hasNewline(text, locStart(comment), { - backwards: true - })) { - // If a comment exists on its own line, prefer a leading comment. - // We also need to check if it's the first line of the file. - if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) {// We're good - } else if (followingNode) { - // Always a leading comment. - addLeadingComment(followingNode, comment); - } else if (precedingNode) { - addTrailingComment(precedingNode, comment); - } else if (enclosingNode) { - addDanglingComment(enclosingNode, comment); - } else { - // There are no nodes, let's attach it to the root of the ast - - /* istanbul ignore next */ - addDanglingComment(ast, comment); - } - } else if (hasNewline(text, locEnd(comment))) { - if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) {// We're good - } else if (precedingNode) { - // There is content before this comment on the same line, but - // none after it, so prefer a trailing comment of the previous node. - addTrailingComment(precedingNode, comment); - } else if (followingNode) { - addLeadingComment(followingNode, comment); - } else if (enclosingNode) { - addDanglingComment(enclosingNode, comment); - } else { - // There are no nodes, let's attach it to the root of the ast - - /* istanbul ignore next */ - addDanglingComment(ast, comment); - } - } else { - if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) {// We're good - } else if (precedingNode && followingNode) { - // Otherwise, text exists both before and after the comment on - // the same line. If there is both a preceding and following - // node, use a tie-breaking algorithm to determine if it should - // be attached to the next or previous node. In the last case, - // simply attach the right node; - var tieCount = tiesToBreak.length; - - if (tieCount > 0) { - var lastTie = tiesToBreak[tieCount - 1]; - - if (lastTie.followingNode !== comment.followingNode) { - breakTies(tiesToBreak, text, options); - } - } - - tiesToBreak.push(comment); - } else if (precedingNode) { - addTrailingComment(precedingNode, comment); - } else if (followingNode) { - addLeadingComment(followingNode, comment); - } else if (enclosingNode) { - addDanglingComment(enclosingNode, comment); - } else { - // There are no nodes, let's attach it to the root of the ast - - /* istanbul ignore next */ - addDanglingComment(ast, comment); - } - } - }); - breakTies(tiesToBreak, text, options); - comments.forEach(function (comment) { - // These node references were useful for breaking ties, but we - // don't need them anymore, and they create cycles in the AST that - // may lead to infinite recursion if we don't delete them here. - delete comment.precedingNode; - delete comment.enclosingNode; - delete comment.followingNode; - }); -} - -function breakTies(tiesToBreak, text, options) { - var tieCount = tiesToBreak.length; - - if (tieCount === 0) { - return; - } - - var _tiesToBreak$ = tiesToBreak[0], - precedingNode = _tiesToBreak$.precedingNode, - followingNode = _tiesToBreak$.followingNode; - var gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps - // between the tied comments. In order to qualify as leading, a - // comment must be separated from followingNode by an unbroken series of - // gaps (or other comments). Gaps should only contain whitespace or open - // parentheses. - - var indexOfFirstLeadingComment; - - for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) { - var comment = tiesToBreak[indexOfFirstLeadingComment - 1]; - assert$3.strictEqual(comment.precedingNode, precedingNode); - assert$3.strictEqual(comment.followingNode, followingNode); - var gap = text.slice(options.locEnd(comment), gapEndPos).trim(); - - if (gap === "" || /^\(+$/.test(gap)) { - gapEndPos = options.locStart(comment); - } else { - // The gap string contained something other than whitespace or open - // parentheses. - break; - } - } - - tiesToBreak.forEach(function (comment, i) { - if (i < indexOfFirstLeadingComment) { - addTrailingComment(precedingNode, comment); - } else { - addLeadingComment(followingNode, comment); - } - }); - tiesToBreak.length = 0; -} - -function printComment(commentPath, options) { - var comment = commentPath.getValue(); - comment.printed = true; - return options.printer.printComment(commentPath, options); -} - -function findExpressionIndexForComment(quasis, comment, options) { - var startPos = options.locStart(comment) - 1; - - for (var i = 1; i < quasis.length; ++i) { - if (startPos < getQuasiRange(quasis[i]).start) { - return i - 1; - } - } // We haven't found it, it probably means that some of the locations are off. - // Let's just return the first one. - - /* istanbul ignore next */ - - - return 0; -} - -function getQuasiRange(expr) { - if (expr.start !== undefined) { - // Babylon - return { - start: expr.start, - end: expr.end - }; - } // Flow - - - return { - start: expr.range[0], - end: expr.range[1] - }; -} - -function printLeadingComment(commentPath, print, options) { - var comment = commentPath.getValue(); - var contents = printComment(commentPath, options); - - if (!contents) { - return ""; - } - - var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the - // same line or not. - - if (isBlock) { - return concat([contents, hasNewline(options.originalText, options.locEnd(comment)) ? hardline : " "]); - } - - return concat([contents, hardline]); -} - -function printTrailingComment(commentPath, print, options) { - var comment = commentPath.getValue(); - var contents = printComment(commentPath, options); - - if (!contents) { - return ""; - } - - var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break - // when the parentParentNode is a ClassDeclaration/-Expression - // And the parentNode is in the superClass property - - var parentNode = commentPath.getNode(1); - var parentParentNode = commentPath.getNode(2); - var isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode; - - if (hasNewline(options.originalText, options.locStart(comment), { - backwards: true - })) { - // This allows comments at the end of nested structures: - // { - // x: 1, - // y: 2 - // // A comment - // } - // Those kinds of comments are almost always leading comments, but - // here it doesn't go "outside" the block and turns it into a - // trailing comment for `2`. We can simulate the above by checking - // if this a comment on its own line; normal trailing comments are - // always at the end of another expression. - var isLineBeforeEmpty = isPreviousLineEmpty(options.originalText, comment, options.locStart); - return lineSuffix(concat([hardline, isLineBeforeEmpty ? hardline : "", contents])); - } else if (isBlock || isParentSuperClass) { - // Trailing block comments never need a newline - return concat([" ", contents]); - } - - return concat([lineSuffix(" " + contents), !isBlock ? breakParent : ""]); -} - -function printDanglingComments(path, options, sameIndent, filter) { - var parts = []; - var node = path.getValue(); - - if (!node || !node.comments) { - return ""; - } - - path.each(function (commentPath) { - var comment = commentPath.getValue(); - - if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) { - parts.push(printComment(commentPath, options)); - } - }, "comments"); - - if (parts.length === 0) { - return ""; - } - - if (sameIndent) { - return join(hardline, parts); - } - - return indent(concat([hardline, join(hardline, parts)])); -} - -function prependCursorPlaceholder(path, options, printed) { - if (path.getNode() === options.cursorNode && path.getValue()) { - return concat([cursor, printed, cursor]); - } - - return printed; -} - -function printComments(path, print, options, needsSemi) { - var value = path.getValue(); - var printed = print(path); - var comments = value && value.comments; - - if (!comments || comments.length === 0) { - return prependCursorPlaceholder(path, options, printed); - } - - var leadingParts = []; - var trailingParts = [needsSemi ? ";" : "", printed]; - path.each(function (commentPath) { - var comment = commentPath.getValue(); - var leading = comment.leading, - trailing = comment.trailing; - - if (leading) { - var contents = printLeadingComment(commentPath, print, options); - - if (!contents) { - return; - } - - leadingParts.push(contents); - var text = options.originalText; - - if (hasNewline(text, skipNewline(text, options.locEnd(comment)))) { - leadingParts.push(hardline); - } - } else if (trailing) { - trailingParts.push(printTrailingComment(commentPath, print, options)); - } - }, "comments"); - return prependCursorPlaceholder(path, options, concat(leadingParts.concat(trailingParts))); -} - -var comments = { - attach: attach, - printComments: printComments, - printDanglingComments: printDanglingComments, - getSortedChildNodes: getSortedChildNodes -}; - -function FastPath(value) { - assert$3.ok(this instanceof FastPath); - this.stack = [value]; -} // The name of the current property is always the penultimate element of -// this.stack, and always a String. - - -FastPath.prototype.getName = function getName() { - var s = this.stack; - var len = s.length; - - if (len > 1) { - return s[len - 2]; - } // Since the name is always a string, null is a safe sentinel value to - // return if we do not know the name of the (root) value. - - /* istanbul ignore next */ - - - return null; -}; // The value of the current property is always the final element of -// this.stack. - - -FastPath.prototype.getValue = function getValue() { - var s = this.stack; - return s[s.length - 1]; -}; - -function getNodeHelper(path, count) { - var s = path.stack; - - for (var i = s.length - 1; i >= 0; i -= 2) { - var value = s[i]; - - if (value && !Array.isArray(value) && --count < 0) { - return value; - } - } - - return null; -} - -FastPath.prototype.getNode = function getNode(count) { - return getNodeHelper(this, ~~count); -}; - -FastPath.prototype.getParentNode = function getParentNode(count) { - return getNodeHelper(this, ~~count + 1); -}; // Temporarily push properties named by string arguments given after the -// callback function onto this.stack, then call the callback with a -// reference to this (modified) FastPath object. Note that the stack will -// be restored to its original state after the callback is finished, so it -// is probably a mistake to retain a reference to the path. - - -FastPath.prototype.call = function call(callback -/*, name1, name2, ... */ -) { - var s = this.stack; - var origLen = s.length; - var value = s[origLen - 1]; - var argc = arguments.length; - - for (var i = 1; i < argc; ++i) { - var name = arguments[i]; - value = value[name]; - s.push(name, value); - } - - var result = callback(this); - s.length = origLen; - return result; -}; // Similar to FastPath.prototype.call, except that the value obtained by -// accessing this.getValue()[name1][name2]... should be array-like. The -// callback will be called with a reference to this path object for each -// element of the array. - - -FastPath.prototype.each = function each(callback -/*, name1, name2, ... */ -) { - var s = this.stack; - var origLen = s.length; - var value = s[origLen - 1]; - var argc = arguments.length; - - for (var i = 1; i < argc; ++i) { - var name = arguments[i]; - value = value[name]; - s.push(name, value); - } - - for (var _i = 0; _i < value.length; ++_i) { - if (_i in value) { - s.push(_i, value[_i]); // If the callback needs to know the value of i, call - // path.getName(), assuming path is the parameter name. - - callback(this); - s.length -= 2; - } - } - - s.length = origLen; -}; // Similar to FastPath.prototype.each, except that the results of the -// callback function invocations are stored in an array and returned at -// the end of the iteration. - - -FastPath.prototype.map = function map(callback -/*, name1, name2, ... */ -) { - var s = this.stack; - var origLen = s.length; - var value = s[origLen - 1]; - var argc = arguments.length; - - for (var i = 1; i < argc; ++i) { - var name = arguments[i]; - value = value[name]; - s.push(name, value); - } - - var result = new Array(value.length); - - for (var _i2 = 0; _i2 < value.length; ++_i2) { - if (_i2 in value) { - s.push(_i2, value[_i2]); - result[_i2] = callback(this, _i2); - s.length -= 2; - } - } - - s.length = origLen; - return result; -}; - -var fastPath = FastPath; - -var normalize$1 = options.normalize; - -function printSubtree(path, print, options$$1, printAstToDoc) { - if (options$$1.printer.embed) { - return options$$1.printer.embed(path, print, function (text, partialNextOptions) { - return textToDoc(text, partialNextOptions, options$$1, printAstToDoc); - }, options$$1); - } -} - -function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) { - var nextOptions = normalize$1(Object.assign({}, parentOptions, partialNextOptions, { - parentParser: parentOptions.parser, - originalText: text - }), { - passThrough: true - }); - var result = parser.parse(text, nextOptions); - var ast = result.ast; - text = result.text; - var astComments = ast.comments; - delete ast.comments; - comments.attach(astComments, ast, text, nextOptions); - return printAstToDoc(ast, nextOptions); -} - -var multiparser = { - printSubtree: printSubtree -}; - -var doc$2 = doc; -var docBuilders$2 = doc$2.builders; -var concat$3 = docBuilders$2.concat; -var hardline$2 = docBuilders$2.hardline; -var addAlignmentToDoc$1 = docBuilders$2.addAlignmentToDoc; -var docUtils$2 = doc$2.utils; - -function printAstToDoc(ast, options, addAlignmentSize) { - addAlignmentSize = addAlignmentSize || 0; - var printer = options.printer; - var cache = new Map(); - - function printGenerically(path, args) { - var node = path.getValue(); - var shouldCache = node && _typeof(node) === "object" && args === undefined; - - if (shouldCache && cache.has(node)) { - return cache.get(node); - } // We let JSXElement print its comments itself because it adds () around - // UnionTypeAnnotation has to align the child without the comments - - - var res; - - if (printer.willPrintOwnComments && printer.willPrintOwnComments(path)) { - res = genericPrint(path, options, printGenerically, args); - } else { - res = comments.printComments(path, function (p) { - return genericPrint(p, options, printGenerically, args); - }, options, args && args.needsSemi); - } - - if (shouldCache) { - cache.set(node, res); - } - - return res; - } - - var doc$$2 = printGenerically(new fastPath(ast)); - - if (addAlignmentSize > 0) { - // Add a hardline to make the indents take effect - // It should be removed in index.js format() - doc$$2 = addAlignmentToDoc$1(docUtils$2.removeLines(concat$3([hardline$2, doc$$2])), addAlignmentSize, options.tabWidth); - } - - docUtils$2.propagateBreaks(doc$$2); - - if (options.parser === "json" || options.parser === "json5" || options.parser === "json-stringify") { - doc$$2 = concat$3([doc$$2, hardline$2]); - } - - return doc$$2; -} - -function genericPrint(path, options, printPath, args) { - assert$3.ok(path instanceof fastPath); - var node = path.getValue(); - var printer = options.printer; // Escape hatch - - if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) { - return options.originalText.slice(options.locStart(node), options.locEnd(node)); - } - - if (node) { - try { - // Potentially switch to a different parser - var sub = multiparser.printSubtree(path, printPath, options, printAstToDoc); - - if (sub) { - return sub; - } - } catch (error) { - /* istanbul ignore if */ - if (commonjsGlobal.PRETTIER_DEBUG) { - throw error; - } // Continue with current parser - - } - } - - return printer.print(path, options, printPath, args); -} - -var astToDoc = printAstToDoc; - -function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { - var resultStartNode = startNodeAndParents.node; - var resultEndNode = endNodeAndParents.node; - - if (resultStartNode === resultEndNode) { - return { - startNode: resultStartNode, - endNode: resultEndNode - }; - } - - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = endNodeAndParents.parentNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var endParent = _step.value; - - if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) { - resultEndNode = endParent; - } else { - break; - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = startNodeAndParents.parentNodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var startParent = _step2.value; - - if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) { - resultStartNode = startParent; - } else { - break; - } - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return != null) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - - return { - startNode: resultStartNode, - endNode: resultEndNode - }; -} - -function findNodeAtOffset(node, offset, options, predicate, parentNodes) { - predicate = predicate || function () { - return true; - }; - - parentNodes = parentNodes || []; - var start = options.locStart(node, options.locStart); - var end = options.locEnd(node, options.locEnd); - - if (start <= offset && offset <= end) { - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - - try { - for (var _iterator3 = comments.getSortedChildNodes(node, options)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var childNode = _step3.value; - var childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes)); - - if (childResult) { - return childResult; - } - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return != null) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - - if (predicate(node)) { - return { - node: node, - parentNodes: parentNodes - }; - } - } -} // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 - - -function isSourceElement(opts, node) { - if (node == null) { - return false; - } // JS and JS like to avoid repetitions - - - var jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015 - "ImportDeclaration", // Module - "ExportDefaultDeclaration", // Module - "ExportNamedDeclaration", // Module - "ExportAllDeclaration", // Module - "TypeAlias", // Flow - "InterfaceDeclaration", // Flow, TypeScript - "TypeAliasDeclaration", // TypeScript - "ExportAssignment", // TypeScript - "ExportDeclaration" // TypeScript - ]; - var jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"]; - var graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"]; - - switch (opts.parser) { - case "flow": - case "babylon": - case "typescript": - return jsSourceElements.indexOf(node.type) > -1; - - case "json": - return jsonSourceElements.indexOf(node.type) > -1; - - case "graphql": - return graphqlSourceElements.indexOf(node.kind) > -1; - - case "vue": - return node.tag !== "root"; - } - - return false; -} - -function calculateRange(text, opts, ast) { - // Contract the range so that it has non-whitespace characters at its endpoints. - // This ensures we can format a range that doesn't end on a node. - var rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); - var startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart); - var endNonWhitespace; - - for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) { - if (text[endNonWhitespace - 1].match(/\S/)) { - break; - } - } - - var startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, function (node) { - return isSourceElement(opts, node); - }); - var endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, function (node) { - return isSourceElement(opts, node); - }); - - if (!startNodeAndParents || !endNodeAndParents) { - return { - rangeStart: 0, - rangeEnd: 0 - }; - } - - var siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts); - var startNode = siblingAncestors.startNode, - endNode = siblingAncestors.endNode; - var rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart)); - var rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd)); - return { - rangeStart: rangeStart, - rangeEnd: rangeEnd - }; -} - -var rangeUtil = { - calculateRange: calculateRange, - findNodeAtOffset: findNodeAtOffset -}; - -var normalizeOptions = options.normalize; -var _printDocToString = doc.printer.printDocToString; -var printDocToDebug = doc.debug.printDocToDebug; -var UTF8BOM = 0xfeff; -var CURSOR = Symbol("cursor"); - -function guessLineEnding(text) { - var index = text.indexOf("\n"); - - if (index >= 0 && text.charAt(index - 1) === "\r") { - return "\r\n"; - } - - return "\n"; -} - -function ensureAllCommentsPrinted(astComments) { - if (!astComments) { - return; - } - - for (var i = 0; i < astComments.length; ++i) { - if (astComments[i].value.trim() === "prettier-ignore") { - // If there's a prettier-ignore, we're not printing that sub-tree so we - // don't know if the comments was printed or not. - return; - } - } - - astComments.forEach(function (comment) { - if (!comment.printed) { - throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!'); - } - - delete comment.printed; - }); -} - -function attachComments(text, ast, opts) { - var astComments = ast.comments; - - if (astComments) { - delete ast.comments; - comments.attach(astComments, ast, text, opts); - } - - ast.tokens = []; - opts.originalText = opts.parser === "yaml" ? text : text.trimRight(); - return astComments; -} - -function coreFormat(text, opts, addAlignmentSize) { - if (!text || !text.trim().length) { - return { - formatted: "", - cursorOffset: 0 - }; - } - - addAlignmentSize = addAlignmentSize || 0; - var parsed = parser.parse(text, opts); - var ast = parsed.ast; - text = parsed.text; - - if (opts.cursorOffset >= 0) { - var nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts); - - if (nodeResult && nodeResult.node) { - opts.cursorNode = nodeResult.node; - } - } - - var astComments = attachComments(text, ast, opts); - var doc$$1 = astToDoc(ast, opts, addAlignmentSize); - opts.newLine = guessLineEnding(text); - - var result = _printDocToString(doc$$1, opts); - - ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline - - if (addAlignmentSize > 0) { - var trimmed = result.formatted.trim(); - - if (result.cursorNodeStart !== undefined) { - result.cursorNodeStart -= result.formatted.indexOf(trimmed); - } - - result.formatted = trimmed + opts.newLine; - } - - if (opts.cursorOffset >= 0) { - var oldCursorNodeStart; - var oldCursorNodeText; - var cursorOffsetRelativeToOldCursorNode; - var newCursorNodeStart; - var newCursorNodeText; - - if (opts.cursorNode && result.cursorNodeText) { - oldCursorNodeStart = opts.locStart(opts.cursorNode); - oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode)); - cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart; - newCursorNodeStart = result.cursorNodeStart; - newCursorNodeText = result.cursorNodeText; - } else { - oldCursorNodeStart = 0; - oldCursorNodeText = text; - cursorOffsetRelativeToOldCursorNode = opts.cursorOffset; - newCursorNodeStart = 0; - newCursorNodeText = result.formatted; - } - - if (oldCursorNodeText === newCursorNodeText) { - return { - formatted: result.formatted, - cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode - }; - } // diff old and new cursor node texts, with a special cursor - // symbol inserted to find out where it moves to - - - var oldCursorNodeCharArray = oldCursorNodeText.split(""); - oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR); - var newCursorNodeCharArray = newCursorNodeText.split(""); - var cursorNodeDiff = lib.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray); - var cursorOffset = newCursorNodeStart; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = cursorNodeDiff[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var entry = _step.value; - - if (entry.removed) { - if (entry.value.indexOf(CURSOR) > -1) { - break; - } - } else { - cursorOffset += entry.count; - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - return { - formatted: result.formatted, - cursorOffset: cursorOffset - }; - } - - return { - formatted: result.formatted - }; -} - -function formatRange(text, opts) { - var parsed = parser.parse(text, opts); - var ast = parsed.ast; - text = parsed.text; - var range = rangeUtil.calculateRange(text, opts, ast); - var rangeStart = range.rangeStart; - var rangeEnd = range.rangeEnd; - var rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. - // This is so we can detect indentation correctly and restore it. - // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 - - var rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1); - var indentString = text.slice(rangeStart2, rangeStart); - var alignmentSize = util.getAlignmentSize(indentString, opts.tabWidth); - var rangeResult = coreFormat(rangeString, Object.assign({}, opts, { - rangeStart: 0, - rangeEnd: Infinity, - printWidth: opts.printWidth - alignmentSize, - // track the cursor offset only if it's within our range - cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1 - }), alignmentSize); // Since the range contracts to avoid trailing whitespace, - // we need to remove the newline that was inserted by the `format` call. - - var rangeTrimmed = rangeResult.formatted.trimRight(); - var formatted = text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd); - var cursorOffset = opts.cursorOffset; - - if (opts.cursorOffset >= rangeEnd) { - // handle the case where the cursor was past the end of the range - cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length); - } else if (rangeResult.cursorOffset !== undefined) { - // handle the case where the cursor was in the range - cursorOffset = rangeResult.cursorOffset + rangeStart; - } // keep the cursor as it was if it was before the start of the range - - - return { - formatted: formatted, - cursorOffset: cursorOffset - }; -} - -function format(text, opts) { - var selectedParser = parser.resolveParser(opts); - var hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text); - - if (opts.requirePragma && !hasPragma) { - return { - formatted: text - }; - } - - if (opts.rangeStart > 0 || opts.rangeEnd < text.length) { - return formatRange(text, opts); - } - - var hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM; - - if (hasUnicodeBOM) { - text = text.substring(1); - } - - if (opts.insertPragma && opts.printer.insertPragma && !hasPragma) { - text = opts.printer.insertPragma(text); - } - - var result = coreFormat(text, opts); - - if (hasUnicodeBOM) { - result.formatted = String.fromCharCode(UTF8BOM) + result.formatted; - } - - return result; -} - -var core = { - formatWithCursor: function formatWithCursor(text, opts) { - opts = normalizeOptions(opts); - return format(text, opts); - }, - parse: function parse(text, opts, massage) { - opts = normalizeOptions(opts); - var parsed = parser.parse(text, opts); - - if (massage) { - parsed.ast = massageAst(parsed.ast, opts); - } - - return parsed; - }, - formatAST: function formatAST(ast, opts) { - opts = normalizeOptions(opts); - var doc$$1 = astToDoc(ast, opts); - return _printDocToString(doc$$1, opts); - }, - // Doesn't handle shebang for now - formatDoc: function formatDoc(doc$$1, opts) { - var debug = printDocToDebug(doc$$1); - opts = normalizeOptions(Object.assign({}, opts, { - parser: "babylon" - })); - return format(debug, opts).formatted; - }, - printToDoc: function printToDoc(text, opts) { - opts = normalizeOptions(opts); - var parsed = parser.parse(text, opts); - var ast = parsed.ast; - text = parsed.text; - attachComments(text, ast, opts); - return astToDoc(ast, opts); - }, - printDocToString: function printDocToString(doc$$1, opts) { - return _printDocToString(doc$$1, normalizeOptions(opts)); - } -}; - -var _require$$0$builders$1 = doc.builders; -var indent$3 = _require$$0$builders$1.indent; -var join$3 = _require$$0$builders$1.join; -var hardline$4 = _require$$0$builders$1.hardline; -var softline$2 = _require$$0$builders$1.softline; -var literalline$2 = _require$$0$builders$1.literalline; -var concat$5 = _require$$0$builders$1.concat; -var dedentToRoot$1 = _require$$0$builders$1.dedentToRoot; -var _require$$0$utils = doc.utils; -var mapDoc$2 = _require$$0$utils.mapDoc; -var stripTrailingHardline$1 = _require$$0$utils.stripTrailingHardline; - -function embed(path, print, textToDoc -/*, options */ -) { - var node = path.getValue(); - var parent = path.getParentNode(); - var parentParent = path.getParentNode(1); - - switch (node.type) { - case "TemplateLiteral": - { - var isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(function (isIt) { - return isIt(path); - }); - - if (isCss) { - // Get full template literal with expressions replaced by placeholders - var rawQuasis = node.quasis.map(function (q) { - return q.value.raw; - }); - var placeholderID = 0; - var text = rawQuasis.reduce(function (prevVal, currVal, idx) { - return idx == 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal; - }, ""); - var doc$$2 = textToDoc(text, { - parser: "css" - }); - return transformCssDoc(doc$$2, path, print); - } - /* - * react-relay and graphql-tag - * graphql`...` - * graphql.experimental`...` - * gql`...` - * - * This intentionally excludes Relay Classic tags, as Prettier does not - * support Relay Classic formatting. - */ - - - if (isGraphQL(path)) { - var expressionDocs = node.expressions ? path.map(print, "expressions") : []; - var numQuasis = node.quasis.length; - - if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") { - return "``"; - } - - var parts = []; - - for (var i = 0; i < numQuasis; i++) { - var templateElement = node.quasis[i]; - var isFirst = i === 0; - var isLast = i === numQuasis - 1; - var _text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence - // (which would make the `cooked` value be `null` or `undefined`) - - if (typeof _text !== "string") { - return null; - } - - var lines = _text.split("\n"); - - var numLines = lines.length; - var expressionDoc = expressionDocs[i]; - var startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === ""; - var endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === ""; - var commentsAndWhitespaceOnly = lines.every(function (line) { - return /^\s*(?:#[^\r\n]*)?$/.test(line); - }); // Bail out if an interpolation occurs within a comment. - - if (!isLast && /#[^\r\n]*$/.test(lines[numLines - 1])) { - return null; - } - - var _doc = null; - - if (commentsAndWhitespaceOnly) { - _doc = printGraphqlComments(lines); - } else { - _doc = stripTrailingHardline$1(textToDoc(_text, { - parser: "graphql" - })); - } - - if (_doc) { - _doc = escapeBackticks(_doc); - - if (!isFirst && startsWithBlankLine) { - parts.push(""); - } - - parts.push(_doc); - - if (!isLast && endsWithBlankLine) { - parts.push(""); - } - } else if (!isFirst && !isLast && startsWithBlankLine) { - parts.push(""); - } - - if (expressionDoc) { - parts.push(concat$5(["${", expressionDoc, "}"])); - } - } - - return concat$5(["`", indent$3(concat$5([hardline$4, join$3(hardline$4, parts)])), hardline$4, "`"]); - } - - break; - } - - case "TemplateElement": - { - /** - * md`...` - * markdown`...` - */ - if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) { - var _text2 = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, function (_, backslashes) { - return "\\".repeat(backslashes.length / 2) + "`"; - }); - - var indentation = getIndentation(_text2); - var hasIndent = indentation !== ""; - return concat$5([hasIndent ? indent$3(concat$5([softline$2, printMarkdown(_text2.replace(new RegExp("^".concat(indentation), "gm"), ""))])) : concat$5([literalline$2, dedentToRoot$1(printMarkdown(_text2))]), softline$2]); - } - - break; - } - } - - function printMarkdown(text) { - var doc$$2 = textToDoc(text, { - parser: "markdown", - __inJsTemplate: true - }); - return stripTrailingHardline$1(escapeBackticks(doc$$2)); - } -} - -function isPropertyWithinAngularComponentDecorator(path, parentIndexToCheck) { - var parent = path.getParentNode(parentIndexToCheck); - return !!(parent && parent.type === "Decorator" && parent.expression && parent.expression.type === "CallExpression" && parent.expression.callee && parent.expression.callee.name === "Component"); -} - -function getIndentation(str) { - var firstMatchedIndent = str.match(/^([^\S\n]*)\S/m); - return firstMatchedIndent === null ? "" : firstMatchedIndent[1]; -} - -function escapeBackticks(doc$$2) { - return mapDoc$2(doc$$2, function (currentDoc) { - if (!currentDoc.parts) { - return currentDoc; - } - - var parts = []; - currentDoc.parts.forEach(function (part) { - if (typeof part === "string") { - parts.push(part.replace(/(\\*)`/g, "$1$1\\`")); - } else { - parts.push(part); - } - }); - return Object.assign({}, currentDoc, { - parts: parts - }); - }); -} - -function transformCssDoc(quasisDoc, path, print) { - var parentNode = path.getValue(); - var isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim(); - - if (isEmpty) { - return "``"; - } - - var expressionDocs = parentNode.expressions ? path.map(print, "expressions") : []; - var newDoc = replacePlaceholders(quasisDoc, expressionDocs); - /* istanbul ignore if */ - - if (!newDoc) { - throw new Error("Couldn't insert all the expressions"); - } - - return concat$5(["`", indent$3(concat$5([hardline$4, stripTrailingHardline$1(newDoc)])), softline$2, "`"]); -} // Search all the placeholders in the quasisDoc tree -// and replace them with the expression docs one by one -// returns a new doc with all the placeholders replaced, -// or null if it couldn't replace any expression - - -function replacePlaceholders(quasisDoc, expressionDocs) { - if (!expressionDocs || !expressionDocs.length) { - return quasisDoc; - } - - var expressions = expressionDocs.slice(); - var replaceCounter = 0; - var newDoc = mapDoc$2(quasisDoc, function (doc$$2) { - if (!doc$$2 || !doc$$2.parts || !doc$$2.parts.length) { - return doc$$2; - } - - var parts = doc$$2.parts; - var atIndex = parts.indexOf("@"); - var placeholderIndex = atIndex + 1; - - if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) { - // If placeholder is split, join it - var at = parts[atIndex]; - var placeholder = parts[placeholderIndex]; - var rest = parts.slice(placeholderIndex + 1); - parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest); - } - - var atPlaceholderIndex = parts.findIndex(function (part) { - return typeof part === "string" && part.startsWith("@prettier-placeholder"); - }); - - if (atPlaceholderIndex > -1) { - var _placeholder = parts[atPlaceholderIndex]; - - var _rest = parts.slice(atPlaceholderIndex + 1); - - var placeholderMatch = _placeholder.match(/@prettier-placeholder-(.+)-id([\s\S]*)/); - - var placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like: - // animation: linear ${time}s ease-out; - - var suffix = placeholderMatch[2]; - var expression = expressions[placeholderID]; - replaceCounter++; - parts = parts.slice(0, atPlaceholderIndex).concat(["${", expression, "}" + suffix]).concat(_rest); - } - - return Object.assign({}, doc$$2, { - parts: parts - }); - }); - return expressions.length === replaceCounter ? newDoc : null; -} - -function printGraphqlComments(lines) { - var parts = []; - var seenComment = false; - lines.map(function (textLine) { - return textLine.trim(); - }).forEach(function (textLine, i, array) { - // Lines are either whitespace only, or a comment (with poential whitespace - // around it). Drop whitespace-only lines. - if (textLine === "") { - return; - } - - if (array[i - 1] === "" && seenComment) { - // If a non-first comment is preceded by a blank (whitespace only) line, - // add in a blank line. - parts.push(concat$5([hardline$4, textLine])); - } else { - parts.push(textLine); - } - - seenComment = true; - }); // If `lines` was whitespace only, return `null`. - - return parts.length === 0 ? null : join$3(hardline$4, parts); -} -/** - * Template literal in this context: - * <style jsx>{`div{color:red}`}</style> - */ - - -function isStyledJsx(path) { - var node = path.getValue(); - var parent = path.getParentNode(); - var parentParent = path.getParentNode(1); - return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(function (attribute) { - return attribute.name.name === "jsx"; - }); -} -/** - * Angular Components can have: - * - Inline HTML template - * - Inline CSS styles - * - * ...which are both within template literals somewhere - * inside of the Component decorator factory. - * - * TODO: Format HTML template once prettier's HTML - * formatting is "ready" - * - * E.g. - * @Component({ - * template: `<div>...</div>`, - * styles: [`h1 { color: blue; }`] - * }) - */ - - -function isAngularComponentStyles(path) { - var parent = path.getParentNode(); - var parentParent = path.getParentNode(1); - var isWithinArrayValueFromProperty = !!(parent && parent.type === "ArrayExpression" && parentParent.type === "Property"); - - if (isWithinArrayValueFromProperty && isPropertyWithinAngularComponentDecorator(path, 4)) { - if (parentParent.key && parentParent.key.name === "styles") { - return true; - } - } - - return false; -} -/** - * styled-components template literals - */ - - -function isStyledComponents(path) { - var parent = path.getParentNode(); - - if (!parent || parent.type !== "TaggedTemplateExpression") { - return false; - } - - var tag = parent.tag; - - switch (tag.type) { - case "MemberExpression": - return (// styled.foo`` - isStyledIdentifier(tag.object) || // Component.extend`` - isStyledExtend(tag) - ); - - case "CallExpression": - return (// styled(Component)`` - isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attr({})`` - isStyledIdentifier(tag.callee.object.object) || // Component.extend.attr({)`` - isStyledExtend(tag.callee.object)) || // styled(Component).attr({})`` - tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee)) - ); - - case "Identifier": - // css`` - return tag.name === "css"; - - default: - return false; - } -} -/** - * JSX element with CSS prop - */ - - -function isCssProp(path) { - var parent = path.getParentNode(); - var parentParent = path.getParentNode(1); - return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css"; -} - -function isStyledIdentifier(node) { - return node.type === "Identifier" && node.name === "styled"; -} - -function isStyledExtend(node) { - return /^[A-Z]/.test(node.object.name) && node.property.name === "extend"; -} -/* - * react-relay and graphql-tag - * graphql`...` - * graphql.experimental`...` - * gql`...` - * GraphQL comment block - * - * This intentionally excludes Relay Classic tags, as Prettier does not - * support Relay Classic formatting. - */ - - -function isGraphQL(path) { - var node = path.getValue(); - var parent = path.getParentNode(); // This checks for a leading comment that is exactly `/* GraphQL */` - // In order to be in line with other implementations of this comment tag - // we will not trim the comment value and we will expect exactly one space on - // either side of the GraphQL string - // Also see ./clean.js - - var hasGraphQLComment = node.leadingComments && node.leadingComments.some(function (comment) { - return comment.type === "CommentBlock" && comment.value === " GraphQL "; - }); - return hasGraphQLComment || parent && (parent.type === "TaggedTemplateExpression" && (parent.tag.type === "MemberExpression" && parent.tag.object.name === "graphql" && parent.tag.property.name === "experimental" || parent.tag.type === "Identifier" && (parent.tag.name === "gql" || parent.tag.name === "graphql")) || parent.type === "CallExpression" && parent.callee.type === "Identifier" && parent.callee.name === "graphql"); -} - -var embed_1 = embed; - -function clean(ast, newObj, parent) { - ["range", "raw", "comments", "leadingComments", "trailingComments", "extra", "start", "end", "flags"].forEach(function (name) { - delete newObj[name]; - }); - - if (ast.type === "BigIntLiteral") { - newObj.value = newObj.value.toLowerCase(); - } // We remove extra `;` and add them when needed - - - if (ast.type === "EmptyStatement") { - return null; - } // We move text around, including whitespaces and add {" "} - - - if (ast.type === "JSXText") { - return null; - } - - if (ast.type === "JSXExpressionContainer" && ast.expression.type === "Literal" && ast.expression.value === " ") { - return null; - } // (TypeScript) Ignore `static` in `constructor(static p) {}` - // and `export` in `constructor(export p) {}` - - - if (ast.type === "TSParameterProperty" && ast.accessibility === null && !ast.readonly) { - return { - type: "Identifier", - name: ast.parameter.name, - typeAnnotation: newObj.parameter.typeAnnotation, - decorators: newObj.decorators - }; - } // (TypeScript) ignore empty `specifiers` array - - - if (ast.type === "TSNamespaceExportDeclaration" && ast.specifiers && ast.specifiers.length === 0) { - delete newObj.specifiers; - } // (TypeScript) bypass TSParenthesizedType - - - if (ast.type === "TSParenthesizedType" && ast.typeAnnotation.type === "TSTypeAnnotation") { - return newObj.typeAnnotation.typeAnnotation; - } // We convert <div></div> to <div /> - - - if (ast.type === "JSXOpeningElement") { - delete newObj.selfClosing; - } - - if (ast.type === "JSXElement") { - delete newObj.closingElement; - } // We change {'key': value} into {key: value} - - - if ((ast.type === "Property" || ast.type === "ObjectProperty" || ast.type === "MethodDefinition" || ast.type === "ClassProperty" || ast.type === "TSPropertySignature" || ast.type === "ObjectTypeProperty") && _typeof(ast.key) === "object" && ast.key && (ast.key.type === "Literal" || ast.key.type === "StringLiteral" || ast.key.type === "Identifier")) { - delete newObj.key; - } - - if (ast.type === "OptionalMemberExpression" && ast.optional === false) { - newObj.type = "MemberExpression"; - delete newObj.optional; - } // Remove raw and cooked values from TemplateElement when it's CSS - // styled-jsx - - - if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(function (attr) { - return attr.name.name === "jsx"; - })) { - var templateLiterals = newObj.children.filter(function (child) { - return child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral"; - }).map(function (container) { - return container.expression; - }); - var quasis = templateLiterals.reduce(function (quasis, templateLiteral) { - return quasis.concat(templateLiteral.quasis); - }, []); - quasis.forEach(function (q) { - return delete q.value; - }); - } // CSS template literals in css prop - - - if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") { - newObj.value.expression.quasis.forEach(function (q) { - return delete q.value; - }); - } // CSS template literals in Angular Component decorator - - - var expression = ast.expression || ast.callee; - - if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1 && expression.arguments[0].properties.some(function (prop) { - return prop.key.name === "styles" && prop.value.type === "ArrayExpression"; - })) { - newObj.expression.arguments[0].properties.forEach(function (prop) { - if (prop.value.type === "ArrayExpression") { - prop.value.elements[0].quasis.forEach(function (q) { - return delete q.value; - }); - } - }); - } // styled-components, graphql, markdown - - - if (ast.type === "TaggedTemplateExpression" && (ast.tag.type === "MemberExpression" || ast.tag.type === "Identifier" && (ast.tag.name === "gql" || ast.tag.name === "graphql" || ast.tag.name === "css" || ast.tag.name === "md" || ast.tag.name === "markdown") || ast.tag.type === "CallExpression")) { - newObj.quasi.quasis.forEach(function (quasi) { - return delete quasi.value; - }); - } - - if (ast.type === "TemplateLiteral") { - // This checks for a leading comment that is exactly `/* GraphQL */` - // In order to be in line with other implementations of this comment tag - // we will not trim the comment value and we will expect exactly one space on - // either side of the GraphQL string - // Also see ./embed.js - var hasGraphQLComment = ast.leadingComments && ast.leadingComments.some(function (comment) { - return comment.type === "CommentBlock" && comment.value === " GraphQL "; - }); - - if (hasGraphQLComment || parent.type === "CallExpression" && parent.callee.name === "graphql") { - newObj.quasis.forEach(function (quasi) { - return delete quasi.value; - }); - } - } -} - -var clean_1 = clean; - -var detectNewline = createCommonjsModule(function (module) { - 'use strict'; - - module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - var newlines = str.match(/(?:\r?\n)/g) || []; - - if (newlines.length === 0) { - return null; - } - - var crlf = newlines.filter(function (el) { - return el === '\r\n'; - }).length; - var lf = newlines.length - crlf; - return crlf > lf ? '\r\n' : '\n'; - }; - - module.exports.graceful = function (str) { - return module.exports(str) || '\n'; - }; -}); - -var build = createCommonjsModule(function (module, exports) { - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.extract = extract; - exports.strip = strip; - exports.parse = parse; - exports.parseWithComments = parseWithComments; - exports.print = print; - - var _detectNewline; - - function _load_detectNewline() { - return _detectNewline = _interopRequireDefault(detectNewline); - } - - var _os; - - function _load_os() { - return _os = require$$1$1; - } - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; - } - /** - * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * - */ - - - var commentEndRe = /\*\/$/; - var commentStartRe = /^\/\*\*/; - var docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; - var lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g; - var ltrimNewlineRe = /^(\r?\n)+/; - var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g; - var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; - var stringStartRe = /(\r?\n|^) *\* ?/g; - - function extract(contents) { - var match = contents.match(docblockRe); - return match ? match[0].trimLeft() : ''; - } - - function strip(contents) { - var match = contents.match(docblockRe); - return match && match[0] ? contents.substring(match[0].length) : contents; - } - - function parse(docblock) { - return parseWithComments(docblock).pragmas; - } - - function parseWithComments(docblock) { - var line = (0, (_detectNewline || _load_detectNewline()).default)(docblock) || (_os || _load_os()).EOL; - - docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives - - var prev = ''; - - while (prev !== docblock) { - prev = docblock; - docblock = docblock.replace(multilineRe, "".concat(line, "$1 $2").concat(line)); - } - - docblock = docblock.replace(ltrimNewlineRe, '').trimRight(); - var result = Object.create(null); - var comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight(); - var match; - - while (match = propertyRe.exec(docblock)) { - // strip linecomments from pragmas - var nextPragma = match[2].replace(lineCommentRe, ''); - - if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) { - result[match[1]] = [].concat(result[match[1]], nextPragma); - } else { - result[match[1]] = nextPragma; - } - } - - return { - comments: comments, - pragmas: result - }; - } - - function print(_ref) { - var _ref$comments = _ref.comments; - var comments = _ref$comments === undefined ? '' : _ref$comments; - var _ref$pragmas = _ref.pragmas; - var pragmas = _ref$pragmas === undefined ? {} : _ref$pragmas; - - var line = (0, (_detectNewline || _load_detectNewline()).default)(comments) || (_os || _load_os()).EOL; - - var head = '/**'; - var start = ' *'; - var tail = ' */'; - var keys = Object.keys(pragmas); - var printedObject = keys.map(function (key) { - return printKeyValues(key, pragmas[key]); - }).reduce(function (arr, next) { - return arr.concat(next); - }, []).map(function (keyValue) { - return start + ' ' + keyValue + line; - }).join(''); - - if (!comments) { - if (keys.length === 0) { - return ''; - } - - if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) { - var value = pragmas[keys[0]]; - return "".concat(head, " ").concat(printKeyValues(keys[0], value)[0]).concat(tail); - } - } - - var printedComments = comments.split(line).map(function (textLine) { - return "".concat(start, " ").concat(textLine); - }).join(line) + line; - return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail; - } - - function printKeyValues(key, valueOrArray) { - return [].concat(valueOrArray).map(function (value) { - return "@".concat(key, " ").concat(value).trim(); - }); - } -}); -unwrapExports(build); - -function hasPragma(text) { - var pragmas = Object.keys(build.parse(build.extract(text))); - return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1; -} - -function insertPragma$1(text) { - var parsedDocblock = build.parseWithComments(build.extract(text)); - var pragmas = Object.assign({ - format: "" - }, parsedDocblock.pragmas); - var newDocblock = build.print({ - pragmas: pragmas, - comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines - - }); - var strippedText = build.strip(text); - var separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n"; - return newDocblock + separatingNewlines + strippedText; -} - -var pragma = { - hasPragma: hasPragma, - insertPragma: insertPragma$1 -}; - -var addLeadingComment$2 = utilShared.addLeadingComment; -var addTrailingComment$2 = utilShared.addTrailingComment; -var addDanglingComment$2 = utilShared.addDanglingComment; - -function handleOwnLineComment(comment, text, options, ast, isLastComment) { - var precedingNode = comment.precedingNode, - enclosingNode = comment.enclosingNode, - followingNode = comment.followingNode; - - if (handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleMemberExpressionComments(enclosingNode, followingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleImportSpecifierComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) || handleAssignmentPatternComments(enclosingNode, comment) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options)) { - return true; - } - - return false; -} - -function handleEndOfLineComment(comment, text, options, ast, isLastComment) { - var precedingNode = comment.precedingNode, - enclosingNode = comment.enclosingNode, - followingNode = comment.followingNode; - - if (handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) || handleImportSpecifierComments(enclosingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleTypeAliasComments(enclosingNode, followingNode, comment) || handleVariableDeclaratorComments(enclosingNode, followingNode, comment)) { - return true; - } - - return false; -} - -function handleRemainingComment(comment, text, options, ast, isLastComment) { - var precedingNode = comment.precedingNode, - enclosingNode = comment.enclosingNode, - followingNode = comment.followingNode; - - if (handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment, options) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleCommentAfterArrowParams(text, enclosingNode, comment, options) || handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) || handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) || handleBreakAndContinueStatementComments(enclosingNode, comment)) { - return true; - } - - return false; -} - -function addBlockStatementFirstComment(node, comment) { - var body = node.body.filter(function (n) { - return n.type !== "EmptyStatement"; - }); - - if (body.length === 0) { - addDanglingComment$2(node, comment); - } else { - addLeadingComment$2(body[0], comment); - } -} - -function addBlockOrNotComment(node, comment) { - if (node.type === "BlockStatement") { - addBlockStatementFirstComment(node, comment); - } else { - addLeadingComment$2(node, comment); - } -} // There are often comments before the else clause of if statements like -// -// if (1) { ... } -// // comment -// else { ... } -// -// They are being attached as leading comments of the BlockExpression which -// is not well printed. What we want is to instead move the comment inside -// of the block and make it leadingComment of the first element of the block -// or dangling comment of the block if there is nothing inside -// -// if (1) { ... } -// else { -// // comment -// ... -// } - - -function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) { - if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) { - return false; - } // We unfortunately have no way using the AST or location of nodes to know - // if the comment is positioned before the condition parenthesis: - // if (a /* comment */) {} - // The only workaround I found is to look at the next character to see if - // it is a ). - - - var nextCharacter = util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd); - - if (nextCharacter === ")") { - addTrailingComment$2(precedingNode, comment); - return true; - } // Comments before `else`: - // - treat as trailing comments of the consequent, if it's a BlockStatement - // - treat as a dangling comment otherwise - - - if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) { - if (precedingNode.type === "BlockStatement") { - addTrailingComment$2(precedingNode, comment); - } else { - addDanglingComment$2(enclosingNode, comment); - } - - return true; - } - - if (followingNode.type === "BlockStatement") { - addBlockStatementFirstComment(followingNode, comment); - return true; - } - - if (followingNode.type === "IfStatement") { - addBlockOrNotComment(followingNode.consequent, comment); - return true; - } // For comments positioned after the condition parenthesis in an if statement - // before the consequent with or without brackets on, such as - // if (a) /* comment */ {} or if (a) /* comment */ true, - // we look at the next character to see if it is a { or if the following node - // is the consequent for the if statement - - - if (nextCharacter === "{" || enclosingNode.consequent === followingNode) { - addLeadingComment$2(followingNode, comment); - return true; - } - - return false; -} // Same as IfStatement but for TryStatement - - -function handleTryStatementComments(enclosingNode, followingNode, comment) { - if (!enclosingNode || enclosingNode.type !== "TryStatement" || !followingNode) { - return false; - } - - if (followingNode.type === "BlockStatement") { - addBlockStatementFirstComment(followingNode, comment); - return true; - } - - if (followingNode.type === "TryStatement") { - addBlockOrNotComment(followingNode.finalizer, comment); - return true; - } - - if (followingNode.type === "CatchClause") { - addBlockOrNotComment(followingNode.body, comment); - return true; - } - - return false; -} - -function handleMemberExpressionComments(enclosingNode, followingNode, comment) { - if (enclosingNode && enclosingNode.type === "MemberExpression" && followingNode && followingNode.type === "Identifier") { - addLeadingComment$2(enclosingNode, comment); - return true; - } - - return false; -} - -function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) { - var isSameLineAsPrecedingNode = precedingNode && !util.hasNewlineInRange(text, options.locEnd(precedingNode), options.locStart(comment)); - - if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && enclosingNode.type === "ConditionalExpression" && followingNode) { - addLeadingComment$2(followingNode, comment); - return true; - } - - return false; -} - -function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) { - if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") { - addTrailingComment$2(enclosingNode.value.left, comment); - return true; - } - - return false; -} - -function handleClassComments(enclosingNode, precedingNode, followingNode, comment) { - if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression") && enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) { - if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) { - addLeadingComment$2(enclosingNode, comment); - } else { - addTrailingComment$2(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment); - } - - return true; - } - - return false; -} - -function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) { - // This is only needed for estree parsers (flow, typescript) to attach - // after a method name: - // obj = { fn /*comment*/() {} }; - if (enclosingNode && precedingNode && (enclosingNode.type === "Property" || enclosingNode.type === "MethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) }; - // comment should be attached to value instead of key - util.getNextNonSpaceNonCommentCharacter(text, precedingNode, options.locEnd) !== ":") { - addTrailingComment$2(precedingNode, comment); - return true; - } // Print comments between decorators and class methods as a trailing comment - // on the decorator node instead of the method node - - - if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "MethodDefinition")) { - addTrailingComment$2(precedingNode, comment); - return true; - } - - return false; -} - -function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) { - if (util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== "(") { - return false; - } - - if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) { - addTrailingComment$2(precedingNode, comment); - return true; - } - - return false; -} - -function handleCommentAfterArrowParams(text, enclosingNode, comment, options) { - if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) { - return false; - } - - var index = utilShared.getNextNonSpaceNonCommentCharacterIndex(text, comment, options); - - if (text.substr(index, 2) === "=>") { - addDanglingComment$2(enclosingNode, comment); - return true; - } - - return false; -} - -function handleCommentInEmptyParens(text, enclosingNode, comment, options) { - if (util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== ")") { - return false; - } // Only add dangling comments to fix the case when no params are present, - // i.e. a function without any argument. - - - if (enclosingNode && ((enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ArrowFunctionExpression" && (enclosingNode.body.type !== "CallExpression" || enclosingNode.body.arguments.length === 0) || enclosingNode.type === "ClassMethod" || enclosingNode.type === "ObjectMethod") && enclosingNode.params.length === 0 || enclosingNode.type === "CallExpression" && enclosingNode.arguments.length === 0)) { - addDanglingComment$2(enclosingNode, comment); - return true; - } - - if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) { - addDanglingComment$2(enclosingNode.value, comment); - return true; - } - - return false; -} - -function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) { - // Type definitions functions - if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") { - addTrailingComment$2(precedingNode, comment); - return true; - } // Real functions - - - if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && (enclosingNode.type === "ArrowFunctionExpression" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "ObjectMethod" || enclosingNode.type === "ClassMethod") && util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ")") { - addTrailingComment$2(precedingNode, comment); - return true; - } - - return false; -} - -function handleImportSpecifierComments(enclosingNode, comment) { - if (enclosingNode && enclosingNode.type === "ImportSpecifier") { - addLeadingComment$2(enclosingNode, comment); - return true; - } - - return false; -} - -function handleLabeledStatementComments(enclosingNode, comment) { - if (enclosingNode && enclosingNode.type === "LabeledStatement") { - addLeadingComment$2(enclosingNode, comment); - return true; - } - - return false; -} - -function handleBreakAndContinueStatementComments(enclosingNode, comment) { - if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) { - addTrailingComment$2(enclosingNode, comment); - return true; - } - - return false; -} - -function handleCallExpressionComments(precedingNode, enclosingNode, comment) { - if (enclosingNode && enclosingNode.type === "CallExpression" && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) { - addLeadingComment$2(enclosingNode.arguments[0], comment); - return true; - } - - return false; -} - -function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) { - if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) { - addTrailingComment$2(precedingNode, comment); - return true; - } - - return false; -} - -function handlePropertyComments(enclosingNode, comment) { - if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) { - addLeadingComment$2(enclosingNode, comment); - return true; - } - - return false; -} - -function handleOnlyComments(enclosingNode, ast, comment, isLastComment) { - // With Flow the enclosingNode is undefined so use the AST instead. - if (ast && ast.body && ast.body.length === 0) { - if (isLastComment) { - addDanglingComment$2(ast, comment); - } else { - addLeadingComment$2(ast, comment); - } - - return true; - } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) { - if (isLastComment) { - addDanglingComment$2(enclosingNode, comment); - } else { - addLeadingComment$2(enclosingNode, comment); - } - - return true; - } - - return false; -} - -function handleForComments(enclosingNode, precedingNode, comment) { - if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) { - addLeadingComment$2(enclosingNode, comment); - return true; - } - - return false; -} - -function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) { - if (precedingNode && enclosingNode && enclosingNode.type === "ImportDeclaration" && util.hasNewline(text, options.locEnd(comment))) { - addTrailingComment$2(precedingNode, comment); - return true; - } - - return false; -} - -function handleAssignmentPatternComments(enclosingNode, comment) { - if (enclosingNode && enclosingNode.type === "AssignmentPattern") { - addLeadingComment$2(enclosingNode, comment); - return true; - } - - return false; -} - -function handleTypeAliasComments(enclosingNode, followingNode, comment) { - if (enclosingNode && enclosingNode.type === "TypeAlias") { - addLeadingComment$2(enclosingNode, comment); - return true; - } - - return false; -} - -function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) { - if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression")) { - addLeadingComment$2(followingNode, comment); - return true; - } - - return false; -} - -function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) { - if (!enclosingNode || enclosingNode.type !== "TSMappedType") { - return false; - } - - if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) { - addLeadingComment$2(followingNode.name, comment); - return true; - } - - if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) { - addTrailingComment$2(precedingNode.constraint, comment); - return true; - } - - return false; -} - -function isBlockComment(comment) { - return comment.type === "Block" || comment.type === "CommentBlock"; -} - -var comments$3 = { - handleOwnLineComment: handleOwnLineComment, - handleEndOfLineComment: handleEndOfLineComment, - handleRemainingComment: handleRemainingComment, - isBlockComment: isBlockComment -}; - -function hasClosureCompilerTypeCastComment(text, path, locStart, locEnd) { - // https://github.com/google/closure-compiler/wiki/Annotating-Types#type-casts - // Syntax example: var x = /** @type {string} */ (fruit); - var n = path.getValue(); - return util.getNextNonSpaceNonCommentCharacter(text, n, locEnd) === ")" && (hasTypeCastComment(n) || hasAncestorTypeCastComment(0)); // for sub-item: /** @type {array} */ (numberOrString).map(x => x); - - function hasAncestorTypeCastComment(index) { - var ancestor = path.getParentNode(index); - return ancestor && util.getNextNonSpaceNonCommentCharacter(text, ancestor, locEnd) !== ")" && /^[\s(]*$/.test(text.slice(locStart(ancestor), locStart(n))) ? hasTypeCastComment(ancestor) || hasAncestorTypeCastComment(index + 1) : false; - } - - function hasTypeCastComment(node) { - return node.comments && node.comments.some(function (comment) { - return comment.leading && comments$3.isBlockComment(comment) && comment.value.match(/^\*\s*@type\s*{[^}]+}\s*$/) && util.getNextNonSpaceNonCommentCharacter(text, comment, locEnd) === "("; - }); - } -} - -function needsParens(path, options) { - var parent = path.getParentNode(); - - if (!parent) { - return false; - } - - var name = path.getName(); - var node = path.getNode(); // If the value of this path is some child of a Node and not a Node - // itself, then it doesn't need parentheses. Only Node objects (in - // fact, only Expression nodes) need parentheses. - - if (path.getValue() !== node) { - return false; - } // Only statements don't need parentheses. - - - if (isStatement(node)) { - return false; - } // Closure compiler requires that type casted expressions to be surrounded by - // parentheses. - - - if (hasClosureCompilerTypeCastComment(options.originalText, path, options.locStart, options.locEnd)) { - return true; - } // Identifiers never need parentheses. - - - if (node.type === "Identifier") { - return false; - } - - if (parent.type === "ParenthesizedExpression") { - return false; - } // Add parens around the extends clause of a class. It is needed for almost - // all expressions. - - - if ((parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node && (node.type === "ArrowFunctionExpression" || node.type === "AssignmentExpression" || node.type === "AwaitExpression" || node.type === "BinaryExpression" || node.type === "ConditionalExpression" || node.type === "LogicalExpression" || node.type === "NewExpression" || node.type === "ObjectExpression" || node.type === "ParenthesizedExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "UnaryExpression" || node.type === "UpdateExpression" || node.type === "YieldExpression")) { - return true; - } - - if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway - util.startsWithNoLookaheadToken(node, - /* forbidFunctionClassAndDoExpr */ - false) || parent.type === "ExpressionStatement" && util.startsWithNoLookaheadToken(node, - /* forbidFunctionClassAndDoExpr */ - true)) { - return true; - } - - switch (node.type) { - case "CallExpression": - { - var firstParentNotMemberExpression = parent; - var i = 0; - - while (firstParentNotMemberExpression && firstParentNotMemberExpression.type === "MemberExpression") { - firstParentNotMemberExpression = path.getParentNode(++i); - } - - if (firstParentNotMemberExpression.type === "NewExpression" && firstParentNotMemberExpression.callee === path.getParentNode(i - 1)) { - return true; - } - - return false; - } - - case "SpreadElement": - case "SpreadProperty": - return parent.type === "MemberExpression" && name === "object" && parent.object === node; - - case "UpdateExpression": - if (parent.type === "UnaryExpression") { - return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-"); - } - - // else fallthrough - - case "UnaryExpression": - switch (parent.type) { - case "UnaryExpression": - return node.operator === parent.operator && (node.operator === "+" || node.operator === "-"); - - case "MemberExpression": - return name === "object" && parent.object === node; - - case "TaggedTemplateExpression": - return true; - - case "NewExpression": - case "CallExpression": - return name === "callee" && parent.callee === node; - - case "BinaryExpression": - return parent.operator === "**" && name === "left"; - - case "TSNonNullExpression": - return true; - - default: - return false; - } - - case "BinaryExpression": - { - if (parent.type === "UpdateExpression") { - return true; - } - - var isLeftOfAForStatement = function isLeftOfAForStatement(node) { - var i = 0; - - while (node) { - var _parent = path.getParentNode(i++); - - if (!_parent) { - return false; - } - - if (_parent.type === "ForStatement" && _parent.init === node) { - return true; - } - - node = _parent; - } - - return false; - }; - - if (node.operator === "in" && isLeftOfAForStatement(node)) { - return true; - } - } - // fallthrough - - case "TSTypeAssertionExpression": - case "TSAsExpression": - case "LogicalExpression": - switch (parent.type) { - case "ConditionalExpression": - return node.type === "TSAsExpression"; - - case "CallExpression": - case "NewExpression": - return name === "callee" && parent.callee === node; - - case "ClassDeclaration": - case "TSAbstractClassDeclaration": - return name === "superClass" && parent.superClass === node; - - case "TSTypeAssertionExpression": - case "TaggedTemplateExpression": - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - case "BindExpression": - case "AwaitExpression": - case "TSAsExpression": - case "TSNonNullExpression": - case "UpdateExpression": - return true; - - case "MemberExpression": - return name === "object" && parent.object === node; - - case "AssignmentExpression": - return parent.left === node && (node.type === "TSTypeAssertionExpression" || node.type === "TSAsExpression"); - - case "Decorator": - return parent.expression === node && (node.type === "TSTypeAssertionExpression" || node.type === "TSAsExpression"); - - case "BinaryExpression": - case "LogicalExpression": - { - if (!node.operator && node.type !== "TSTypeAssertionExpression") { - return true; - } - - var po = parent.operator; - var pp = util.getPrecedence(po); - var no = node.operator; - var np = util.getPrecedence(no); - - if (pp > np) { - return true; - } - - if ((po === "||" || po === "??") && no === "&&") { - return true; - } - - if (pp === np && name === "right") { - assert$3.strictEqual(parent.right, node); - return true; - } - - if (pp === np && !util.shouldFlatten(po, no)) { - return true; - } - - if (pp < np && no === "%") { - return !util.shouldFlatten(po, no); - } // Add parenthesis when working with binary operators - // It's not stricly needed but helps with code understanding - - - if (util.isBitwiseOperator(po)) { - return true; - } - - return false; - } - - default: - return false; - } - - case "TSParenthesizedType": - { - var grandParent = path.getParentNode(1); - - if ((parent.type === "TSTypeParameter" || parent.type === "TypeParameter" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAnnotation" || parent.type === "GenericTypeAnnotation" || parent.type === "TSTypeReference") && node.typeAnnotation.type === "TSTypeAnnotation" && node.typeAnnotation.typeAnnotation.type !== "TSFunctionType" && grandParent.type !== "TSTypeOperator") { - return false; - } // Delegate to inner TSParenthesizedType - - - if (node.typeAnnotation.type === "TSParenthesizedType") { - return false; - } - - return true; - } - - case "SequenceExpression": - switch (parent.type) { - case "ReturnStatement": - return false; - - case "ForStatement": - // Although parentheses wouldn't hurt around sequence - // expressions in the head of for loops, traditional style - // dictates that e.g. i++, j++ should not be wrapped with - // parentheses. - return false; - - case "ExpressionStatement": - return name !== "expression"; - - case "ArrowFunctionExpression": - // We do need parentheses, but SequenceExpressions are handled - // specially when printing bodies of arrow functions. - return name !== "body"; - - default: - // Otherwise err on the side of overparenthesization, adding - // explicit exceptions above if this proves overzealous. - return true; - } - - case "YieldExpression": - if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") { - return true; - } - - // else fallthrough - - case "AwaitExpression": - switch (parent.type) { - case "TaggedTemplateExpression": - case "UnaryExpression": - case "BinaryExpression": - case "LogicalExpression": - case "SpreadElement": - case "SpreadProperty": - case "TSAsExpression": - case "TSNonNullExpression": - case "BindExpression": - return true; - - case "MemberExpression": - return parent.object === node; - - case "NewExpression": - case "CallExpression": - return parent.callee === node; - - case "ConditionalExpression": - return parent.test === node; - - default: - return false; - } - - case "ArrayTypeAnnotation": - return parent.type === "NullableTypeAnnotation"; - - case "IntersectionTypeAnnotation": - case "UnionTypeAnnotation": - return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation"; - - case "NullableTypeAnnotation": - return parent.type === "ArrayTypeAnnotation"; - - case "FunctionTypeAnnotation": - { - var ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent; - return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses - // are really needed, but since ??T doesn't make sense this check - // will almost never be true. - ancestor.type === "NullableTypeAnnotation"; - } - - case "StringLiteral": - case "NumericLiteral": - case "Literal": - if (typeof node.value === "string" && parent.type === "ExpressionStatement" && ( // TypeScript workaround for eslint/typescript-eslint-parser#267 - // See corresponding workaround in printer.js case: "Literal" - options.parser !== "typescript" && !parent.directive || options.parser === "typescript" && options.originalText.substr(options.locStart(node) - 1, 1) === "(")) { - // To avoid becoming a directive - var _grandParent = path.getParentNode(1); - - return _grandParent.type === "Program" || _grandParent.type === "BlockStatement"; - } - - return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node; - - case "AssignmentExpression": - { - var _grandParent2 = path.getParentNode(1); - - if (parent.type === "ArrowFunctionExpression" && parent.body === node) { - return true; - } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) { - return false; - } else if (parent.type === "TSPropertySignature" && parent.name === node) { - return false; - } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) { - return false; - } else if (parent.type === "ExpressionStatement") { - return node.left.type === "ObjectPattern"; - } else if (parent.type === "TSPropertySignature" && parent.key === node) { - return false; - } else if (parent.type === "AssignmentExpression") { - return false; - } else if (parent.type === "SequenceExpression" && _grandParent2 && _grandParent2.type === "ForStatement" && (_grandParent2.init === parent || _grandParent2.update === parent)) { - return false; - } - - return true; - } - - case "ConditionalExpression": - switch (parent.type) { - case "TaggedTemplateExpression": - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - case "BinaryExpression": - case "LogicalExpression": - case "ExportDefaultDeclaration": - case "AwaitExpression": - case "JSXSpreadAttribute": - case "TSTypeAssertionExpression": - case "TypeCastExpression": - case "TSAsExpression": - case "TSNonNullExpression": - return true; - - case "NewExpression": - case "CallExpression": - return name === "callee" && parent.callee === node; - - case "ConditionalExpression": - return name === "test" && parent.test === node; - - case "MemberExpression": - return name === "object" && parent.object === node; - - default: - return false; - } - - case "FunctionExpression": - switch (parent.type) { - case "CallExpression": - return name === "callee"; - // Not strictly necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses. - - case "TaggedTemplateExpression": - return true; - // This is basically a kind of IIFE. - - case "ExportDefaultDeclaration": - return true; - - default: - return false; - } - - case "ArrowFunctionExpression": - switch (parent.type) { - case "CallExpression": - return name === "callee"; - - case "NewExpression": - return name === "callee"; - - case "MemberExpression": - return name === "object"; - - case "TSAsExpression": - case "BindExpression": - case "TaggedTemplateExpression": - case "UnaryExpression": - case "LogicalExpression": - case "BinaryExpression": - case "AwaitExpression": - case "TSTypeAssertionExpression": - return true; - - case "ConditionalExpression": - return name === "test"; - - default: - return false; - } - - case "ClassExpression": - return parent.type === "ExportDefaultDeclaration"; - - case "OptionalMemberExpression": - return parent.type === "MemberExpression"; - } - - return false; -} - -function isStatement(node) { - return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForAwaitStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "IfStatement" || node.type === "ImportDeclaration" || node.type === "InterfaceDeclaration" || node.type === "LabeledStatement" || node.type === "MethodDefinition" || node.type === "ReturnStatement" || node.type === "SwitchStatement" || node.type === "ThrowStatement" || node.type === "TryStatement" || node.type === "TSAbstractClassDeclaration" || node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSModuleDeclaration" || node.type === "TSNamespaceExportDeclaration" || node.type === "TypeAlias" || node.type === "VariableDeclaration" || node.type === "WhileStatement" || node.type === "WithStatement"; -} - -var needsParens_1 = needsParens; - -var getParentExportDeclaration$1 = util.getParentExportDeclaration; -var isExportDeclaration$1 = util.isExportDeclaration; -var shouldFlatten$1 = util.shouldFlatten; -var getNextNonSpaceNonCommentCharacter$1 = util.getNextNonSpaceNonCommentCharacter; -var hasNewline$2 = util.hasNewline; -var hasNewlineInRange$1 = util.hasNewlineInRange; -var getLast$4 = util.getLast; -var getStringWidth$2 = util.getStringWidth; -var printString$1 = util.printString; -var printNumber$1 = util.printNumber; -var hasIgnoreComment$1 = util.hasIgnoreComment; -var skipWhitespace$1 = util.skipWhitespace; -var hasNodeIgnoreComment$1 = util.hasNodeIgnoreComment; -var getPenultimate$1 = util.getPenultimate; -var startsWithNoLookaheadToken$1 = util.startsWithNoLookaheadToken; -var getIndentSize$1 = util.getIndentSize; -var matchAncestorTypes$1 = util.matchAncestorTypes; -var isWithinParentArrayProperty$1 = util.isWithinParentArrayProperty; -var isNextLineEmpty$2 = utilShared.isNextLineEmpty; -var isNextLineEmptyAfterIndex$1 = utilShared.isNextLineEmptyAfterIndex; -var getNextNonSpaceNonCommentCharacterIndex$2 = utilShared.getNextNonSpaceNonCommentCharacterIndex; -var isIdentifierName = utils.keyword.isIdentifierNameES6; -var insertPragma = pragma.insertPragma; -var _require$$4$builders = doc.builders; -var concat$4 = _require$$4$builders.concat; -var join$2 = _require$$4$builders.join; -var line$3 = _require$$4$builders.line; -var hardline$3 = _require$$4$builders.hardline; -var softline$1 = _require$$4$builders.softline; -var literalline$1 = _require$$4$builders.literalline; -var group$1 = _require$$4$builders.group; -var indent$2 = _require$$4$builders.indent; -var align$1 = _require$$4$builders.align; -var conditionalGroup$1 = _require$$4$builders.conditionalGroup; -var fill$2 = _require$$4$builders.fill; -var ifBreak$1 = _require$$4$builders.ifBreak; -var breakParent$2 = _require$$4$builders.breakParent; -var lineSuffixBoundary$1 = _require$$4$builders.lineSuffixBoundary; -var addAlignmentToDoc$2 = _require$$4$builders.addAlignmentToDoc; -var dedent$2 = _require$$4$builders.dedent; -var _require$$4$utils = doc.utils; -var willBreak$1 = _require$$4$utils.willBreak; -var isLineNext$1 = _require$$4$utils.isLineNext; -var isEmpty$1 = _require$$4$utils.isEmpty; -var removeLines$1 = _require$$4$utils.removeLines; -var printDocToString$1 = doc.printer.printDocToString; - -function shouldPrintComma(options, level) { - level = level || "es5"; - - switch (options.trailingComma) { - case "all": - if (level === "all") { - return true; - } - - // fallthrough - - case "es5": - if (level === "es5") { - return true; - } - - // fallthrough - - case "none": - default: - return false; - } -} - -function genericPrint$1(path, options, printPath, args) { - var node = path.getValue(); - var needsParens = false; - var linesWithoutParens = printPathNoParens(path, options, printPath, args); - - if (!node || isEmpty$1(linesWithoutParens)) { - return linesWithoutParens; - } - - var decorators = []; - - if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration, it will be - // responsible for printing node.decorators. - !getParentExportDeclaration$1(path)) { - var separator = node.decorators.length === 1 && isWithinParentArrayProperty$1(path, "params") ? line$3 : hardline$3; - path.each(function (decoratorPath) { - var decorator = decoratorPath.getValue(); - - if (decorator.expression) { - decorator = decorator.expression; - } else { - decorator = decorator.callee; - } - - decorators.push(printPath(decoratorPath), separator); - }, "decorators"); - } else if (isExportDeclaration$1(node) && node.declaration && node.declaration.decorators) { - // Export declarations are responsible for printing any decorators - // that logically apply to node.declaration. - path.each(function (decoratorPath) { - var decorator = decoratorPath.getValue(); - var prefix = decorator.type === "Decorator" ? "" : "@"; - decorators.push(prefix, printPath(decoratorPath), hardline$3); - }, "declaration", "decorators"); - } else { - // Nodes with decorators can't have parentheses, so we can avoid - // computing pathNeedsParens() except in this case. - needsParens = needsParens_1(path, options); - } - - var parts = []; - - if (needsParens) { - parts.unshift("("); - } - - parts.push(linesWithoutParens); - - if (needsParens) { - parts.push(")"); - } - - if (decorators.length > 0) { - return group$1(concat$4(decorators.concat(parts))); - } - - return concat$4(parts); -} - -function hasPrettierIgnore(path) { - return hasIgnoreComment$1(path) || hasJsxIgnoreComment(path); -} - -function hasJsxIgnoreComment(path) { - var node = path.getValue(); - var parent = path.getParentNode(); - - if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) { - return false; - } // Lookup the previous sibling, ignoring any empty JSXText elements - - - var index = parent.children.indexOf(node); - var prevSibling = null; - - for (var i = index; i > 0; i--) { - var candidate = parent.children[i - 1]; - - if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) { - continue; - } - - prevSibling = candidate; - break; - } - - return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find(function (comment) { - return comment.value.trim() === "prettier-ignore"; - }); -} // The following is the shared logic for -// ternary operators, namely ConditionalExpression -// and TSConditionalType - - -function formatTernaryOperator(path, options, print, operatorOptions) { - var n = path.getValue(); - var parts = []; - var operatorOpts = Object.assign({ - beforeParts: function beforeParts() { - return [""]; - }, - afterParts: function afterParts() { - return [""]; - }, - shouldCheckJsx: true, - operatorName: "ConditionalExpression", - consequentNode: "consequent", - alternateNode: "alternate", - testNode: "test", - breakNested: true - }, operatorOptions || {}); // We print a ConditionalExpression in either "JSX mode" or "normal mode". - // See tests/jsx/conditional-expression.js for more info. - - var jsxMode = false; - var parent = path.getParentNode(); - var forceNoIndent = parent.type === operatorOpts.operatorName; // Find the outermost non-ConditionalExpression parent, and the outermost - // ConditionalExpression parent. We'll use these to determine if we should - // print in JSX mode. - - var currentParent; - var previousParent; - var i = 0; - - do { - previousParent = currentParent || n; - currentParent = path.getParentNode(i); - i++; - } while (currentParent && currentParent.type === operatorOpts.operatorName); - - var firstNonConditionalParent = currentParent || parent; - var lastConditionalParent = previousParent; - - if (operatorOpts.shouldCheckJsx && isJSXNode(n[operatorOpts.testNode]) || isJSXNode(n[operatorOpts.consequentNode]) || isJSXNode(n[operatorOpts.alternateNode]) || conditionalExpressionChainContainsJSX(lastConditionalParent)) { - jsxMode = true; - forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in - // parens when using ?: within JSX, because the parens are analogous to - // curly braces in an if statement. - - var wrap = function wrap(doc$$2) { - return concat$4([ifBreak$1("(", ""), indent$2(concat$4([softline$1, doc$$2])), softline$1, ifBreak$1(")", "")]); - }; // The only things we don't wrap are: - // * Nested conditional expressions in alternates - // * null - - - var isNull = function isNull(node) { - return node.type === "NullLiteral" || node.type === "Literal" && node.value === null; - }; - - parts.push(" ? ", isNull(n[operatorOpts.consequentNode]) ? path.call(print, operatorOpts.consequentNode) : wrap(path.call(print, operatorOpts.consequentNode)), " : ", n[operatorOpts.alternateNode].type === operatorOpts.operatorName || isNull(n[operatorOpts.alternateNode]) ? path.call(print, operatorOpts.alternateNode) : wrap(path.call(print, operatorOpts.alternateNode))); - } else { - // normal mode - var part = concat$4([line$3, "? ", n[operatorOpts.consequentNode].type === operatorOpts.operatorName ? ifBreak$1("", "(") : "", align$1(2, path.call(print, operatorOpts.consequentNode)), n[operatorOpts.consequentNode].type === operatorOpts.operatorName ? ifBreak$1("", ")") : "", line$3, ": ", align$1(2, path.call(print, operatorOpts.alternateNode))]); - parts.push(parent.type === operatorOpts.operatorName ? options.useTabs ? dedent$2(indent$2(part)) : align$1(Math.max(0, options.tabWidth - 2), part) : part); - } // We want a whole chain of ConditionalExpressions to all - // break if any of them break. That means we should only group around the - // outer-most ConditionalExpression. - - - var maybeGroup = function maybeGroup(doc$$2) { - return operatorOpts.breakNested ? parent === firstNonConditionalParent ? group$1(doc$$2) : doc$$2 : group$1(doc$$2); - }; // Always group in normal mode. - // Break the closing paren to keep the chain right after it: - // (a - // ? b - // : c - // ).call() - - - var breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed; - return maybeGroup(concat$4([].concat(operatorOpts.beforeParts(), forceNoIndent ? concat$4(parts) : indent$2(concat$4(parts)), operatorOpts.afterParts(breakClosingParen)))); -} - -function getTypeScriptMappedTypeModifier(tokenNode, keyword) { - if (tokenNode.type === "TSPlusToken") { - return "+" + keyword; - } else if (tokenNode.type === "TSMinusToken") { - return "-" + keyword; - } - - return keyword; -} - -function printPathNoParens(path, options, print, args) { - var n = path.getValue(); - var semi = options.semi ? ";" : ""; - - if (!n) { - return ""; - } - - if (typeof n === "string") { - return n; - } - - var parts = []; - - switch (n.type) { - case "File": - // Print @babel/parser's InterpreterDirective here so that - // leading comments on the `Program` node get printed after the hashbang. - if (n.program && n.program.interpreter) { - parts.push(path.call(function (programPath) { - return programPath.call(print, "interpreter"); - }, "program")); - } - - parts.push(path.call(print, "program")); - return concat$4(parts); - - case "Program": - // Babel 6 - if (n.directives) { - path.each(function (childPath) { - parts.push(print(childPath), semi, hardline$3); - - if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) { - parts.push(hardline$3); - } - }, "directives"); - } - - parts.push(path.call(function (bodyPath) { - return printStatementSequence(bodyPath, options, print); - }, "body")); - parts.push(comments.printDanglingComments(path, options, - /* sameIndent */ - true)); // Only force a trailing newline if there were any contents. - - if (n.body.length || n.comments) { - parts.push(hardline$3); - } - - return concat$4(parts); - // Babel extension. - - case "EmptyStatement": - return ""; - - case "ExpressionStatement": - // Detect Flow-parsed directives - if (n.directive) { - return concat$4([nodeStr(n.expression, options, true), semi]); - } // Do not append semicolon after the only JSX element in a program - - - return concat$4([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown(options, path) ? "" : semi]); - // Babel extension. - - case "ParenthesizedExpression": - return concat$4(["(", path.call(print, "expression"), ")"]); - - case "AssignmentExpression": - return printAssignment(n.left, path.call(print, "left"), concat$4([" ", n.operator]), n.right, path.call(print, "right"), options); - - case "BinaryExpression": - case "LogicalExpression": - { - var parent = path.getParentNode(); - var parentParent = path.getParentNode(1); - var isInsideParenthesis = n !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement"); - - var _parts = printBinaryishExpressions(path, print, options, - /* isNested */ - false, isInsideParenthesis); // if ( - // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft - // ) { - // - // looks super weird, we want to break the children if the parent breaks - // - // if ( - // this.hasPlugin("dynamicImports") && - // this.lookahead().type === tt.parenLeft - // ) { - - - if (isInsideParenthesis) { - return concat$4(_parts); - } // Break between the parens in unaries or in a member expression, i.e. - // - // ( - // a && - // b && - // c - // ).call() - - - if (parent.type === "UnaryExpression" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed) { - return group$1(concat$4([indent$2(concat$4([softline$1, concat$4(_parts)])), softline$1])); - } // Avoid indenting sub-expressions in some cases where the first sub-expression is already - // indented accordingly. We should indent sub-expressions where the first case isn't indented. - - - var shouldNotIndent = parent.type === "ReturnStatement" || parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || n === parent.body && parent.type === "ArrowFunctionExpression" || n !== parent.body && parent.type === "ForStatement" || parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement"; - var shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || parent.type === "ObjectProperty" || parent.type === "Property"; - var samePrecedenceSubExpression = isBinaryish(n.left) && shouldFlatten$1(n.operator, n.left.operator); - - if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) { - return group$1(concat$4(_parts)); - } - - var rest = concat$4(_parts.slice(1)); - return group$1(concat$4([// Don't include the initial expression in the indentation - // level. The first item is guaranteed to be the first - // left-most expression. - _parts.length > 0 ? _parts[0] : "", indent$2(rest)])); - } - - case "AssignmentPattern": - return concat$4([path.call(print, "left"), " = ", path.call(print, "right")]); - - case "TSTypeAssertionExpression": - { - var shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression"); - var castGroup = group$1(concat$4(["<", indent$2(concat$4([softline$1, path.call(print, "typeAnnotation")])), softline$1, ">"])); - var exprContents = concat$4([ifBreak$1("("), indent$2(concat$4([softline$1, path.call(print, "expression")])), softline$1, ifBreak$1(")")]); - - if (shouldBreakAfterCast) { - return conditionalGroup$1([concat$4([castGroup, path.call(print, "expression")]), concat$4([castGroup, group$1(exprContents, { - shouldBreak: true - })]), concat$4([castGroup, path.call(print, "expression")])]); - } - - return group$1(concat$4([castGroup, path.call(print, "expression")])); - } - - case "OptionalMemberExpression": - case "MemberExpression": - { - var _parent = path.getParentNode(); - - var firstNonMemberParent; - var i = 0; - - do { - firstNonMemberParent = path.getParentNode(i); - i++; - } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression")); - - var shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "VariableDeclarator" && firstNonMemberParent.id.type !== "Identifier" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || n.computed || n.object.type === "Identifier" && n.property.type === "Identifier" && _parent.type !== "MemberExpression" && _parent.type !== "OptionalMemberExpression"; - return concat$4([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$1(indent$2(concat$4([softline$1, printMemberLookup(path, options, print)])))]); - } - - case "MetaProperty": - return concat$4([path.call(print, "meta"), ".", path.call(print, "property")]); - - case "BindExpression": - if (n.object) { - parts.push(path.call(print, "object")); - } - - parts.push(group$1(indent$2(concat$4([softline$1, printBindExpressionCallee(path, options, print)])))); - return concat$4(parts); - - case "Identifier": - { - return concat$4([n.name, printOptionalToken(path), printTypeAnnotation(path, options, print)]); - } - - case "SpreadElement": - case "SpreadElementPattern": - case "RestProperty": - case "SpreadProperty": - case "SpreadPropertyPattern": - case "RestElement": - case "ObjectTypeSpreadProperty": - return concat$4(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]); - - case "FunctionDeclaration": - case "FunctionExpression": - if (isNodeStartingWithDeclare(n, options)) { - parts.push("declare "); - } - - parts.push(printFunctionDeclaration(path, print, options)); - - if (!n.body) { - parts.push(semi); - } - - return concat$4(parts); - - case "ArrowFunctionExpression": - { - if (n.async) { - parts.push("async "); - } - - if (shouldPrintParamsWithoutParens(path, options)) { - parts.push(path.call(print, "params", 0)); - } else { - parts.push(group$1(concat$4([printFunctionParams(path, print, options, - /* expandLast */ - args && (args.expandLastArg || args.expandFirstArg), - /* printTypeParams */ - true), printReturnType(path, print, options)]))); - } - - var dangling = comments.printDanglingComments(path, options, - /* sameIndent */ - true, function (comment) { - var nextCharacter = getNextNonSpaceNonCommentCharacterIndex$2(options.originalText, comment, options); - return options.originalText.substr(nextCharacter, 2) === "=>"; - }); - - if (dangling) { - parts.push(" ", dangling); - } - - parts.push(" =>"); - var body = path.call(function (bodyPath) { - return print(bodyPath, args); - }, "body"); // We want to always keep these types of nodes on the same line - // as the arrow. - - if (!hasLeadingOwnLineComment(options.originalText, n.body, options) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode(n.body) || isTemplateOnItsOwnLine(n.body, options.originalText, options) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) { - return group$1(concat$4([concat$4(parts), " ", body])); - } // We handle sequence expressions as the body of arrows specially, - // so that the required parentheses end up on their own lines. - - - if (n.body.type === "SequenceExpression") { - return group$1(concat$4([concat$4(parts), group$1(concat$4([" (", indent$2(concat$4([softline$1, body])), softline$1, ")"]))])); - } // if the arrow function is expanded as last argument, we are adding a - // level of indentation and need to add a softline to align the closing ) - // with the opening (, or if it's inside a JSXExpression (e.g. an attribute) - // we should align the expression's closing } with the line with the opening {. - - - var shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length); - var printTrailingComma = args && args.expandLastArg && shouldPrintComma(options, "all"); // In order to avoid confusion between - // a => a ? a : a - // a <= a ? a : a - - var shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$1(n.body, - /* forbidFunctionAndClass */ - false); - return group$1(concat$4([concat$4(parts), group$1(concat$4([indent$2(concat$4([line$3, shouldAddParens ? ifBreak$1("", "(") : "", body, shouldAddParens ? ifBreak$1("", ")") : ""])), shouldAddSoftLine ? concat$4([ifBreak$1(printTrailingComma ? "," : ""), softline$1]) : ""]))])); - } - - case "MethodDefinition": - case "TSAbstractMethodDefinition": - if (n.accessibility) { - parts.push(n.accessibility + " "); - } - - if (n.static) { - parts.push("static "); - } - - if (n.type === "TSAbstractMethodDefinition") { - parts.push("abstract "); - } - - parts.push(printMethod(path, options, print)); - return concat$4(parts); - - case "YieldExpression": - parts.push("yield"); - - if (n.delegate) { - parts.push("*"); - } - - if (n.argument) { - parts.push(" ", path.call(print, "argument")); - } - - return concat$4(parts); - - case "AwaitExpression": - return concat$4(["await ", path.call(print, "argument")]); - - case "ImportSpecifier": - if (n.importKind) { - parts.push(path.call(print, "importKind"), " "); - } - - parts.push(path.call(print, "imported")); - - if (n.local && n.local.name !== n.imported.name) { - parts.push(" as ", path.call(print, "local")); - } - - return concat$4(parts); - - case "ExportSpecifier": - parts.push(path.call(print, "local")); - - if (n.exported && n.exported.name !== n.local.name) { - parts.push(" as ", path.call(print, "exported")); - } - - return concat$4(parts); - - case "ImportNamespaceSpecifier": - parts.push("* as "); - - if (n.local) { - parts.push(path.call(print, "local")); - } else if (n.id) { - parts.push(path.call(print, "id")); - } - - return concat$4(parts); - - case "ImportDefaultSpecifier": - if (n.local) { - return path.call(print, "local"); - } - - return path.call(print, "id"); - - case "TSExportAssignment": - return concat$4(["export = ", path.call(print, "expression"), semi]); - - case "ExportDefaultDeclaration": - case "ExportNamedDeclaration": - return printExportDeclaration(path, options, print); - - case "ExportAllDeclaration": - parts.push("export "); - - if (n.exportKind === "type") { - parts.push("type "); - } - - parts.push("* from ", path.call(print, "source"), semi); - return concat$4(parts); - - case "ExportNamespaceSpecifier": - case "ExportDefaultSpecifier": - return path.call(print, "exported"); - - case "ImportDeclaration": - { - parts.push("import "); - - if (n.importKind && n.importKind !== "value") { - parts.push(n.importKind + " "); - } - - var standalones = []; - var grouped = []; - - if (n.specifiers && n.specifiers.length > 0) { - path.each(function (specifierPath) { - var value = specifierPath.getValue(); - - if (value.type === "ImportDefaultSpecifier" || value.type === "ImportNamespaceSpecifier") { - standalones.push(print(specifierPath)); - } else { - grouped.push(print(specifierPath)); - } - }, "specifiers"); - - if (standalones.length > 0) { - parts.push(join$2(", ", standalones)); - } - - if (standalones.length > 0 && grouped.length > 0) { - parts.push(", "); - } - - if (grouped.length === 1 && standalones.length === 0 && n.specifiers && !n.specifiers.some(function (node) { - return node.comments; - })) { - parts.push(concat$4(["{", options.bracketSpacing ? " " : "", concat$4(grouped), options.bracketSpacing ? " " : "", "}"])); - } else if (grouped.length >= 1) { - parts.push(group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, join$2(concat$4([",", line$3]), grouped)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$3 : softline$1, "}"]))); - } - - parts.push(" from "); - } else if (n.importKind && n.importKind === "type" || // import {} from 'x' - /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) { - parts.push("{} from "); - } - - parts.push(path.call(print, "source"), semi); - return concat$4(parts); - } - - case "Import": - return "import"; - - case "BlockStatement": - { - var naked = path.call(function (bodyPath) { - return printStatementSequence(bodyPath, options, print); - }, "body"); - var hasContent = n.body.find(function (node) { - return node.type !== "EmptyStatement"; - }); - var hasDirectives = n.directives && n.directives.length > 0; - - var _parent2 = path.getParentNode(); - - var _parentParent = path.getParentNode(1); - - if (!hasContent && !hasDirectives && !hasDanglingComments(n) && (_parent2.type === "ArrowFunctionExpression" || _parent2.type === "FunctionExpression" || _parent2.type === "FunctionDeclaration" || _parent2.type === "ObjectMethod" || _parent2.type === "ClassMethod" || _parent2.type === "ForStatement" || _parent2.type === "WhileStatement" || _parent2.type === "DoWhileStatement" || _parent2.type === "DoExpression" || _parent2.type === "CatchClause" && !_parentParent.finalizer)) { - return "{}"; - } - - parts.push("{"); // Babel 6 - - if (hasDirectives) { - path.each(function (childPath) { - parts.push(indent$2(concat$4([hardline$3, print(childPath), semi]))); - - if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) { - parts.push(hardline$3); - } - }, "directives"); - } - - if (hasContent) { - parts.push(indent$2(concat$4([hardline$3, naked]))); - } - - parts.push(comments.printDanglingComments(path, options)); - parts.push(hardline$3, "}"); - return concat$4(parts); - } - - case "ReturnStatement": - parts.push("return"); - - if (n.argument) { - if (returnArgumentHasLeadingComment(options, n.argument)) { - parts.push(concat$4([" (", indent$2(concat$4([hardline$3, path.call(print, "argument")])), hardline$3, ")"])); - } else if (n.argument.type === "LogicalExpression" || n.argument.type === "BinaryExpression" || n.argument.type === "SequenceExpression") { - parts.push(group$1(concat$4([ifBreak$1(" (", " "), indent$2(concat$4([softline$1, path.call(print, "argument")])), softline$1, ifBreak$1(")")]))); - } else { - parts.push(" ", path.call(print, "argument")); - } - } - - if (hasDanglingComments(n)) { - parts.push(" ", comments.printDanglingComments(path, options, - /* sameIndent */ - true)); - } - - parts.push(semi); - return concat$4(parts); - - case "NewExpression": - case "OptionalCallExpression": - case "CallExpression": - { - var isNew = n.type === "NewExpression"; - var optional = printOptionalToken(path); - - if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style - // define calls, as a unit. - // e.g. `define(["some/lib", (lib) => {` - !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || n.callee.type === "Import" || // Template literals as single arguments - n.arguments.length === 1 && isTemplateOnItsOwnLine(n.arguments[0], options.originalText, options) || // Keep test declarations on a single line - // e.g. `it('long name', () => {` - !isNew && isTestCall(n, path.getParentNode())) { - return concat$4([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), concat$4(["(", join$2(", ", path.map(print, "arguments")), ")"])]); - } // We detect calls on member lookups and possibly print them in a - // special chain format. See `printMemberChain` for more info. - - - if (!isNew && isMemberish(n.callee)) { - return printMemberChain(path, options, print); - } - - return concat$4([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]); - } - - case "TSInterfaceDeclaration": - if (isNodeStartingWithDeclare(n, options)) { - parts.push("declare "); - } - - parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print), "interface ", path.call(print, "id"), n.typeParameters ? path.call(print, "typeParameters") : "", " "); - - if (n.heritage.length) { - parts.push(group$1(indent$2(concat$4([softline$1, "extends ", indent$2(join$2(concat$4([",", line$3]), path.map(print, "heritage"))), " "])))); - } - - parts.push(path.call(print, "body")); - return concat$4(parts); - - case "ObjectExpression": - case "ObjectPattern": - case "ObjectTypeAnnotation": - case "TSInterfaceBody": - case "TSTypeLiteral": - { - var isTypeAnnotation = n.type === "ObjectTypeAnnotation"; - - var _parent3 = path.getParentNode(0); - - var shouldBreak = n.type === "TSInterfaceBody" || n.type === "ObjectPattern" && _parent3.type !== "FunctionDeclaration" && _parent3.type !== "FunctionExpression" && _parent3.type !== "ArrowFunctionExpression" && _parent3.type !== "AssignmentPattern" && _parent3.type !== "CatchClause" && n.properties.some(function (property) { - return property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern"); - }) || n.type !== "ObjectPattern" && hasNewlineInRange$1(options.originalText, options.locStart(n), options.locEnd(n)); - var isFlowInterfaceLikeBody = isTypeAnnotation && _parent3 && (_parent3.type === "InterfaceDeclaration" || _parent3.type === "DeclareInterface" || _parent3.type === "DeclareClass") && path.getName() === "body"; - var separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$1(semi, ";") : ","; - var fields = []; - var leftBrace = n.exact ? "{|" : "{"; - var rightBrace = n.exact ? "|}" : "}"; - var propertiesField; - - if (n.type === "TSTypeLiteral") { - propertiesField = "members"; - } else if (n.type === "TSInterfaceBody") { - propertiesField = "body"; - } else { - propertiesField = "properties"; - } - - if (isTypeAnnotation) { - fields.push("indexers", "callProperties"); - } - - fields.push(propertiesField); // Unfortunately, things are grouped together in the ast can be - // interleaved in the source code. So we need to reorder them before - // printing them. - - var propsAndLoc = []; - fields.forEach(function (field) { - path.each(function (childPath) { - var node = childPath.getValue(); - propsAndLoc.push({ - node: node, - printed: print(childPath), - loc: options.locStart(node) - }); - }, field); - }); - var separatorParts = []; - var props = propsAndLoc.sort(function (a, b) { - return a.loc - b.loc; - }).map(function (prop) { - var result = concat$4(separatorParts.concat(group$1(prop.printed))); - separatorParts = [separator, line$3]; - - if (prop.node.type === "TSPropertySignature" && hasNodeIgnoreComment$1(prop.node)) { - separatorParts.shift(); - } - - if (isNextLineEmpty$2(options.originalText, prop.node, options)) { - separatorParts.push(hardline$3); - } - - return result; - }); - var lastElem = getLast$4(n[propertiesField]); - var canHaveTrailingSeparator = !(lastElem && (lastElem.type === "RestProperty" || lastElem.type === "RestElement" || hasNodeIgnoreComment$1(lastElem))); - var content; - - if (props.length === 0 && !n.typeAnnotation) { - if (!hasDanglingComments(n)) { - return concat$4([leftBrace, rightBrace]); - } - - content = group$1(concat$4([leftBrace, comments.printDanglingComments(path, options), softline$1, rightBrace, printOptionalToken(path)])); - } else { - content = concat$4([leftBrace, indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, concat$4(props)])), ifBreak$1(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma(options)) ? separator : ""), concat$4([options.bracketSpacing ? line$3 : softline$1, rightBrace]), printOptionalToken(path), printTypeAnnotation(path, options, print)]); - } // If we inline the object as first argument of the parent, we don't want - // to create another group so that the object breaks before the return - // type - - - var parentParentParent = path.getParentNode(2); - - if (n.type === "ObjectPattern" && _parent3 && shouldHugArguments(_parent3) && _parent3.params[0] === n || shouldHugType(n) && parentParentParent && shouldHugArguments(parentParentParent) && parentParentParent.params[0].typeAnnotation && parentParentParent.params[0].typeAnnotation.typeAnnotation === n) { - return content; - } - - return group$1(content, { - shouldBreak: shouldBreak - }); - } - // Babel 6 - - case "ObjectProperty": // Non-standard AST node type. - - case "Property": - if (n.method || n.kind === "get" || n.kind === "set") { - return printMethod(path, options, print); - } - - if (n.shorthand) { - parts.push(path.call(print, "value")); - } else { - var printedLeft; - - if (n.computed) { - printedLeft = concat$4(["[", path.call(print, "key"), "]"]); - } else { - printedLeft = printPropertyKey(path, options, print); - } - - parts.push(printAssignment(n.key, printedLeft, ":", n.value, path.call(print, "value"), options)); - } - - return concat$4(parts); - // Babel 6 - - case "ClassMethod": - if (n.static) { - parts.push("static "); - } - - parts = parts.concat(printObjectMethod(path, options, print)); - return concat$4(parts); - // Babel 6 - - case "ObjectMethod": - return printObjectMethod(path, options, print); - - case "Decorator": - return concat$4(["@", path.call(print, "expression"), path.call(print, "callee")]); - - case "ArrayExpression": - case "ArrayPattern": - if (n.elements.length === 0) { - if (!hasDanglingComments(n)) { - parts.push("[]"); - } else { - parts.push(group$1(concat$4(["[", comments.printDanglingComments(path, options), softline$1, "]"]))); - } - } else { - var _lastElem = getLast$4(n.elements); - - var canHaveTrailingComma = !(_lastElem && _lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which - // changes its length based on the number of commas. The algorithm - // is that if the last argument is null, we need to force insert - // a comma to ensure JavaScript recognizes it. - // [,].length === 1 - // [1,].length === 1 - // [1,,].length === 2 - // - // Note that getLast returns null if the array is empty, but - // we already check for an empty array just above so we are safe - - var needsForcedTrailingComma = canHaveTrailingComma && _lastElem === null; - parts.push(group$1(concat$4(["[", indent$2(concat$4([softline$1, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$1(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma(options) ? "," : ""), comments.printDanglingComments(path, options, - /* sameIndent */ - true), softline$1, "]"]))); - } - - parts.push(printOptionalToken(path), printTypeAnnotation(path, options, print)); - return concat$4(parts); - - case "SequenceExpression": - { - var _parent4 = path.getParentNode(0); - - if (_parent4.type === "ExpressionStatement" || _parent4.type === "ForStatement") { - // For ExpressionStatements and for-loop heads, which are among - // the few places a SequenceExpression appears unparenthesized, we want - // to indent expressions after the first. - var _parts2 = []; - path.each(function (p) { - if (p.getName() === 0) { - _parts2.push(print(p)); - } else { - _parts2.push(",", indent$2(concat$4([line$3, print(p)]))); - } - }, "expressions"); - return group$1(concat$4(_parts2)); - } - - return group$1(concat$4([join$2(concat$4([",", line$3]), path.map(print, "expressions"))])); - } - - case "ThisExpression": - return "this"; - - case "Super": - return "super"; - - case "NullLiteral": - // Babel 6 Literal split - return "null"; - - case "RegExpLiteral": - // Babel 6 Literal split - return printRegex(n); - - case "NumericLiteral": - // Babel 6 Literal split - return printNumber$1(n.extra.raw); - - case "BigIntLiteral": - return concat$4([printNumber$1(n.extra.rawValue), "n"]); - - case "BooleanLiteral": // Babel 6 Literal split - - case "StringLiteral": // Babel 6 Literal split - - case "Literal": - { - if (n.regex) { - return printRegex(n.regex); - } - - if (typeof n.value === "number") { - return printNumber$1(n.raw); - } - - if (typeof n.value !== "string") { - return "" + n.value; - } // TypeScript workaround for eslint/typescript-eslint-parser#267 - // See corresponding workaround in needs-parens.js - - - var grandParent = path.getParentNode(1); - var isTypeScriptDirective = options.parser === "typescript" && typeof n.value === "string" && grandParent && (grandParent.type === "Program" || grandParent.type === "BlockStatement"); - return nodeStr(n, options, isTypeScriptDirective); - } - - case "Directive": - return path.call(print, "value"); - // Babel 6 - - case "DirectiveLiteral": - return nodeStr(n, options); - - case "UnaryExpression": - parts.push(n.operator); - - if (/[a-z]$/.test(n.operator)) { - parts.push(" "); - } - - parts.push(path.call(print, "argument")); - return concat$4(parts); - - case "UpdateExpression": - parts.push(path.call(print, "argument"), n.operator); - - if (n.prefix) { - parts.reverse(); - } - - return concat$4(parts); - - case "ConditionalExpression": - return formatTernaryOperator(path, options, print, { - beforeParts: function beforeParts() { - return [path.call(print, "test")]; - }, - afterParts: function afterParts(breakClosingParen) { - return [breakClosingParen ? softline$1 : ""]; - } - }); - - case "VariableDeclaration": - { - var printed = path.map(function (childPath) { - return print(childPath); - }, "declarations"); // We generally want to terminate all variable declarations with a - // semicolon, except when they in the () part of for loops. - - var parentNode = path.getParentNode(); - var isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement" || parentNode.type === "ForAwaitStatement"; - var hasValue = n.declarations.some(function (decl) { - return decl.init; - }); - var firstVariable; - - if (printed.length === 1) { - firstVariable = printed[0]; - } else if (printed.length > 1) { - // Indent first var to comply with eslint one-var rule - firstVariable = indent$2(printed[0]); - } - - parts = [isNodeStartingWithDeclare(n, options) ? "declare " : "", n.kind, firstVariable ? concat$4([" ", firstVariable]) : "", indent$2(concat$4(printed.slice(1).map(function (p) { - return concat$4([",", hasValue && !isParentForLoop ? hardline$3 : line$3, p]); - })))]; - - if (!(isParentForLoop && parentNode.body !== n)) { - parts.push(semi); - } - - return group$1(concat$4(parts)); - } - - case "VariableDeclarator": - return printAssignment(n.id, concat$4([path.call(print, "id"), path.call(print, "typeParameters")]), " =", n.init, n.init && path.call(print, "init"), options); - - case "WithStatement": - return group$1(concat$4(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))])); - - case "IfStatement": - { - var con = adjustClause(n.consequent, path.call(print, "consequent")); - var opening = group$1(concat$4(["if (", group$1(concat$4([indent$2(concat$4([softline$1, path.call(print, "test")])), softline$1])), ")", con])); - parts.push(opening); - - if (n.alternate) { - var commentOnOwnLine = hasTrailingComment(n.consequent) && n.consequent.comments.some(function (comment) { - return comment.trailing && !comments$3.isBlockComment(comment); - }) || needsHardlineAfterDanglingComment(n); - var elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine; - parts.push(elseOnSameLine ? " " : hardline$3); - - if (hasDanglingComments(n)) { - parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$3 : " "); - } - - parts.push("else", group$1(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement"))); - } - - return concat$4(parts); - } - - case "ForStatement": - { - var _body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent. - // Any comment positioned between the for statement and the parentheses - // is going to be printed before the statement. - - - var _dangling = comments.printDanglingComments(path, options, - /* sameLine */ - true); - - var printedComments = _dangling ? concat$4([_dangling, softline$1]) : ""; - - if (!n.init && !n.test && !n.update) { - return concat$4([printedComments, group$1(concat$4(["for (;;)", _body]))]); - } - - return concat$4([printedComments, group$1(concat$4(["for (", group$1(concat$4([indent$2(concat$4([softline$1, path.call(print, "init"), ";", line$3, path.call(print, "test"), ";", line$3, path.call(print, "update")])), softline$1])), ")", _body]))]); - } - - case "WhileStatement": - return group$1(concat$4(["while (", group$1(concat$4([indent$2(concat$4([softline$1, path.call(print, "test")])), softline$1])), ")", adjustClause(n.body, path.call(print, "body"))])); - - case "ForInStatement": - // Note: esprima can't actually parse "for each (". - return group$1(concat$4([n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))])); - - case "ForOfStatement": - case "ForAwaitStatement": - { - // Babylon 7 removed ForAwaitStatement in favor of ForOfStatement - // with `"await": true`: - // https://github.com/estree/estree/pull/138 - var isAwait = n.type === "ForAwaitStatement" || n.await; - return group$1(concat$4(["for", isAwait ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))])); - } - - case "DoWhileStatement": - { - var clause = adjustClause(n.body, path.call(print, "body")); - var doBody = group$1(concat$4(["do", clause])); - parts = [doBody]; - - if (n.body.type === "BlockStatement") { - parts.push(" "); - } else { - parts.push(hardline$3); - } - - parts.push("while ("); - parts.push(group$1(concat$4([indent$2(concat$4([softline$1, path.call(print, "test")])), softline$1])), ")", semi); - return concat$4(parts); - } - - case "DoExpression": - return concat$4(["do ", path.call(print, "body")]); - - case "BreakStatement": - parts.push("break"); - - if (n.label) { - parts.push(" ", path.call(print, "label")); - } - - parts.push(semi); - return concat$4(parts); - - case "ContinueStatement": - parts.push("continue"); - - if (n.label) { - parts.push(" ", path.call(print, "label")); - } - - parts.push(semi); - return concat$4(parts); - - case "LabeledStatement": - if (n.body.type === "EmptyStatement") { - return concat$4([path.call(print, "label"), ":;"]); - } - - return concat$4([path.call(print, "label"), ": ", path.call(print, "body")]); - - case "TryStatement": - return concat$4(["try ", path.call(print, "block"), n.handler ? concat$4([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$4([" finally ", path.call(print, "finalizer")]) : ""]); - - case "CatchClause": - return concat$4(["catch ", n.param ? concat$4(["(", path.call(print, "param"), ") "]) : "", path.call(print, "body")]); - - case "ThrowStatement": - return concat$4(["throw ", path.call(print, "argument"), semi]); - // Note: ignoring n.lexical because it has no printing consequences. - - case "SwitchStatement": - return concat$4([group$1(concat$4(["switch (", indent$2(concat$4([softline$1, path.call(print, "discriminant")])), softline$1, ")"])), " {", n.cases.length > 0 ? indent$2(concat$4([hardline$3, join$2(hardline$3, path.map(function (casePath) { - var caseNode = casePath.getValue(); - return concat$4([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$2(options.originalText, caseNode, options) ? hardline$3 : ""]); - }, "cases"))])) : "", hardline$3, "}"]); - - case "SwitchCase": - { - if (n.test) { - parts.push("case ", path.call(print, "test"), ":"); - } else { - parts.push("default:"); - } - - var consequent = n.consequent.filter(function (node) { - return node.type !== "EmptyStatement"; - }); - - if (consequent.length > 0) { - var cons = path.call(function (consequentPath) { - return printStatementSequence(consequentPath, options, print); - }, "consequent"); - parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$4([" ", cons]) : indent$2(concat$4([hardline$3, cons]))); - } - - return concat$4(parts); - } - // JSX extensions below. - - case "DebuggerStatement": - return concat$4(["debugger", semi]); - - case "JSXAttribute": - parts.push(path.call(print, "name")); - - if (n.value) { - var res; - - if (isStringLiteral(n.value)) { - var value = rawText(n.value); - res = '"' + value.slice(1, -1).replace(/"/g, """) + '"'; - } else { - res = path.call(print, "value"); - } - - parts.push("=", res); - } - - return concat$4(parts); - - case "JSXIdentifier": - // Can be removed when this is fixed: - // https://github.com/eslint/typescript-eslint-parser/issues/337 - if (!n.name) { - return "this"; - } - - return "" + n.name; - - case "JSXNamespacedName": - return join$2(":", [path.call(print, "namespace"), path.call(print, "name")]); - - case "JSXMemberExpression": - return join$2(".", [path.call(print, "object"), path.call(print, "property")]); - - case "TSQualifiedName": - return join$2(".", [path.call(print, "left"), path.call(print, "right")]); - - case "JSXSpreadAttribute": - case "JSXSpreadChild": - { - return concat$4(["{", path.call(function (p) { - var printed = concat$4(["...", print(p)]); - var n = p.getValue(); - - if (!n.comments || !n.comments.length) { - return printed; - } - - return concat$4([indent$2(concat$4([softline$1, comments.printComments(p, function () { - return printed; - }, options)])), softline$1]); - }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]); - } - - case "JSXExpressionContainer": - { - var _parent5 = path.getParentNode(0); - - var preventInline = _parent5.type === "JSXAttribute" && n.expression.comments && n.expression.comments.length > 0; - - var _shouldInline = !preventInline && (n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression" || n.expression.type === "ArrowFunctionExpression" || n.expression.type === "CallExpression" || n.expression.type === "OptionalCallExpression" || n.expression.type === "FunctionExpression" || n.expression.type === "JSXEmptyExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode(_parent5) && (n.expression.type === "ConditionalExpression" || isBinaryish(n.expression))); - - if (_shouldInline) { - return group$1(concat$4(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"])); - } - - return group$1(concat$4(["{", indent$2(concat$4([softline$1, path.call(print, "expression")])), softline$1, lineSuffixBoundary$1, "}"])); - } - - case "JSXFragment": - case "TSJsxFragment": - case "JSXElement": - { - var elem = comments.printComments(path, function () { - return printJSXElement(path, options, print); - }, options); - return maybeWrapJSXElementInParens(path, elem); - } - - case "JSXOpeningElement": - { - var _n = path.getValue(); - - var nameHasComments = _n.name && _n.name.comments && _n.name.comments.length > 0; // Don't break self-closing elements with no attributes and no comments - - if (_n.selfClosing && !_n.attributes.length && !nameHasComments) { - return concat$4(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]); - } // don't break up opening elements with a single long text attribute - - - if (_n.attributes && _n.attributes.length === 1 && _n.attributes[0].value && isStringLiteral(_n.attributes[0].value) && !_n.attributes[0].value.value.includes("\n") && // We should break for the following cases: - // <div - // // comment - // attr="value" - // > - // <div - // attr="value" - // // comment - // > - !nameHasComments && (!_n.attributes[0].comments || !_n.attributes[0].comments.length)) { - return group$1(concat$4(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$4(path.map(print, "attributes")), _n.selfClosing ? " />" : ">"])); - } - - var lastAttrHasTrailingComments = _n.attributes.length && hasTrailingComment(getLast$4(_n.attributes)); - var bracketSameLine = options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases: - // <div - // // comment - // > - // <div - // attr // comment - // > - !nameHasComments || _n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a - // string literal with newlines - - var _shouldBreak = _n.attributes && _n.attributes.some(function (attr) { - return attr.value && isStringLiteral(attr.value) && attr.value.value.includes("\n"); - }); - - return group$1(concat$4(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$4([indent$2(concat$4(path.map(function (attr) { - return concat$4([line$3, print(attr)]); - }, "attributes"))), _n.selfClosing ? line$3 : bracketSameLine ? ">" : softline$1]), _n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), { - shouldBreak: _shouldBreak - }); - } - - case "JSXClosingElement": - return concat$4(["</", path.call(print, "name"), ">"]); - - case "JSXOpeningFragment": - case "JSXClosingFragment": - case "TSJsxOpeningFragment": - case "TSJsxClosingFragment": - { - var hasComment = n.comments && n.comments.length; - var hasOwnLineComment = hasComment && !n.comments.every(comments$3.isBlockComment); - var isOpeningFragment = n.type === "JSXOpeningFragment" || n.type === "TSJsxOpeningFragment"; - return concat$4([isOpeningFragment ? "<" : "</", indent$2(concat$4([hasOwnLineComment ? hardline$3 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$3 : "", ">"]); - } - - case "JSXText": - /* istanbul ignore next */ - throw new Error("JSXTest should be handled by JSXElement"); - - case "JSXEmptyExpression": - { - var requiresHardline = n.comments && !n.comments.every(comments$3.isBlockComment); - return concat$4([comments.printDanglingComments(path, options, - /* sameIndent */ - !requiresHardline), requiresHardline ? hardline$3 : ""]); - } - - case "ClassBody": - if (!n.comments && n.body.length === 0) { - return "{}"; - } - - return concat$4(["{", n.body.length > 0 ? indent$2(concat$4([hardline$3, path.call(function (bodyPath) { - return printStatementSequence(bodyPath, options, print); - }, "body")])) : comments.printDanglingComments(path, options), hardline$3, "}"]); - - case "ClassProperty": - case "TSAbstractClassProperty": - case "ClassPrivateProperty": - { - if (n.accessibility) { - parts.push(n.accessibility + " "); - } - - if (n.static) { - parts.push("static "); - } - - if (n.type === "TSAbstractClassProperty") { - parts.push("abstract "); - } - - if (n.readonly) { - parts.push("readonly "); - } - - var variance = getFlowVariance(n); - - if (variance) { - parts.push(variance); - } - - if (n.computed) { - parts.push("[", path.call(print, "key"), "]"); - } else { - parts.push(printPropertyKey(path, options, print)); - } - - parts.push(printOptionalToken(path)); - parts.push(printTypeAnnotation(path, options, print)); - - if (n.value) { - parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options)); - } - - parts.push(semi); - return group$1(concat$4(parts)); - } - - case "ClassDeclaration": - case "ClassExpression": - case "TSAbstractClassDeclaration": - if (isNodeStartingWithDeclare(n, options)) { - parts.push("declare "); - } - - parts.push(concat$4(printClass(path, options, print))); - return concat$4(parts); - - case "TSInterfaceHeritage": - parts.push(path.call(print, "id")); - - if (n.typeParameters) { - parts.push(path.call(print, "typeParameters")); - } - - return concat$4(parts); - - case "TemplateElement": - return join$2(literalline$1, n.value.raw.split(/\r?\n/g)); - - case "TemplateLiteral": - { - var expressions = path.map(print, "expressions"); - - var _parentNode = path.getParentNode(); - /** - * describe.each`table`(name, fn) - * describe.only.each`table`(name, fn) - * describe.skip.each`table`(name, fn) - * test.each`table`(name, fn) - * test.only.each`table`(name, fn) - * test.skip.each`table`(name, fn) - * - * Ref: https://github.com/facebook/jest/pull/6102 - */ - - - var jestEachTriggerRegex = /^[xf]?(describe|it|test)$/; - - if (_parentNode.type === "TaggedTemplateExpression" && _parentNode.quasi === n && _parentNode.tag.type === "MemberExpression" && _parentNode.tag.property.type === "Identifier" && _parentNode.tag.property.name === "each" && (_parentNode.tag.object.type === "Identifier" && jestEachTriggerRegex.test(_parentNode.tag.object.name) || _parentNode.tag.object.type === "MemberExpression" && _parentNode.tag.object.property.type === "Identifier" && (_parentNode.tag.object.property.name === "only" || _parentNode.tag.object.property.name === "skip") && _parentNode.tag.object.object.type === "Identifier" && jestEachTriggerRegex.test(_parentNode.tag.object.object.name))) { - /** - * a | b | expected - * ${1} | ${1} | ${2} - * ${1} | ${2} | ${3} - * ${2} | ${1} | ${3} - */ - var headerNames = n.quasis[0].value.raw.trim().split(/\s*\|\s*/); - - if (headerNames.length > 1 || headerNames.some(function (headerName) { - return headerName.length !== 0; - })) { - var stringifiedExpressions = expressions.map(function (doc$$2) { - return "${" + printDocToString$1(doc$$2, Object.assign({}, options, { - printWidth: Infinity - })).formatted + "}"; - }); - var tableBody = [{ - hasLineBreak: false, - cells: [] - }]; - - for (var _i = 1; _i < n.quasis.length; _i++) { - var row = tableBody[tableBody.length - 1]; - var correspondingExpression = stringifiedExpressions[_i - 1]; - row.cells.push(correspondingExpression); - - if (correspondingExpression.indexOf("\n") !== -1) { - row.hasLineBreak = true; - } - - if (n.quasis[_i].value.raw.indexOf("\n") !== -1) { - tableBody.push({ - hasLineBreak: false, - cells: [] - }); - } - } - - var maxColumnCount = tableBody.reduce(function (maxColumnCount, row) { - return Math.max(maxColumnCount, row.cells.length); - }, headerNames.length); - var maxColumnWidths = Array.from(new Array(maxColumnCount), function () { - return 0; - }); - var table = [{ - cells: headerNames - }].concat(tableBody.filter(function (row) { - return row.cells.length !== 0; - })); - table.filter(function (row) { - return !row.hasLineBreak; - }).forEach(function (row) { - row.cells.forEach(function (cell, index) { - maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$2(cell)); - }); - }); - parts.push("`", indent$2(concat$4([hardline$3, join$2(hardline$3, table.map(function (row) { - return join$2(" | ", row.cells.map(function (cell, index) { - return row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$2(cell)); - })); - }))])), hardline$3, "`"); - return concat$4(parts); - } - } - - parts.push("`"); - path.each(function (childPath) { - var i = childPath.getName(); - parts.push(print(childPath)); - - if (i < expressions.length) { - // For a template literal of the following form: - // `someQuery { - // ${call({ - // a, - // b, - // })} - // }` - // the expression is on its own line (there is a \n in the previous - // quasi literal), therefore we want to indent the JavaScript - // expression inside at the beginning of ${ instead of the beginning - // of the `. - var tabWidth = options.tabWidth; - var indentSize = getIndentSize$1(childPath.getValue().value.raw, tabWidth); - var _printed = expressions[i]; - - if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression") { - _printed = concat$4([indent$2(concat$4([softline$1, _printed])), softline$1]); - } - - var aligned = addAlignmentToDoc$2(_printed, indentSize, tabWidth); - parts.push(group$1(concat$4(["${", aligned, lineSuffixBoundary$1, "}"]))); - } - }, "quasis"); - parts.push("`"); - return concat$4(parts); - } - // These types are unprintable because they serve as abstract - // supertypes for other (printable) types. - - case "TaggedTemplateExpression": - return concat$4([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]); - - case "Node": - case "Printable": - case "SourceLocation": - case "Position": - case "Statement": - case "Function": - case "Pattern": - case "Expression": - case "Declaration": - case "Specifier": - case "NamedSpecifier": - case "Comment": - case "MemberTypeAnnotation": // Flow - - case "Type": - /* istanbul ignore next */ - throw new Error("unprintable type: " + JSON.stringify(n.type)); - // Type Annotations for Facebook Flow, typically stripped out or - // transformed away before printing. - - case "TypeAnnotation": - case "TSTypeAnnotation": - if (n.typeAnnotation) { - return path.call(print, "typeAnnotation"); - } - /* istanbul ignore next */ - - - return ""; - - case "TSTupleType": - case "TupleTypeAnnotation": - { - var typesField = n.type === "TSTupleType" ? "elementTypes" : "types"; - return group$1(concat$4(["[", indent$2(concat$4([softline$1, printArrayItems(path, options, typesField, print)])), // TypeScript doesn't support trailing commas in tuple types - n.type === "TSTupleType" ? "" : ifBreak$1(shouldPrintComma(options) ? "," : ""), comments.printDanglingComments(path, options, - /* sameIndent */ - true), softline$1, "]"])); - } - - case "ExistsTypeAnnotation": - return "*"; - - case "EmptyTypeAnnotation": - return "empty"; - - case "AnyTypeAnnotation": - return "any"; - - case "MixedTypeAnnotation": - return "mixed"; - - case "ArrayTypeAnnotation": - return concat$4([path.call(print, "elementType"), "[]"]); - - case "BooleanTypeAnnotation": - return "boolean"; - - case "BooleanLiteralTypeAnnotation": - return "" + n.value; - - case "DeclareClass": - return printFlowDeclaration(path, printClass(path, options, print)); - - case "DeclareFunction": - // For TypeScript the DeclareFunction node shares the AST - // structure with FunctionDeclaration - if (n.params) { - return concat$4(["declare ", printFunctionDeclaration(path, print, options), semi]); - } - - return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]); - - case "DeclareModule": - return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]); - - case "DeclareModuleExports": - return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]); - - case "DeclareVariable": - return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]); - - case "DeclareExportAllDeclaration": - return concat$4(["declare export * from ", path.call(print, "source")]); - - case "DeclareExportDeclaration": - return concat$4(["declare ", printExportDeclaration(path, options, print)]); - - case "DeclareOpaqueType": - case "OpaqueType": - { - parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters")); - - if (n.supertype) { - parts.push(": ", path.call(print, "supertype")); - } - - if (n.impltype) { - parts.push(" = ", path.call(print, "impltype")); - } - - parts.push(semi); - - if (n.type === "DeclareOpaqueType") { - return printFlowDeclaration(path, parts); - } - - return concat$4(parts); - } - - case "FunctionTypeAnnotation": - case "TSFunctionType": - { - // FunctionTypeAnnotation is ambiguous: - // declare function foo(a: B): void; OR - // var A: (a: B) => void; - var _parent6 = path.getParentNode(0); - - var _parentParent2 = path.getParentNode(1); - - var _parentParentParent = path.getParentNode(2); - - var isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !(_parent6.type === "ObjectTypeProperty" && !getFlowVariance(_parent6) && !_parent6.optional && options.locStart(_parent6) === options.locStart(n) || _parent6.type === "ObjectTypeCallProperty" || _parentParentParent && _parentParentParent.type === "DeclareFunction"); - var needsColon = isArrowFunctionTypeAnnotation && (_parent6.type === "TypeAnnotation" || _parent6.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are - // printing ":" as part of the expression and it would put parenthesis - // around :( - - var needsParens = needsColon && isArrowFunctionTypeAnnotation && (_parent6.type === "TypeAnnotation" || _parent6.type === "TSTypeAnnotation") && _parentParent2.type === "ArrowFunctionExpression"; - - if (isObjectTypePropertyAFunction(_parent6, options)) { - isArrowFunctionTypeAnnotation = true; - needsColon = true; - } - - if (needsParens) { - parts.push("("); - } - - parts.push(printFunctionParams(path, print, options, - /* expandArg */ - false, - /* printTypeParams */ - true)); // The returnType is not wrapped in a TypeAnnotation, so the colon - // needs to be added separately. - - if (n.returnType || n.predicate || n.typeAnnotation) { - parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation")); - } - - if (needsParens) { - parts.push(")"); - } - - return group$1(concat$4(parts)); - } - - case "TSRestType": - return concat$4(["...", path.call(print, "typeAnnotation")]); - - case "TSOptionalType": - return concat$4([path.call(print, "typeAnnotation"), "?"]); - - case "FunctionTypeParam": - return concat$4([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]); - - case "GenericTypeAnnotation": - return concat$4([path.call(print, "id"), path.call(print, "typeParameters")]); - - case "DeclareInterface": - case "InterfaceDeclaration": - case "InterfaceTypeAnnotation": - { - if (n.type === "DeclareInterface" || isNodeStartingWithDeclare(n, options)) { - parts.push("declare "); - } - - parts.push("interface"); - - if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") { - parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters")); - } - - if (n["extends"].length > 0) { - parts.push(group$1(indent$2(concat$4([line$3, "extends ", join$2(", ", path.map(print, "extends"))])))); - } - - parts.push(" ", path.call(print, "body")); - return group$1(concat$4(parts)); - } - - case "ClassImplements": - case "InterfaceExtends": - return concat$4([path.call(print, "id"), path.call(print, "typeParameters")]); - - case "TSIntersectionType": - case "IntersectionTypeAnnotation": - { - var types = path.map(print, "types"); - var result = []; - var wasIndented = false; - - for (var _i2 = 0; _i2 < types.length; ++_i2) { - if (_i2 === 0) { - result.push(types[_i2]); - } else if (isObjectType(n.types[_i2 - 1]) && isObjectType(n.types[_i2])) { - // If both are objects, don't indent - result.push(concat$4([" & ", wasIndented ? indent$2(types[_i2]) : types[_i2]])); - } else if (!isObjectType(n.types[_i2 - 1]) && !isObjectType(n.types[_i2])) { - // If no object is involved, go to the next line if it breaks - result.push(indent$2(concat$4([" &", line$3, types[_i2]]))); - } else { - // If you go from object to non-object or vis-versa, then inline it - if (_i2 > 1) { - wasIndented = true; - } - - result.push(" & ", _i2 > 1 ? indent$2(types[_i2]) : types[_i2]); - } - } - - return group$1(concat$4(result)); - } - - case "TSUnionType": - case "UnionTypeAnnotation": - { - // single-line variation - // A | B | C - // multi-line variation - // | A - // | B - // | C - var _parent7 = path.getParentNode(); - - var _parentParent3 = path.getParentNode(1); // If there's a leading comment, the parent is doing the indentation - - - var shouldIndent = _parent7.type !== "TypeParameterInstantiation" && _parent7.type !== "TSTypeParameterInstantiation" && _parent7.type !== "GenericTypeAnnotation" && _parent7.type !== "TSTypeReference" && !(_parent7.type === "FunctionTypeParam" && !_parent7.name) && _parentParent3.type !== "TSTypeAssertionExpression" && !((_parent7.type === "TypeAlias" || _parent7.type === "VariableDeclarator") && hasLeadingOwnLineComment(options.originalText, n, options)); // { - // a: string - // } | null | void - // should be inlined and not be printed in the multi-line variant - - var shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like - // | child1 - // // comment - // | child2 - - var _printed2 = path.map(function (typePath) { - var printedType = typePath.call(print); - - if (!shouldHug) { - printedType = align$1(2, printedType); - } - - return comments.printComments(typePath, function () { - return printedType; - }, options); - }, "types"); - - if (shouldHug) { - return join$2(" | ", _printed2); - } - - var code = concat$4([ifBreak$1(concat$4([shouldIndent ? line$3 : "", "| "])), join$2(concat$4([line$3, "| "]), _printed2)]); - var hasParens; - - if (n.type === "TSUnionType") { - var greatGrandParent = path.getParentNode(2); - var greatGreatGrandParent = path.getParentNode(3); - hasParens = greatGrandParent && greatGrandParent.type === "TSParenthesizedType" && greatGreatGrandParent && (greatGreatGrandParent.type === "TSUnionType" || greatGreatGrandParent.type === "TSIntersectionType"); - } else { - hasParens = needsParens_1(path, options); - } - - if (hasParens) { - return group$1(concat$4([indent$2(code), softline$1])); - } - - return group$1(shouldIndent ? indent$2(code) : code); - } - - case "NullableTypeAnnotation": - return concat$4(["?", path.call(print, "typeAnnotation")]); - - case "TSNullKeyword": - case "NullLiteralTypeAnnotation": - return "null"; - - case "ThisTypeAnnotation": - return "this"; - - case "NumberTypeAnnotation": - return "number"; - - case "ObjectTypeCallProperty": - if (n.static) { - parts.push("static "); - } - - parts.push(path.call(print, "value")); - return concat$4(parts); - - case "ObjectTypeIndexer": - { - var _variance = getFlowVariance(n); - - return concat$4([_variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]); - } - - case "ObjectTypeProperty": - { - var _variance2 = getFlowVariance(n); - - var modifier = ""; - - if (n.proto) { - modifier = "proto "; - } else if (n.static) { - modifier = "static "; - } - - return concat$4([modifier, isGetterOrSetter(n) ? n.kind + " " : "", _variance2 || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation(n, options) ? "" : ": ", path.call(print, "value")]); - } - - case "QualifiedTypeIdentifier": - return concat$4([path.call(print, "qualification"), ".", path.call(print, "id")]); - - case "StringLiteralTypeAnnotation": - return nodeStr(n, options); - - case "NumberLiteralTypeAnnotation": - assert$3.strictEqual(_typeof(n.value), "number"); - - if (n.extra != null) { - return printNumber$1(n.extra.raw); - } - - return printNumber$1(n.raw); - - case "StringTypeAnnotation": - return "string"; - - case "DeclareTypeAlias": - case "TypeAlias": - { - if (n.type === "DeclareTypeAlias" || isNodeStartingWithDeclare(n, options)) { - parts.push("declare "); - } - - var _printed3 = printAssignmentRight(n.id, n.right, path.call(print, "right"), options); - - parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", _printed3, semi); - return group$1(concat$4(parts)); - } - - case "TypeCastExpression": - return concat$4(["(", path.call(print, "expression"), ": ", path.call(print, "typeAnnotation"), ")"]); - - case "TypeParameterDeclaration": - case "TypeParameterInstantiation": - case "TSTypeParameterDeclaration": - case "TSTypeParameterInstantiation": - return printTypeParameters(path, options, print, "params"); - - case "TSTypeParameter": - case "TypeParameter": - { - var _parent8 = path.getParentNode(); - - if (_parent8.type === "TSMappedType") { - parts.push("[", path.call(print, "name")); - - if (n.constraint) { - parts.push(" in ", path.call(print, "constraint")); - } - - parts.push("]"); - return concat$4(parts); - } - - var _variance3 = getFlowVariance(n); - - if (_variance3) { - parts.push(_variance3); - } - - parts.push(path.call(print, "name")); - - if (n.bound) { - parts.push(": "); - parts.push(path.call(print, "bound")); - } - - if (n.constraint) { - parts.push(" extends ", path.call(print, "constraint")); - } - - if (n["default"]) { - parts.push(" = ", path.call(print, "default")); - } - - return concat$4(parts); - } - - case "TypeofTypeAnnotation": - return concat$4(["typeof ", path.call(print, "argument")]); - - case "VoidTypeAnnotation": - return "void"; - - case "InferredPredicate": - return "%checks"; - // Unhandled types below. If encountered, nodes of these types should - // be either left alone or desugared into AST types that are fully - // supported by the pretty-printer. - - case "DeclaredPredicate": - return concat$4(["%checks(", path.call(print, "value"), ")"]); - - case "TSAbstractKeyword": - return "abstract"; - - case "TSAnyKeyword": - return "any"; - - case "TSAsyncKeyword": - return "async"; - - case "TSBooleanKeyword": - return "boolean"; - - case "TSConstKeyword": - return "const"; - - case "TSDeclareKeyword": - return "declare"; - - case "TSExportKeyword": - return "export"; - - case "TSNeverKeyword": - return "never"; - - case "TSNumberKeyword": - return "number"; - - case "TSObjectKeyword": - return "object"; - - case "TSProtectedKeyword": - return "protected"; - - case "TSPrivateKeyword": - return "private"; - - case "TSPublicKeyword": - return "public"; - - case "TSReadonlyKeyword": - return "readonly"; - - case "TSSymbolKeyword": - return "symbol"; - - case "TSStaticKeyword": - return "static"; - - case "TSStringKeyword": - return "string"; - - case "TSUndefinedKeyword": - return "undefined"; - - case "TSUnknownKeyword": - return "unknown"; - - case "TSVoidKeyword": - return "void"; - - case "TSAsExpression": - return concat$4([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]); - - case "TSArrayType": - return concat$4([path.call(print, "elementType"), "[]"]); - - case "TSPropertySignature": - { - if (n.export) { - parts.push("export "); - } - - if (n.accessibility) { - parts.push(n.accessibility + " "); - } - - if (n.static) { - parts.push("static "); - } - - if (n.readonly) { - parts.push("readonly "); - } - - if (n.computed) { - parts.push("["); - } - - parts.push(printPropertyKey(path, options, print)); - - if (n.computed) { - parts.push("]"); - } - - parts.push(printOptionalToken(path)); - - if (n.typeAnnotation) { - parts.push(": "); - parts.push(path.call(print, "typeAnnotation")); - } // This isn't valid semantically, but it's in the AST so we can print it. - - - if (n.initializer) { - parts.push(" = ", path.call(print, "initializer")); - } - - return concat$4(parts); - } - - case "TSParameterProperty": - if (n.accessibility) { - parts.push(n.accessibility + " "); - } - - if (n.export) { - parts.push("export "); - } - - if (n.static) { - parts.push("static "); - } - - if (n.readonly) { - parts.push("readonly "); - } - - parts.push(path.call(print, "parameter")); - return concat$4(parts); - - case "TSTypeReference": - return concat$4([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]); - - case "TSTypeQuery": - return concat$4(["typeof ", path.call(print, "exprName")]); - - case "TSParenthesizedType": - { - return path.call(print, "typeAnnotation"); - } - - case "TSIndexSignature": - { - var _parent9 = path.getParentNode(); - - return concat$4([n.export ? "export " : "", n.accessibility ? concat$4([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", path.call(print, "index"), "]: ", path.call(print, "typeAnnotation"), _parent9.type === "ClassBody" ? semi : ""]); - } - - case "TSTypePredicate": - return concat$4([path.call(print, "parameterName"), " is ", path.call(print, "typeAnnotation")]); - - case "TSNonNullExpression": - return concat$4([path.call(print, "expression"), "!"]); - - case "TSThisType": - return "this"; - - case "TSLastTypeNode": - // TSImportType - return concat$4([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, "argument"), ")", !n.qualifier ? "" : concat$4([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]); - - case "TSLiteralType": - return path.call(print, "literal"); - - case "TSIndexedAccessType": - return concat$4([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]); - - case "TSConstructSignature": - case "TSConstructorType": - case "TSCallSignature": - { - if (n.type !== "TSCallSignature") { - parts.push("new "); - } - - parts.push(group$1(printFunctionParams(path, print, options, - /* expandArg */ - false, - /* printTypeParams */ - true))); - - if (n.typeAnnotation) { - var isType = n.type === "TSConstructorType"; - parts.push(isType ? " => " : ": ", path.call(print, "typeAnnotation")); - } - - return concat$4(parts); - } - - case "TSTypeOperator": - return concat$4([n.operator, " ", path.call(print, "typeAnnotation")]); - - case "TSMappedType": - return group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, n.readonlyToken ? concat$4([getTypeScriptMappedTypeModifier(n.readonlyToken, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.questionToken ? getTypeScriptMappedTypeModifier(n.questionToken, "?") : "", ": ", path.call(print, "typeAnnotation")])), comments.printDanglingComments(path, options, - /* sameIndent */ - true), options.bracketSpacing ? line$3 : softline$1, "}"])); - - case "TSMethodSignature": - parts.push(n.accessibility ? concat$4([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken(path), printFunctionParams(path, print, options, - /* expandArg */ - false, - /* printTypeParams */ - true)); - - if (n.typeAnnotation) { - parts.push(": ", path.call(print, "typeAnnotation")); - } - - return group$1(concat$4(parts)); - - case "TSNamespaceExportDeclaration": - parts.push("export as namespace ", path.call(print, "name")); - - if (options.semi) { - parts.push(";"); - } - - return group$1(concat$4(parts)); - - case "TSEnumDeclaration": - if (isNodeStartingWithDeclare(n, options)) { - parts.push("declare "); - } - - if (n.modifiers) { - parts.push(printTypeScriptModifiers(path, options, print)); - } - - if (n.const) { - parts.push("const "); - } - - parts.push("enum ", path.call(print, "id"), " "); - - if (n.members.length === 0) { - parts.push(group$1(concat$4(["{", comments.printDanglingComments(path, options), softline$1, "}"]))); - } else { - parts.push(group$1(concat$4(["{", indent$2(concat$4([hardline$3, printArrayItems(path, options, "members", print), shouldPrintComma(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options, - /* sameIndent */ - true), hardline$3, "}"]))); - } - - return concat$4(parts); - - case "TSEnumMember": - parts.push(path.call(print, "id")); - - if (n.initializer) { - parts.push(" = ", path.call(print, "initializer")); - } - - return concat$4(parts); - - case "TSImportEqualsDeclaration": - parts.push(printTypeScriptModifiers(path, options, print), "import ", path.call(print, "name"), " = ", path.call(print, "moduleReference")); - - if (options.semi) { - parts.push(";"); - } - - return group$1(concat$4(parts)); - - case "TSExternalModuleReference": - return concat$4(["require(", path.call(print, "expression"), ")"]); - - case "TSModuleDeclaration": - { - var _parent10 = path.getParentNode(); - - var isExternalModule = isLiteral(n.id); - var parentIsDeclaration = _parent10.type === "TSModuleDeclaration"; - var bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration"; - - if (parentIsDeclaration) { - parts.push("."); - } else { - if (n.declare === true) { - parts.push("declare "); - } - - parts.push(printTypeScriptModifiers(path, options, print)); // Global declaration looks like this: - // (declare)? global { ... } - - var isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(options.originalText.slice(options.locStart(n), options.locStart(n.id))); - - if (!isGlobalDeclaration) { - parts.push(isExternalModule ? "module " : "namespace "); - } - } - - parts.push(path.call(print, "id")); - - if (bodyIsDeclaration) { - parts.push(path.call(print, "body")); - } else if (n.body) { - parts.push(" {", indent$2(concat$4([line$3, path.call(function (bodyPath) { - return comments.printDanglingComments(bodyPath, options, true); - }, "body"), group$1(path.call(print, "body"))])), line$3, "}"); - } else { - parts.push(semi); - } - - return concat$4(parts); - } - - case "TSModuleBlock": - return path.call(function (bodyPath) { - return printStatementSequence(bodyPath, options, print); - }, "body"); - - case "PrivateName": - return concat$4(["#", path.call(print, "id")]); - - case "TSConditionalType": - return formatTernaryOperator(path, options, print, { - beforeParts: function beforeParts() { - return [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")]; - }, - shouldCheckJsx: false, - operatorName: "TSConditionalType", - consequentNode: "trueType", - alternateNode: "falseType", - testNode: "checkType", - breakNested: false - }); - - case "TSInferType": - return concat$4(["infer", " ", path.call(print, "typeParameter")]); - - case "InterpreterDirective": - parts.push("#!", n.value, hardline$3); - - if (isNextLineEmpty$2(options.originalText, n, options)) { - parts.push(hardline$3); - } - - return concat$4(parts); - - default: - /* istanbul ignore next */ - throw new Error("unknown type: " + JSON.stringify(n.type)); - } -} - -function printStatementSequence(path, options, print) { - var printed = []; - var bodyNode = path.getNode(); - var isClass = bodyNode.type === "ClassBody"; - path.map(function (stmtPath, i) { - var stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy - // "statements," it's safer simply to skip them. - - /* istanbul ignore if */ - - if (!stmt) { - return; - } // Skip printing EmptyStatement nodes to avoid leaving stray - // semicolons lying around. - - - if (stmt.type === "EmptyStatement") { - return; - } - - var stmtPrinted = print(stmtPath); - var text = options.originalText; - var parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI - // don't prepend the only JSX element in a program with semicolon - - if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) { - if (stmt.comments && stmt.comments.some(function (comment) { - return comment.leading; - })) { - parts.push(print(stmtPath, { - needsSemi: true - })); - } else { - parts.push(";", stmtPrinted); - } - } else { - parts.push(stmtPrinted); - } - - if (!options.semi && isClass) { - if (classPropMayCauseASIProblems(stmtPath)) { - parts.push(";"); - } else if (stmt.type === "ClassProperty") { - var nextChild = bodyNode.body[i + 1]; - - if (classChildNeedsASIProtection(nextChild)) { - parts.push(";"); - } - } - } - - if (isNextLineEmpty$2(text, stmt, options) && !isLastStatement(stmtPath)) { - parts.push(hardline$3); - } - - printed.push(concat$4(parts)); - }); - return join$2(hardline$3, printed); -} - -function printPropertyKey(path, options, print) { - var node = path.getNode(); - var key = node.key; - - if (key.type === "Identifier" && !node.computed && options.parser === "json") { - // a -> "a" - return path.call(function (keyPath) { - return comments.printComments(keyPath, function () { - return JSON.stringify(key.name); - }, options); - }, "key"); - } - - if (isStringLiteral(key) && isIdentifierName(key.value) && !node.computed && options.parser !== "json" && !(options.parser === "typescript" && node.type === "ClassProperty")) { - // 'a' -> a - return path.call(function (keyPath) { - return comments.printComments(keyPath, function () { - return key.value; - }, options); - }, "key"); - } - - return path.call(print, "key"); -} - -function printMethod(path, options, print) { - var node = path.getNode(); - var semi = options.semi ? ";" : ""; - var kind = node.kind; - var parts = []; - - if (node.type === "ObjectMethod" || node.type === "ClassMethod") { - node.value = node; - } - - if (node.value.async) { - parts.push("async "); - } - - if (!kind || kind === "init" || kind === "method" || kind === "constructor") { - if (node.value.generator) { - parts.push("*"); - } - } else { - assert$3.ok(kind === "get" || kind === "set"); - parts.push(kind, " "); - } - - var key = printPropertyKey(path, options, print); - - if (node.computed) { - key = concat$4(["[", key, "]"]); - } - - parts.push(key, concat$4(path.call(function (valuePath) { - return [printFunctionTypeParameters(valuePath, options, print), group$1(concat$4([printFunctionParams(valuePath, print, options), printReturnType(valuePath, print, options)]))]; - }, "value"))); - - if (!node.value.body || node.value.body.length === 0) { - parts.push(semi); - } else { - parts.push(" ", path.call(print, "value", "body")); - } - - return concat$4(parts); -} - -function couldGroupArg(arg) { - return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertionExpression" || arg.type === "TSAsExpression" || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && !arg.returnType && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || isJSXNode(arg.body)); -} - -function shouldGroupLastArg(args) { - var lastArg = getLast$4(args); - var penultimateArg = getPenultimate$1(args); - return !hasLeadingComment(lastArg) && !hasTrailingComment(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type, - // disable last element expansion. - !penultimateArg || penultimateArg.type !== lastArg.type); -} - -function shouldGroupFirstArg(args) { - if (args.length !== 2) { - return false; - } - - var firstArg = args[0]; - var secondArg = args[1]; - return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && !couldGroupArg(secondArg); -} - -var functionCompositionFunctionNames = new Set(["pipe", // RxJS, Ramda -"pipeP", // Ramda -"pipeK", // Ramda -"compose", // Ramda, Redux -"composeFlipped", // Not from any library, but common in Haskell, so supported -"composeP", // Ramda -"composeK", // Ramda -"flow", // Lodash -"flowRight", // Lodash -"connect" // Redux -]); - -function isThisExpression(node) { - switch (node.type) { - case "OptionalMemberExpression": - case "MemberExpression": - { - return isThisExpression(node.object); - } - - case "ThisExpression": - case "Super": - { - return true; - } - } -} - -function isFunctionCompositionFunction(node) { - switch (node.type) { - case "OptionalMemberExpression": - case "MemberExpression": - { - return !isThisExpression(node.object) && isFunctionCompositionFunction(node.property); - } - - case "Identifier": - { - return functionCompositionFunctionNames.has(node.name); - } - - case "StringLiteral": - case "Literal": - { - return functionCompositionFunctionNames.has(node.value); - } - } -} - -function printArgumentsList(path, options, print) { - var node = path.getValue(); - var args = node.arguments; - - if (args.length === 0) { - return concat$4(["(", comments.printDanglingComments(path, options, - /* sameIndent */ - true), ")"]); - } - - var anyArgEmptyLine = false; - var hasEmptyLineFollowingFirstArg = false; - var lastArgIndex = args.length - 1; - var printedArguments = path.map(function (argPath, index) { - var arg = argPath.getNode(); - var parts = [print(argPath)]; - - if (index === lastArgIndex) {// do nothing - } else if (isNextLineEmpty$2(options.originalText, arg, options)) { - if (index === 0) { - hasEmptyLineFollowingFirstArg = true; - } - - anyArgEmptyLine = true; - parts.push(",", hardline$3, hardline$3); - } else { - parts.push(",", line$3); - } - - return concat$4(parts); - }, "arguments"); - var maybeTrailingComma = shouldPrintComma(options, "all") ? "," : ""; - - function allArgsBrokenOut() { - return group$1(concat$4(["(", indent$2(concat$4([line$3, concat$4(printedArguments)])), maybeTrailingComma, line$3, ")"]), { - shouldBreak: true - }); - } // We want to get - // pipe( - // x => x + 1, - // x => x - 1 - // ) - // here, but not - // process.stdout.pipe(socket) - - - if (isFunctionCompositionFunction(node.callee) && args.length > 1) { - return allArgsBrokenOut(); - } - - var shouldGroupFirst = shouldGroupFirstArg(args); - var shouldGroupLast = shouldGroupLastArg(args); - - if (shouldGroupFirst || shouldGroupLast) { - var shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine; // We want to print the last argument with a special flag - - var printedExpanded; - var i = 0; - path.each(function (argPath) { - if (shouldGroupFirst && i === 0) { - printedExpanded = [concat$4([argPath.call(function (p) { - return print(p, { - expandFirstArg: true - }); - }), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$3 : line$3, hasEmptyLineFollowingFirstArg ? hardline$3 : ""])].concat(printedArguments.slice(1)); - } - - if (shouldGroupLast && i === args.length - 1) { - printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(function (p) { - return print(p, { - expandLastArg: true - }); - })); - } - - i++; - }, "arguments"); - var somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1); - return concat$4([somePrintedArgumentsWillBreak ? breakParent$2 : "", conditionalGroup$1([concat$4([ifBreak$1(indent$2(concat$4(["(", softline$1, concat$4(printedExpanded)])), concat$4(["(", concat$4(printedExpanded)])), somePrintedArgumentsWillBreak ? concat$4([ifBreak$1(maybeTrailingComma), softline$1]) : "", ")"]), shouldGroupFirst ? concat$4(["(", group$1(printedExpanded[0], { - shouldBreak: true - }), concat$4(printedExpanded.slice(1)), ")"]) : concat$4(["(", concat$4(printedArguments.slice(0, -1)), group$1(getLast$4(printedExpanded), { - shouldBreak: true - }), ")"]), allArgsBrokenOut()], { - shouldBreak: shouldBreak - })]); - } - - return group$1(concat$4(["(", indent$2(concat$4([softline$1, concat$4(printedArguments)])), ifBreak$1(shouldPrintComma(options, "all") ? "," : ""), softline$1, ")"]), { - shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine - }); -} - -function printTypeAnnotation(path, options, print) { - var node = path.getValue(); - - if (!node.typeAnnotation) { - return ""; - } - - var parentNode = path.getParentNode(); - var isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite; - var isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node; - - if (isFlowAnnotationComment(options.originalText, node.typeAnnotation, options)) { - return concat$4([" /*: ", path.call(print, "typeAnnotation"), " */"]); - } - - return concat$4([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]); -} - -function printFunctionTypeParameters(path, options, print) { - var fun = path.getValue(); - - if (fun.typeArguments) { - return path.call(print, "typeArguments"); - } - - if (fun.typeParameters) { - return path.call(print, "typeParameters"); - } - - return ""; -} - -function printFunctionParams(path, print, options, expandArg, printTypeParams) { - var fun = path.getValue(); - var paramsField = fun.parameters ? "parameters" : "params"; - var typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : ""; - var printed = []; - - if (fun[paramsField]) { - printed = path.map(print, paramsField); - } - - if (fun.rest) { - printed.push(concat$4(["...", path.call(print, "rest")])); - } - - if (printed.length === 0) { - return concat$4([typeParams, "(", comments.printDanglingComments(path, options, - /* sameIndent */ - true, function (comment) { - return getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")"; - }), ")"]); - } - - var lastParam = getLast$4(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the - // params of the first/last argument, we dont want the arguments to break and instead - // want the whole expression to be on a new line. - // - // Good: Bad: - // verylongcall( verylongcall(( - // (a, b) => { a, - // } b, - // }) ) => { - // }) - - if (expandArg && !(fun[paramsField] && fun[paramsField].some(function (n) { - return n.comments; - }))) { - return group$1(concat$4([removeLines$1(typeParams), "(", join$2(", ", printed.map(removeLines$1)), ")"])); - } // Single object destructuring should hug - // - // function({ - // a, - // b, - // c - // }) {} - - - if (shouldHugArguments(fun)) { - return concat$4([typeParams, "(", join$2(", ", printed), ")"]); - } - - var parent = path.getParentNode(); // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})` - - if (isTestCall(parent)) { - return concat$4([typeParams, "(", join$2(", ", printed), ")"]); - } - - var flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"]; - var isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction(parent, options) || isTypeAnnotationAFunction(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && flowTypeAnnotations.indexOf(fun[paramsField][0].typeAnnotation.type) !== -1 && !(fun[paramsField][0].typeAnnotation.type === "GenericTypeAnnotation" && fun[paramsField][0].typeAnnotation.typeParameters) && !fun.rest; - - if (isFlowShorthandWithOneArg) { - if (options.arrowParens === "always") { - return concat$4(["(", concat$4(printed), ")"]); - } - - return concat$4(printed); - } - - var canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest; - return concat$4([typeParams, "(", indent$2(concat$4([softline$1, join$2(concat$4([",", line$3]), printed)])), ifBreak$1(canHaveTrailingComma && shouldPrintComma(options, "all") ? "," : ""), softline$1, ")"]); -} - -function shouldPrintParamsWithoutParens(path, options) { - if (options.arrowParens === "always") { - return false; - } - - if (options.arrowParens === "avoid") { - var node = path.getValue(); - return canPrintParamsWithoutParens(node); - } // Fallback default; should be unreachable - - - return false; -} - -function canPrintParamsWithoutParens(node) { - return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType; -} - -function printFunctionDeclaration(path, print, options) { - var n = path.getValue(); - var parts = []; - - if (n.async) { - parts.push("async "); - } - - parts.push("function"); - - if (n.generator) { - parts.push("*"); - } - - if (n.id) { - parts.push(" ", path.call(print, "id")); - } - - parts.push(printFunctionTypeParameters(path, options, print), group$1(concat$4([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body")); - return concat$4(parts); -} - -function printObjectMethod(path, options, print) { - var objMethod = path.getValue(); - var parts = []; - - if (objMethod.async) { - parts.push("async "); - } - - if (objMethod.generator) { - parts.push("*"); - } - - if (objMethod.method || objMethod.kind === "get" || objMethod.kind === "set") { - return printMethod(path, options, print); - } - - var key = printPropertyKey(path, options, print); - - if (objMethod.computed) { - parts.push("[", key, "]"); - } else { - parts.push(key); - } - - parts.push(printFunctionTypeParameters(path, options, print), group$1(concat$4([printFunctionParams(path, print, options), printReturnType(path, print, options)])), " ", path.call(print, "body")); - return concat$4(parts); -} - -function printReturnType(path, print, options) { - var n = path.getValue(); - var returnType = path.call(print, "returnType"); - - if (n.returnType && isFlowAnnotationComment(options.originalText, n.returnType, options)) { - return concat$4([" /*: ", returnType, " */"]); - } - - var parts = [returnType]; // prepend colon to TypeScript type annotation - - if (n.returnType && n.returnType.typeAnnotation) { - parts.unshift(": "); - } - - if (n.predicate) { - // The return type will already add the colon, but otherwise we - // need to do it ourselves - parts.push(n.returnType ? " " : ": ", path.call(print, "predicate")); - } - - return concat$4(parts); -} - -function printExportDeclaration(path, options, print) { - var decl = path.getValue(); - var semi = options.semi ? ";" : ""; - var parts = ["export "]; - var isDefault = decl["default"] || decl.type === "ExportDefaultDeclaration"; - - if (isDefault) { - parts.push("default "); - } - - parts.push(comments.printDanglingComments(path, options, - /* sameIndent */ - true)); - - if (needsHardlineAfterDanglingComment(decl)) { - parts.push(hardline$3); - } - - if (decl.declaration) { - parts.push(path.call(print, "declaration")); - - if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSAbstractClassDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction") { - parts.push(semi); - } - } else { - if (decl.specifiers && decl.specifiers.length > 0) { - var specifiers = []; - var defaultSpecifiers = []; - var namespaceSpecifiers = []; - path.each(function (specifierPath) { - var specifierType = path.getValue().type; - - if (specifierType === "ExportSpecifier") { - specifiers.push(print(specifierPath)); - } else if (specifierType === "ExportDefaultSpecifier") { - defaultSpecifiers.push(print(specifierPath)); - } else if (specifierType === "ExportNamespaceSpecifier") { - namespaceSpecifiers.push(concat$4(["* as ", print(specifierPath)])); - } - }, "specifiers"); - var isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0; - var isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0); - parts.push(decl.exportKind === "type" ? "type " : "", concat$4(defaultSpecifiers), concat$4([isDefaultFollowed ? ", " : ""]), concat$4(namespaceSpecifiers), concat$4([isNamespaceFollowed ? ", " : ""]), specifiers.length !== 0 ? group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, join$2(concat$4([",", line$3]), specifiers)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$3 : softline$1, "}"])) : ""); - } else { - parts.push("{}"); - } - - if (decl.source) { - parts.push(" from ", path.call(print, "source")); - } - - parts.push(semi); - } - - return concat$4(parts); -} - -function printFlowDeclaration(path, parts) { - var parentExportDecl = getParentExportDeclaration$1(path); - - if (parentExportDecl) { - assert$3.strictEqual(parentExportDecl.type, "DeclareExportDeclaration"); - } else { - // If the parent node has type DeclareExportDeclaration, then it - // will be responsible for printing the "declare" token. Otherwise - // it needs to be printed with this non-exported declaration node. - parts.unshift("declare "); - } - - return concat$4(parts); -} - -function getFlowVariance(path) { - if (!path.variance) { - return null; - } // Babylon 7.0 currently uses variance node type, and flow should - // follow suit soon: - // https://github.com/babel/babel/issues/4722 - - - var variance = path.variance.kind || path.variance; - - switch (variance) { - case "plus": - return "+"; - - case "minus": - return "-"; - - default: - /* istanbul ignore next */ - return variance; - } -} - -function printTypeScriptModifiers(path, options, print) { - var n = path.getValue(); - - if (!n.modifiers || !n.modifiers.length) { - return ""; - } - - return concat$4([join$2(" ", path.map(print, "modifiers")), " "]); -} - -function printTypeParameters(path, options, print, paramsKey) { - var n = path.getValue(); - - if (!n[paramsKey]) { - return ""; - } // for TypeParameterDeclaration typeParameters is a single node - - - if (!Array.isArray(n[paramsKey])) { - return path.call(print, paramsKey); - } - - var grandparent = path.getNode(2); - var isParameterInTestCall = grandparent != null && isTestCall(grandparent); - var shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation"); - - if (shouldInline) { - return concat$4(["<", join$2(", ", path.map(print, paramsKey)), ">"]); - } - - return group$1(concat$4(["<", indent$2(concat$4([softline$1, join$2(concat$4([",", line$3]), path.map(print, paramsKey))])), ifBreak$1(options.parser !== "typescript" && shouldPrintComma(options, "all") ? "," : ""), softline$1, ">"])); -} - -function printClass(path, options, print) { - var n = path.getValue(); - var parts = []; - - if (n.type === "TSAbstractClassDeclaration") { - parts.push("abstract "); - } - - parts.push("class"); - - if (n.id) { - parts.push(" ", path.call(print, "id")); - } - - parts.push(path.call(print, "typeParameters")); - var partsGroup = []; - - if (n.superClass) { - var printed = concat$4(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line - // If there is only on extends and there are not comments - - if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) { - parts.push(concat$4([" ", path.call(function (superClass) { - return comments.printComments(superClass, function () { - return printed; - }, options); - }, "superClass")])); - } else { - partsGroup.push(group$1(concat$4([line$3, path.call(function (superClass) { - return comments.printComments(superClass, function () { - return printed; - }, options); - }, "superClass")]))); - } - } else if (n.extends && n.extends.length > 0) { - parts.push(" extends ", join$2(", ", path.map(print, "extends"))); - } - - if (n["mixins"] && n["mixins"].length > 0) { - partsGroup.push(line$3, "mixins ", group$1(indent$2(join$2(concat$4([",", line$3]), path.map(print, "mixins"))))); - } - - if (n["implements"] && n["implements"].length > 0) { - partsGroup.push(line$3, "implements", group$1(indent$2(concat$4([line$3, join$2(concat$4([",", line$3]), path.map(print, "implements"))])))); - } - - if (partsGroup.length > 0) { - parts.push(group$1(indent$2(concat$4(partsGroup)))); - } - - if (n.body && n.body.comments && hasLeadingOwnLineComment(options.originalText, n.body, options)) { - parts.push(hardline$3); - } else { - parts.push(" "); - } - - parts.push(path.call(print, "body")); - return parts; -} - -function printOptionalToken(path) { - var node = path.getValue(); - - if (!node.optional) { - return ""; - } - - if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) { - return "?."; - } - - return "?"; -} - -function printMemberLookup(path, options, print) { - var property = path.call(print, "property"); - var n = path.getValue(); - var optional = printOptionalToken(path); - - if (!n.computed) { - return concat$4([optional, ".", property]); - } - - if (!n.property || isNumericLiteral(n.property)) { - return concat$4([optional, "[", property, "]"]); - } - - return group$1(concat$4([optional, "[", indent$2(concat$4([softline$1, property])), softline$1, "]"])); -} - -function printBindExpressionCallee(path, options, print) { - return concat$4(["::", path.call(print, "callee")]); -} // We detect calls on member expressions specially to format a -// common pattern better. The pattern we are looking for is this: -// -// arr -// .map(x => x + 1) -// .filter(x => x > 10) -// .some(x => x % 2) -// -// The way it is structured in the AST is via a nested sequence of -// MemberExpression and CallExpression. We need to traverse the AST -// and make groups out of it to print it in the desired way. - - -function printMemberChain(path, options, print) { - // The first phase is to linearize the AST by traversing it down. - // - // a().b() - // has the following AST structure: - // CallExpression(MemberExpression(CallExpression(Identifier))) - // and we transform it into - // [Identifier, CallExpression, MemberExpression, CallExpression] - var printedNodes = []; // Here we try to retain one typed empty line after each call expression or - // the first group whether it is in parentheses or not - - function shouldInsertEmptyLineAfter(node) { - var originalText = options.originalText; - var nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$2(originalText, node, options); - var nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty - // line after that parenthesis - - if (nextChar == ")") { - return isNextLineEmptyAfterIndex$1(originalText, nextCharIndex + 1, options); - } - - return isNextLineEmpty$2(originalText, node, options); - } - - function rec(path) { - var node = path.getValue(); - - if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) { - printedNodes.unshift({ - node: node, - printed: concat$4([comments.printComments(path, function () { - return concat$4([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]); - }, options), shouldInsertEmptyLineAfter(node) ? hardline$3 : ""]) - }); - path.call(function (callee) { - return rec(callee); - }, "callee"); - } else if (isMemberish(node)) { - printedNodes.unshift({ - node: node, - needsParens: needsParens_1(path, options), - printed: comments.printComments(path, function () { - return node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print); - }, options) - }); - path.call(function (object) { - return rec(object); - }, "object"); - } else if (node.type === "TSNonNullExpression") { - printedNodes.unshift({ - node: node, - printed: comments.printComments(path, function () { - return "!"; - }, options) - }); - path.call(function (expression) { - return rec(expression); - }, "expression"); - } else { - printedNodes.unshift({ - node: node, - printed: path.call(print) - }); - } - } // Note: the comments of the root node have already been printed, so we - // need to extract this first call without printing them as they would - // if handled inside of the recursive call. - - - var node = path.getValue(); - printedNodes.unshift({ - node: node, - printed: concat$4([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]) - }); - path.call(function (callee) { - return rec(callee); - }, "callee"); // Once we have a linear list of printed nodes, we want to create groups out - // of it. - // - // a().b.c().d().e - // will be grouped as - // [ - // [Identifier, CallExpression], - // [MemberExpression, MemberExpression, CallExpression], - // [MemberExpression, CallExpression], - // [MemberExpression], - // ] - // so that we can print it as - // a() - // .b.c() - // .d() - // .e - // The first group is the first node followed by - // - as many CallExpression as possible - // < fn()()() >.something() - // - as many array acessors as possible - // < fn()[0][1][2] >.something() - // - then, as many MemberExpression as possible but the last one - // < this.items >.something() - - var groups = []; - var currentGroup = [printedNodes[0]]; - var i = 1; - - for (; i < printedNodes.length; ++i) { - if (printedNodes[i].node.type === "TSNonNullExpression" || printedNodes[i].node.type === "OptionalCallExpression" || printedNodes[i].node.type === "CallExpression" || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral(printedNodes[i].node.property)) { - currentGroup.push(printedNodes[i]); - } else { - break; - } - } - - if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") { - for (; i + 1 < printedNodes.length; ++i) { - if (isMemberish(printedNodes[i].node) && isMemberish(printedNodes[i + 1].node)) { - currentGroup.push(printedNodes[i]); - } else { - break; - } - } - } - - groups.push(currentGroup); - currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by - // a sequence of CallExpression. To compute it, we keep adding things to the - // group until we has seen a CallExpression in the past and reach a - // MemberExpression - - var hasSeenCallExpression = false; - - for (; i < printedNodes.length; ++i) { - if (hasSeenCallExpression && isMemberish(printedNodes[i].node)) { - // [0] should be appended at the end of the group instead of the - // beginning of the next one - if (printedNodes[i].node.computed && isNumericLiteral(printedNodes[i].node.property)) { - currentGroup.push(printedNodes[i]); - continue; - } - - groups.push(currentGroup); - currentGroup = []; - hasSeenCallExpression = false; - } - - if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") { - hasSeenCallExpression = true; - } - - currentGroup.push(printedNodes[i]); - - if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(function (comment) { - return comment.trailing; - })) { - groups.push(currentGroup); - currentGroup = []; - hasSeenCallExpression = false; - } - } - - if (currentGroup.length > 0) { - groups.push(currentGroup); - } // There are cases like Object.keys(), Observable.of(), _.values() where - // they are the subject of all the chained calls and therefore should - // be kept on the same line: - // - // Object.keys(items) - // .filter(x => x) - // .map(x => x) - // - // In order to detect those cases, we use an heuristic: if the first - // node is an identifier with the name starting with a capital - // letter or just a sequence of _$. The rationale is that they are - // likely to be factories. - - - function isFactory(name) { - return /^[A-Z]|^[_$]+$/.test(name); - } // In case the Identifier is shorter than tab width, we can keep the - // first call in a single line, if it's an ExpressionStatement. - // - // d3.scaleLinear() - // .domain([0, 100]) - // .range([0, width]); - // - - - function isShort(name) { - return name.length <= options.tabWidth; - } - - function shouldNotWrap(groups) { - var parent = path.getParentNode(); - var isExpression = parent && parent.type === "ExpressionStatement"; - var hasComputed = groups[1].length && groups[1][0].node.computed; - - if (groups[0].length === 1) { - var firstNode = groups[0][0].node; - return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed); - } - - var lastNode = getLast$4(groups[0]).node; - return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed); - } - - var shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups); - - function printGroup(printedGroup) { - var result = []; - - for (var _i3 = 0; _i3 < printedGroup.length; _i3++) { - // Checks if the next node (i.e. the parent node) needs parens - // and print accordingl y - if (printedGroup[_i3 + 1] && printedGroup[_i3 + 1].needsParens) { - result.push("(", printedGroup[_i3].printed, printedGroup[_i3 + 1].printed, ")"); - _i3++; - } else { - result.push(printedGroup[_i3].printed); - } - } - - return concat$4(result); - } - - function printIndentedGroup(groups) { - if (groups.length === 0) { - return ""; - } - - return indent$2(group$1(concat$4([hardline$3, join$2(hardline$3, groups.map(printGroup))]))); - } - - var printedGroups = groups.map(printGroup); - var oneLine = concat$4(printedGroups); - var cutoff = shouldMerge ? 3 : 2; - var flatGroups = groups.slice(0, cutoff).reduce(function (res, group) { - return res.concat(group); - }, []); - var hasComment = flatGroups.slice(1, -1).some(function (node) { - return hasLeadingComment(node.node); - }) || flatGroups.slice(0, -1).some(function (node) { - return hasTrailingComment(node.node); - }) || groups[cutoff] && hasLeadingComment(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just - // render everything concatenated together. - - if (groups.length <= cutoff && !hasComment) { - return group$1(oneLine); - } // Find out the last node in the first group and check if it has an - // empty line after - - - var lastNodeBeforeIndent = getLast$4(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node; - var shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent); - var expanded = concat$4([printGroup(groups[0]), shouldMerge ? concat$4(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$3 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]); - var callExpressionCount = printedNodes.filter(function (tuple) { - return tuple.node.type === "CallExpression" || tuple.node.type === "OptionalCallExpression"; - }).length; // We don't want to print in one line if there's: - // * A comment. - // * 3 or more chained calls. - // * Any group but the last one has a hard line. - // If the last group is a function it's okay to inline if it fits. - - if (hasComment || callExpressionCount >= 3 || printedGroups.slice(0, -1).some(willBreak$1)) { - return group$1(expanded); - } - - return concat$4([// We only need to check `oneLine` because if `expanded` is chosen - // that means that the parent group has already been broken - // naturally - willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$2 : "", conditionalGroup$1([oneLine, expanded])]); -} - -function isJSXNode(node) { - return node.type === "JSXElement" || node.type === "JSXFragment" || node.type === "TSJsxFragment"; -} - -function isEmptyJSXElement(node) { - if (node.children.length === 0) { - return true; - } - - if (node.children.length > 1) { - return false; - } // if there is one text child and does not contain any meaningful text - // we can treat the element as empty. - - - var child = node.children[0]; - return isLiteral(child) && !isMeaningfulJSXText(child); -} // Only space, newline, carriage return, and tab are treated as whitespace -// inside JSX. - - -var jsxWhitespaceChars = " \n\r\t"; -var containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); -var matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)"); // Meaningful if it contains non-whitespace characters, -// or it contains whitespace without a new line. - -function isMeaningfulJSXText(node) { - return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node))); -} - -function conditionalExpressionChainContainsJSX(node) { - return Boolean(getConditionalChainContents(node).find(isJSXNode)); -} // If we have nested conditional expressions, we want to print them in JSX mode -// if there's at least one JSXElement somewhere in the tree. -// -// A conditional expression chain like this should be printed in normal mode, -// because there aren't JSXElements anywhere in it: -// -// isA ? "A" : isB ? "B" : isC ? "C" : "Unknown"; -// -// But a conditional expression chain like this should be printed in JSX mode, -// because there is a JSXElement in the last ConditionalExpression: -// -// isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>; -// -// This type of ConditionalExpression chain is structured like this in the AST: -// -// ConditionalExpression { -// test: ..., -// consequent: ..., -// alternate: ConditionalExpression { -// test: ..., -// consequent: ..., -// alternate: ConditionalExpression { -// test: ..., -// consequent: ..., -// alternate: ..., -// } -// } -// } -// -// We want to traverse over that shape and convert it into a flat structure so -// that we can find if there's a JSXElement somewhere inside. - - -function getConditionalChainContents(node) { - // Given this code: - // - // // Using a ConditionalExpression as the consequent is uncommon, but should - // // be handled. - // A ? B : C ? D : E ? F ? G : H : I - // - // which has this AST: - // - // ConditionalExpression { - // test: Identifier(A), - // consequent: Identifier(B), - // alternate: ConditionalExpression { - // test: Identifier(C), - // consequent: Identifier(D), - // alternate: ConditionalExpression { - // test: Identifier(E), - // consequent: ConditionalExpression { - // test: Identifier(F), - // consequent: Identifier(G), - // alternate: Identifier(H), - // }, - // alternate: Identifier(I), - // } - // } - // } - // - // we should return this Array: - // - // [ - // Identifier(A), - // Identifier(B), - // Identifier(C), - // Identifier(D), - // Identifier(E), - // Identifier(F), - // Identifier(G), - // Identifier(H), - // Identifier(I) - // ]; - // - // This loses the information about whether each node was the test, - // consequent, or alternate, but we don't care about that here- we are only - // flattening this structure to find if there's any JSXElements inside. - var nonConditionalExpressions = []; - - function recurse(node) { - if (node.type === "ConditionalExpression") { - recurse(node.test); - recurse(node.consequent); - recurse(node.alternate); - } else { - nonConditionalExpressions.push(node); - } - } - - recurse(node); - return nonConditionalExpressions; -} // Detect an expression node representing `{" "}` - - -function isJSXWhitespaceExpression(node) { - return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments; -} - -function separatorNoWhitespace(isFacebookTranslationTag, child) { - if (isFacebookTranslationTag) { - return ""; - } - - if (child.length === 1) { - return softline$1; - } - - return hardline$3; -} - -function separatorWithWhitespace(isFacebookTranslationTag, child) { - if (isFacebookTranslationTag) { - return hardline$3; - } - - if (child.length === 1) { - return softline$1; - } - - return hardline$3; -} // JSX Children are strange, mostly for two reasons: -// 1. JSX reads newlines into string values, instead of skipping them like JS -// 2. up to one whitespace between elements within a line is significant, -// but not between lines. -// -// Leading, trailing, and lone whitespace all need to -// turn themselves into the rather ugly `{' '}` when breaking. -// -// We print JSX using the `fill` doc primitive. -// This requires that we give it an array of alternating -// content and whitespace elements. -// To ensure this we add dummy `""` content elements as needed. - - -function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) { - var n = path.getValue(); - var children = []; // using `map` instead of `each` because it provides `i` - - path.map(function (childPath, i) { - var child = childPath.getValue(); - - if (isLiteral(child)) { - var text = rawText(child); // Contains a non-whitespace character - - if (isMeaningfulJSXText(child)) { - var words = text.split(matchJsxWhitespaceRegex); // Starts with whitespace - - if (words[0] === "") { - children.push(""); - words.shift(); - - if (/\n/.test(words[0])) { - children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1])); - } else { - children.push(jsxWhitespace); - } - - words.shift(); - } - - var endWhitespace; // Ends with whitespace - - if (getLast$4(words) === "") { - words.pop(); - endWhitespace = words.pop(); - } // This was whitespace only without a new line. - - - if (words.length === 0) { - return; - } - - words.forEach(function (word, i) { - if (i % 2 === 1) { - children.push(line$3); - } else { - children.push(word); - } - }); - - if (endWhitespace !== undefined) { - if (/\n/.test(endWhitespace)) { - children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$4(children))); - } else { - children.push(jsxWhitespace); - } - } else { - children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$4(children))); - } - } else if (/\n/.test(text)) { - // Keep (up to one) blank line between tags/expressions/text. - // Note: We don't keep blank lines between text elements. - if (text.match(/\n/g).length > 1) { - children.push(""); - children.push(hardline$3); - } - } else { - children.push(""); - children.push(jsxWhitespace); - } - } else { - var printedChild = print(childPath); - children.push(printedChild); - var next = n.children[i + 1]; - var directlyFollowedByMeaningfulText = next && isMeaningfulJSXText(next); - - if (directlyFollowedByMeaningfulText) { - var firstWord = rawText(next).trim().split(matchJsxWhitespaceRegex)[0]; - children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord)); - } else { - children.push(hardline$3); - } - } - }, "children"); - return children; -} // JSX expands children from the inside-out, instead of the outside-in. -// This is both to break children before attributes, -// and to ensure that when children break, their parents do as well. -// -// Any element that is written without any newlines and fits on a single line -// is left that way. -// Not only that, any user-written-line containing multiple JSX siblings -// should also be kept on one line if possible, -// so each user-written-line is wrapped in its own group. -// -// Elements that contain newlines or don't fit on a single line (recursively) -// are fully-split, using hardline and shouldBreak: true. -// -// To support that case properly, all leading and trailing spaces -// are stripped from the list of children, and replaced with a single hardline. - - -function printJSXElement(path, options, print) { - var n = path.getValue(); // Turn <div></div> into <div /> - - if (n.type === "JSXElement" && isEmptyJSXElement(n)) { - n.openingElement.selfClosing = true; - return path.call(print, "openingElement"); - } - - var openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment"); - var closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment"); - - if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) { - return concat$4([openingLines, concat$4(path.map(print, "children")), closingLines]); - } // Convert `{" "}` to text nodes containing a space. - // This makes it easy to turn them into `jsxWhitespace` which - // can then print as either a space or `{" "}` when breaking. - - - n.children = n.children.map(function (child) { - if (isJSXWhitespaceExpression(child)) { - return { - type: "JSXText", - value: " ", - raw: " " - }; - } - - return child; - }); - var containsTag = n.children.filter(isJSXNode).length > 0; - var containsMultipleExpressions = n.children.filter(function (child) { - return child.type === "JSXExpressionContainer"; - }).length > 1; - var containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true. - - var forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions; - var rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}'; - var jsxWhitespace = ifBreak$1(concat$4([rawJsxWhitespace, softline$1]), " "); - var isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt"; - var children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag); - var containsText = n.children.filter(function (child) { - return isMeaningfulJSXText(child); - }).length > 0; // We can end up we multiple whitespace elements with empty string - // content between them. - // We need to remove empty whitespace and softlines before JSX whitespace - // to get the correct output. - - for (var i = children.length - 2; i >= 0; i--) { - var isPairOfEmptyStrings = children[i] === "" && children[i + 1] === ""; - var isPairOfHardlines = children[i] === hardline$3 && children[i + 1] === "" && children[i + 2] === hardline$3; - var isLineFollowedByJSXWhitespace = (children[i] === softline$1 || children[i] === hardline$3) && children[i + 1] === "" && children[i + 2] === jsxWhitespace; - var isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$1 || children[i + 2] === hardline$3); - var isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace; - - if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace) { - children.splice(i, 2); - } else if (isJSXWhitespaceFollowedByLine) { - children.splice(i + 1, 2); - } - } // Trim trailing lines (or empty strings) - - - while (children.length && (isLineNext$1(getLast$4(children)) || isEmpty$1(getLast$4(children)))) { - children.pop(); - } // Trim leading lines (or empty strings) - - - while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) { - children.shift(); - children.shift(); - } // Tweak how we format children if outputting this element over multiple lines. - // Also detect whether we will force this element to output over multiple lines. - - - var multilineChildren = []; - children.forEach(function (child, i) { - // There are a number of situations where we need to ensure we display - // whitespace as `{" "}` when outputting this element over multiple lines. - if (child === jsxWhitespace) { - if (i === 1 && children[i - 1] === "") { - if (children.length === 2) { - // Solitary whitespace - multilineChildren.push(rawJsxWhitespace); - return; - } // Leading whitespace - - - multilineChildren.push(concat$4([rawJsxWhitespace, hardline$3])); - return; - } else if (i === children.length - 1) { - // Trailing whitespace - multilineChildren.push(rawJsxWhitespace); - return; - } else if (children[i - 1] === "" && children[i - 2] === hardline$3) { - // Whitespace after line break - multilineChildren.push(rawJsxWhitespace); - return; - } - } - - multilineChildren.push(child); - - if (willBreak$1(child)) { - forcedBreak = true; - } - }); // If there is text we use `fill` to fit as much onto each line as possible. - // When there is no text (just tags and expressions) we use `group` - // to output each on a separate line. - - var content = containsText ? fill$2(multilineChildren) : group$1(concat$4(multilineChildren), { - shouldBreak: true - }); - var multiLineElem = group$1(concat$4([openingLines, indent$2(concat$4([hardline$3, content])), hardline$3, closingLines])); - - if (forcedBreak) { - return multiLineElem; - } - - return conditionalGroup$1([group$1(concat$4([openingLines, concat$4(children), closingLines])), multiLineElem]); -} - -function maybeWrapJSXElementInParens(path, elem) { - var parent = path.getParentNode(); - - if (!parent) { - return elem; - } - - var NO_WRAP_PARENTS = { - ArrayExpression: true, - JSXAttribute: true, - JSXElement: true, - JSXExpressionContainer: true, - JSXFragment: true, - TSJsxFragment: true, - ExpressionStatement: true, - CallExpression: true, - OptionalCallExpression: true, - ConditionalExpression: true - }; - - if (NO_WRAP_PARENTS[parent.type]) { - return elem; - } - - var shouldBreak = matchAncestorTypes$1(path, ["ArrowFunctionExpression", "CallExpression", "JSXExpressionContainer"]); - return group$1(concat$4([ifBreak$1("("), indent$2(concat$4([softline$1, elem])), softline$1, ifBreak$1(")")]), { - shouldBreak: shouldBreak - }); -} - -function isBinaryish(node) { - return node.type === "BinaryExpression" || node.type === "LogicalExpression"; -} - -function isMemberish(node) { - return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object; -} - -function shouldInlineLogicalExpression(node) { - if (node.type !== "LogicalExpression") { - return false; - } - - if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) { - return true; - } - - if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) { - return true; - } - - if (isJSXNode(node.right)) { - return true; - } - - return false; -} // For binary expressions to be consistent, we need to group -// subsequent operators with the same precedence level under a single -// group. Otherwise they will be nested such that some of them break -// onto new lines but not all. Operators with the same precedence -// level should either all break or not. Because we group them by -// precedence level and the AST is structured based on precedence -// level, things are naturally broken up correctly, i.e. `&&` is -// broken before `+`. - - -function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) { - var parts = []; - var node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same. - - if (isBinaryish(node)) { - // Put all operators with the same precedence level in the same - // group. The reason we only need to do this with the `left` - // expression is because given an expression like `1 + 2 - 3`, it - // is always parsed like `((1 + 2) - 3)`, meaning the `left` side - // is where the rest of the expression will exist. Binary - // expressions on the right side mean they have a difference - // precedence level and should be treated as a separate group, so - // print them normally. (This doesn't hold for the `**` operator, - // which is unique in that it is right-associative.) - if (shouldFlatten$1(node.operator, node.left.operator)) { - // Flatten them out by recursively calling this function. - parts = parts.concat(path.call(function (left) { - return printBinaryishExpressions(left, print, options, - /* isNested */ - true, isInsideParenthesis); - }, "left")); - } else { - parts.push(path.call(print, "left")); - } - - var shouldInline = shouldInlineLogicalExpression(node); - var lineBeforeOperator = node.operator === "|>"; - var right = shouldInline ? concat$4([node.operator, " ", path.call(print, "right")]) : concat$4([lineBeforeOperator ? softline$1 : "", node.operator, lineBeforeOperator ? " " : line$3, path.call(print, "right")]); // If there's only a single binary expression, we want to create a group - // in order to avoid having a small right part like -1 be on its own line. - - var parent = path.getParentNode(); - var shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type; - parts.push(" ", shouldGroup ? group$1(right) : right); // The root comments are already printed, but we need to manually print - // the other ones since we don't call the normal print on BinaryExpression, - // only for the left and right parts - - if (isNested && node.comments) { - parts = comments.printComments(path, function () { - return concat$4(parts); - }, options); - } - } else { - // Our stopping case. Simply print the node normally. - parts.push(path.call(print)); - } - - return parts; -} - -function printAssignmentRight(leftNode, rightNode, printedRight, options) { - if (hasLeadingOwnLineComment(options.originalText, rightNode, options)) { - return indent$2(concat$4([hardline$3, printedRight])); - } - - var canBreak = isBinaryish(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || (leftNode.type === "Identifier" || isStringLiteral(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral(rightNode) || isMemberExpressionChain(rightNode)) && // do not put values on a separate line from the key in json - options.parser !== "json" && options.parser !== "json5"; - - if (canBreak) { - return indent$2(concat$4([line$3, printedRight])); - } - - return concat$4([" ", printedRight]); -} - -function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) { - if (!rightNode) { - return printedLeft; - } - - var printed = printAssignmentRight(leftNode, rightNode, printedRight, options); - return group$1(concat$4([printedLeft, operator, printed])); -} - -function adjustClause(node, clause, forceSpace) { - if (node.type === "EmptyStatement") { - return ";"; - } - - if (node.type === "BlockStatement" || forceSpace) { - return concat$4([" ", clause]); - } - - return indent$2(concat$4([line$3, clause])); -} - -function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) { - var raw = rawText(node); - var isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral"; - return printString$1(raw, options, isDirectiveLiteral); -} - -function printRegex(node) { - var flags = node.flags.split("").sort().join(""); - return "/".concat(node.pattern, "/").concat(flags); -} - -function isLastStatement(path) { - var parent = path.getParentNode(); - - if (!parent) { - return true; - } - - var node = path.getValue(); - var body = (parent.body || parent.consequent).filter(function (stmt) { - return stmt.type !== "EmptyStatement"; - }); - return body && body[body.length - 1] === node; -} - -function hasLeadingComment(node) { - return node.comments && node.comments.some(function (comment) { - return comment.leading; - }); -} - -function hasTrailingComment(node) { - return node.comments && node.comments.some(function (comment) { - return comment.trailing; - }); -} - -function hasLeadingOwnLineComment(text, node, options) { - if (isJSXNode(node)) { - return hasNodeIgnoreComment$1(node); - } - - var res = node.comments && node.comments.some(function (comment) { - return comment.leading && hasNewline$2(text, options.locEnd(comment)); - }); - return res; -} - -function hasNakedLeftSide(node) { - return node.type === "AssignmentExpression" || node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "ConditionalExpression" || node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "BindExpression" && !node.object || node.type === "UpdateExpression" && !node.prefix; -} - -function isFlowAnnotationComment(text, typeAnnotation, options) { - var start = options.locStart(typeAnnotation); - var end = skipWhitespace$1(text, options.locEnd(typeAnnotation)); - return text.substr(start, 2) === "/*" && text.substr(end, 2) === "*/"; -} - -function getLeftSide(node) { - if (node.expressions) { - return node.expressions[0]; - } - - return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression; -} - -function getLeftSidePathName(path, node) { - if (node.expressions) { - return ["expressions", 0]; - } - - if (node.left) { - return ["left"]; - } - - if (node.test) { - return ["test"]; - } - - if (node.callee) { - return ["callee"]; - } - - if (node.object) { - return ["object"]; - } - - if (node.tag) { - return ["tag"]; - } - - if (node.argument) { - return ["argument"]; - } - - if (node.expression) { - return ["expression"]; - } - - throw new Error("Unexpected node has no left side", node); -} - -function exprNeedsASIProtection(path, options) { - var node = path.getValue(); - var maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode(node) || node.type === "BindExpression" || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex; - - if (maybeASIProblem) { - return true; - } - - if (!hasNakedLeftSide(node)) { - return false; - } - - return path.call.apply(path, [function (childPath) { - return exprNeedsASIProtection(childPath, options); - }].concat(getLeftSidePathName(path, node))); -} - -function stmtNeedsASIProtection(path, options) { - var node = path.getNode(); - - if (node.type !== "ExpressionStatement") { - return false; - } - - return path.call(function (childPath) { - return exprNeedsASIProtection(childPath, options); - }, "expression"); -} - -function classPropMayCauseASIProblems(path) { - var node = path.getNode(); - - if (node.type !== "ClassProperty") { - return false; - } - - var name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today - // so isn't properly tested yet. - - if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) { - return true; - } -} - -function classChildNeedsASIProtection(node) { - if (!node) { - return; - } - - if (!node.computed) { - var name = node.key && node.key.name; - - if (name === "in" || name === "instanceof") { - return true; - } - } - - switch (node.type) { - case "ClassProperty": - case "TSAbstractClassProperty": - return node.computed; - - case "MethodDefinition": // Flow - - case "TSAbstractMethodDefinition": // TypeScript - - case "ClassMethod": - { - // Babylon - var isAsync = node.value ? node.value.async : node.async; - var isGenerator = node.value ? node.value.generator : node.generator; - - if (isAsync || node.static || node.kind === "get" || node.kind === "set") { - return false; - } - - if (node.computed || isGenerator) { - return true; - } - - return false; - } - - default: - /* istanbul ignore next */ - return false; - } -} // This recurses the return argument, looking for the first token -// (the leftmost leaf node) and, if it (or its parents) has any -// leadingComments, returns true (so it can be wrapped in parens). - - -function returnArgumentHasLeadingComment(options, argument) { - if (hasLeadingOwnLineComment(options.originalText, argument, options)) { - return true; - } - - if (hasNakedLeftSide(argument)) { - var leftMost = argument; - var newLeftMost; - - while (newLeftMost = getLeftSide(leftMost)) { - leftMost = newLeftMost; - - if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) { - return true; - } - } - } - - return false; -} - -function isMemberExpressionChain(node) { - if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") { - return false; - } - - if (node.object.type === "Identifier") { - return true; - } - - return isMemberExpressionChain(node.object); -} // Hack to differentiate between the following two which have the same ast -// type T = { method: () => void }; -// type T = { method(): void }; - - -function isObjectTypePropertyAFunction(node, options) { - return node.type === "ObjectTypeProperty" && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options); -} // TODO: This is a bad hack and we need a better way to distinguish between -// arrow functions and otherwise - - -function isFunctionNotation(node, options) { - return isGetterOrSetter(node) || sameLocStart(node, node.value, options); -} - -function isGetterOrSetter(node) { - return node.kind === "get" || node.kind === "set"; -} - -function sameLocStart(nodeA, nodeB, options) { - return options.locStart(nodeA) === options.locStart(nodeB); -} // Hack to differentiate between the following two which have the same ast -// declare function f(a): void; -// var f: (a) => void; - - -function isTypeAnnotationAFunction(node, options) { - return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options); -} - -function isNodeStartingWithDeclare(node, options) { - if (!(options.parser === "flow" || options.parser === "typescript")) { - return false; - } - - return options.originalText.slice(0, options.locStart(node)).match(/declare[ \t]*$/) || options.originalText.slice(node.range[0], node.range[1]).startsWith("declare "); -} - -function shouldHugType(node) { - if (isObjectType(node)) { - return true; - } - - if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") { - var voidCount = node.types.filter(function (n) { - return n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword"; - }).length; - var objectCount = node.types.filter(function (n) { - return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}> - n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference"; - }).length; - - if (node.types.length - 1 === voidCount && objectCount > 0) { - return true; - } - } - - return false; -} - -function shouldHugArguments(fun) { - return fun && fun.params && fun.params.length === 1 && !fun.params[0].comments && (fun.params[0].type === "ObjectPattern" || fun.params[0].type === "ArrayPattern" || fun.params[0].type === "Identifier" && fun.params[0].typeAnnotation && (fun.params[0].typeAnnotation.type === "TypeAnnotation" || fun.params[0].typeAnnotation.type === "TSTypeAnnotation") && isObjectType(fun.params[0].typeAnnotation.typeAnnotation) || fun.params[0].type === "FunctionTypeParam" && isObjectType(fun.params[0].typeAnnotation) || fun.params[0].type === "AssignmentPattern" && (fun.params[0].left.type === "ObjectPattern" || fun.params[0].left.type === "ArrayPattern") && (fun.params[0].right.type === "Identifier" || fun.params[0].right.type === "ObjectExpression" && fun.params[0].right.properties.length === 0 || fun.params[0].right.type === "ArrayExpression" && fun.params[0].right.elements.length === 0)) && !fun.rest; -} - -function templateLiteralHasNewLines(template) { - return template.quasis.some(function (quasi) { - return quasi.value.raw.includes("\n"); - }); -} - -function isTemplateOnItsOwnLine(n, text, options) { - return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$2(text, options.locStart(n), { - backwards: true - }); -} - -function printArrayItems(path, options, printPath, print) { - var printedElements = []; - var separatorParts = []; - path.each(function (childPath) { - printedElements.push(concat$4(separatorParts)); - printedElements.push(group$1(print(childPath))); - separatorParts = [",", line$3]; - - if (childPath.getValue() && isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) { - separatorParts.push(softline$1); - } - }, printPath); - return concat$4(printedElements); -} - -function hasDanglingComments(node) { - return node.comments && node.comments.some(function (comment) { - return !comment.leading && !comment.trailing; - }); -} - -function needsHardlineAfterDanglingComment(node) { - if (!node.comments) { - return false; - } - - var lastDanglingComment = getLast$4(node.comments.filter(function (comment) { - return !comment.leading && !comment.trailing; - })); - return lastDanglingComment && !comments$3.isBlockComment(lastDanglingComment); -} - -function isLiteral(node) { - return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText"; -} - -function isNumericLiteral(node) { - return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number"; -} - -function isStringLiteral(node) { - return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string"; -} - -function isObjectType(n) { - return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral"; -} - -var unitTestRe = /^(skip|[fx]?(it|describe|test))$/; // eg; `describe("some string", (done) => {})` - -function isTestCall(n, parent) { - if (n.type !== "CallExpression") { - return false; - } - - if (n.arguments.length === 1) { - if (isAngularTestWrapper(n) && parent && isTestCall(parent)) { - return isFunctionOrArrowExpression(n.arguments[0].type); - } - - if (isUnitTestSetUp(n)) { - return isFunctionOrArrowExpression(n.arguments[0].type) || isAngularTestWrapper(n.arguments[0]); - } - } else if (n.arguments.length === 2) { - if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) { - return isFunctionOrArrowExpression(n.arguments[1].type) && n.arguments[1].params.length <= 1 || isAngularTestWrapper(n.arguments[1]); - } - } - - return false; -} - -function isSkipOrOnlyBlock(node) { - return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && node.callee.object.type === "Identifier" && node.callee.property.type === "Identifier" && unitTestRe.test(node.callee.object.name) && (node.callee.property.name === "only" || node.callee.property.name === "skip"); -} - -function isTemplateLiteral(node) { - return node.type === "TemplateLiteral"; -} // `inject` is used in AngularJS 1.x, `async` in Angular 2+ -// example: https://docs.angularjs.org/guide/unit-testing#using-beforeall- - - -function isAngularTestWrapper(node) { - return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject"); -} - -function isFunctionOrArrowExpression(type) { - return type === "FunctionExpression" || type === "ArrowFunctionExpression"; -} - -function isUnitTestSetUp(n) { - var unitTestSetUpRe = /^(before|after)(Each|All)$/; - return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1; -} - -function isTheOnlyJSXElementInMarkdown(options, path) { - if (options.parentParser !== "markdown") { - return false; - } - - var node = path.getNode(); - - if (!node.expression || !isJSXNode(node.expression)) { - return false; - } - - var parent = path.getParentNode(); - return parent.type === "Program" && parent.body.length == 1; -} - -function willPrintOwnComments(path) { - var node = path.getValue(); - var parent = path.getParentNode(); - return (node && isJSXNode(node) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && !hasIgnoreComment$1(path); -} - -function canAttachComment(node) { - return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import" && !(node.callee && node.callee.type === "Import"); -} - -function printComment$1(commentPath, options) { - var comment = commentPath.getValue(); - - switch (comment.type) { - case "CommentBlock": - case "Block": - { - if (isJsDocComment(comment)) { - var printed = printJsDocComment(comment); // We need to prevent an edge case of a previous trailing comment - // printed as a `lineSuffix` which causes the comments to be - // interleaved. See https://github.com/prettier/prettier/issues/4412 - - if (comment.trailing && !hasNewline$2(options.originalText, options.locStart(comment), { - backwards: true - })) { - return concat$4([hardline$3, printed]); - } - - return printed; - } - - var isInsideFlowComment = options.originalText.substr(options.locEnd(comment) - 3, 3) === "*-/"; - return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/"); - } - - case "CommentLine": - case "Line": - // Print shebangs with the proper comment characters - if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) { - return "#!" + comment.value.trimRight(); - } - - return "//" + comment.value.trimRight(); - - default: - throw new Error("Not a comment: " + JSON.stringify(comment)); - } -} - -function isJsDocComment(comment) { - var lines = comment.value.split("\n"); - return lines.length > 1 && lines.slice(0, lines.length - 1).every(function (line) { - return line.trim()[0] === "*"; - }); -} - -function printJsDocComment(comment) { - var lines = comment.value.split("\n"); - return concat$4(["/*", join$2(hardline$3, lines.map(function (line, index) { - return (index > 0 ? " " : "") + (index < lines.length - 1 ? line.trim() : line.trimLeft()); - })), "*/"]); -} - -function rawText(node) { - return node.extra ? node.extra.raw : node.raw; -} - -var printerEstree = { - print: genericPrint$1, - embed: embed_1, - insertPragma: insertPragma, - massageAstNode: clean_1, - hasPrettierIgnore: hasPrettierIgnore, - willPrintOwnComments: willPrintOwnComments, - canAttachComment: canAttachComment, - printComment: printComment$1, - isBlockComment: comments$3.isBlockComment, - handleComments: { - ownLine: comments$3.handleOwnLineComment, - endOfLine: comments$3.handleEndOfLineComment, - remaining: comments$3.handleRemainingComment - } -}; - -var _require$$0$builders$2 = doc.builders; -var concat$6 = _require$$0$builders$2.concat; -var hardline$5 = _require$$0$builders$2.hardline; -var indent$4 = _require$$0$builders$2.indent; -var join$4 = _require$$0$builders$2.join; - -function genericPrint$2(path, options, print) { - var node = path.getValue(); - - switch (node.type) { - case "ArrayExpression": - return node.elements.length === 0 ? "[]" : concat$6(["[", indent$4(concat$6([hardline$5, join$4(concat$6([",", hardline$5]), path.map(print, "elements"))])), hardline$5, "]"]); - - case "ObjectExpression": - return node.properties.length === 0 ? "{}" : concat$6(["{", indent$4(concat$6([hardline$5, join$4(concat$6([",", hardline$5]), path.map(print, "properties"))])), hardline$5, "}"]); - - case "ObjectProperty": - return concat$6([path.call(print, "key"), ": ", path.call(print, "value")]); - - case "UnaryExpression": - return concat$6([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]); - - case "NullLiteral": - return "null"; - - case "BooleanLiteral": - return node.value ? "true" : "false"; - - case "StringLiteral": - case "NumericLiteral": - return JSON.stringify(node.value); - - case "Identifier": - return JSON.stringify(node.name); - - default: - /* istanbul ignore next */ - throw new Error("unknown type: " + JSON.stringify(node.type)); - } -} - -function clean$2(node, newNode -/*, parent*/ -) { - delete newNode.start; - delete newNode.end; - delete newNode.extra; - delete newNode.loc; - delete newNode.comments; - - if (node.type === "Identifier") { - return { - type: "StringLiteral", - value: node.name - }; - } - - if (node.type === "UnaryExpression" && node.operator === "+") { - return newNode.argument; - } -} - -var printerEstreeJson = { - print: genericPrint$2, - massageAstNode: clean$2 -}; - -var CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js - -var commonOptions = { - bracketSpacing: { - since: "0.0.0", - category: CATEGORY_COMMON, - type: "boolean", - default: true, - description: "Print spaces between brackets.", - oppositeDescription: "Do not print spaces between brackets." - }, - singleQuote: { - since: "0.0.0", - category: CATEGORY_COMMON, - type: "boolean", - default: false, - description: "Use single quotes instead of double quotes." - }, - proseWrap: { - since: "1.8.2", - category: CATEGORY_COMMON, - type: "choice", - default: [{ - since: "1.8.2", - value: true - }, { - since: "1.9.0", - value: "preserve" - }], - description: "How to wrap prose.", - choices: [{ - since: "1.9.0", - value: "always", - description: "Wrap prose if it exceeds the print width." - }, { - since: "1.9.0", - value: "never", - description: "Do not wrap prose." - }, { - since: "1.9.0", - value: "preserve", - description: "Wrap prose as-is." - }, { - value: false, - deprecated: "1.9.0", - redirect: "never" - }, { - value: true, - deprecated: "1.9.0", - redirect: "always" - }] - } -}; - -var CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js - -var options$3 = { - arrowParens: { - since: "1.9.0", - category: CATEGORY_JAVASCRIPT, - type: "choice", - default: "avoid", - description: "Include parentheses around a sole arrow function parameter.", - choices: [{ - value: "avoid", - description: "Omit parens when possible. Example: `x => x`" - }, { - value: "always", - description: "Always include parens. Example: `(x) => x`" - }] - }, - bracketSpacing: commonOptions.bracketSpacing, - jsxBracketSameLine: { - since: "0.17.0", - category: CATEGORY_JAVASCRIPT, - type: "boolean", - default: false, - description: "Put > on the last line instead of at a new line." - }, - semi: { - since: "1.0.0", - category: CATEGORY_JAVASCRIPT, - type: "boolean", - default: true, - description: "Print semicolons.", - oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them." - }, - singleQuote: commonOptions.singleQuote, - trailingComma: { - since: "0.0.0", - category: CATEGORY_JAVASCRIPT, - type: "choice", - default: [{ - since: "0.0.0", - value: false - }, { - since: "0.19.0", - value: "none" - }], - description: "Print trailing commas wherever possible when multi-line.", - choices: [{ - value: "none", - description: "No trailing commas." - }, { - value: "es5", - description: "Trailing commas where valid in ES5 (objects, arrays, etc.)" - }, { - value: "all", - description: "Trailing commas wherever possible (including function arguments)." - }, { - value: true, - deprecated: "0.19.0", - redirect: "es5" - }, { - value: false, - deprecated: "0.19.0", - redirect: "none" - }] - } -}; - -var languageExtend = function languageExtend() { - var _arguments = arguments; - var main = arguments[0]; - - var _loop = function _loop(i) { - var arg = _arguments[i]; - Object.keys(arg).forEach(function (key) { - var newKey = key === "languageId" ? "linguistLanguageId" : key; - var value = arg[key]; - - if (Array.isArray(main[newKey])) { - main[newKey] = main[newKey].concat(value); - } else { - main[newKey] = value; - } - }); - }; - - for (var i = 1; i < arguments.length; i++) { - _loop(i); - } - - return main; -}; - -var name$1 = "JavaScript"; -var type = "programming"; -var tmScope = "source.js"; -var aceMode = "javascript"; -var codemirrorMode = "javascript"; -var codemirrorMimeType = "text/javascript"; -var color = "#f1e05a"; -var aliases = ["js", "node"]; -var extensions = [".js", "._js", ".bones", ".es", ".es6", ".frag", ".gs", ".jake", ".jsb", ".jscad", ".jsfl", ".jsm", ".jss", ".mjs", ".njs", ".pac", ".sjs", ".ssjs", ".xsjs", ".xsjslib"]; -var filenames = ["Jakefile"]; -var interpreters = ["node"]; -var languageId = 183; -var javascript = { - name: name$1, - type: type, - tmScope: tmScope, - aceMode: aceMode, - codemirrorMode: codemirrorMode, - codemirrorMimeType: codemirrorMimeType, - color: color, - aliases: aliases, - extensions: extensions, - filenames: filenames, - interpreters: interpreters, - languageId: languageId -}; - -var javascript$1 = Object.freeze({ - name: name$1, - type: type, - tmScope: tmScope, - aceMode: aceMode, - codemirrorMode: codemirrorMode, - codemirrorMimeType: codemirrorMimeType, - color: color, - aliases: aliases, - extensions: extensions, - filenames: filenames, - interpreters: interpreters, - languageId: languageId, - default: javascript -}); - -var name$2 = "JSX"; -var type$1 = "programming"; -var group$2 = "JavaScript"; -var extensions$1 = [".jsx"]; -var tmScope$1 = "source.js.jsx"; -var aceMode$1 = "javascript"; -var codemirrorMode$1 = "jsx"; -var codemirrorMimeType$1 = "text/jsx"; -var languageId$1 = 178; -var jsx = { - name: name$2, - type: type$1, - group: group$2, - extensions: extensions$1, - tmScope: tmScope$1, - aceMode: aceMode$1, - codemirrorMode: codemirrorMode$1, - codemirrorMimeType: codemirrorMimeType$1, - languageId: languageId$1 -}; - -var jsx$1 = Object.freeze({ - name: name$2, - type: type$1, - group: group$2, - extensions: extensions$1, - tmScope: tmScope$1, - aceMode: aceMode$1, - codemirrorMode: codemirrorMode$1, - codemirrorMimeType: codemirrorMimeType$1, - languageId: languageId$1, - default: jsx -}); - -var name$3 = "TypeScript"; -var type$2 = "programming"; -var color$1 = "#2b7489"; -var aliases$1 = ["ts"]; -var extensions$2 = [".ts", ".tsx"]; -var tmScope$2 = "source.ts"; -var aceMode$2 = "typescript"; -var codemirrorMode$2 = "javascript"; -var codemirrorMimeType$2 = "application/typescript"; -var languageId$2 = 378; -var typescript = { - name: name$3, - type: type$2, - color: color$1, - aliases: aliases$1, - extensions: extensions$2, - tmScope: tmScope$2, - aceMode: aceMode$2, - codemirrorMode: codemirrorMode$2, - codemirrorMimeType: codemirrorMimeType$2, - languageId: languageId$2 -}; - -var typescript$1 = Object.freeze({ - name: name$3, - type: type$2, - color: color$1, - aliases: aliases$1, - extensions: extensions$2, - tmScope: tmScope$2, - aceMode: aceMode$2, - codemirrorMode: codemirrorMode$2, - codemirrorMimeType: codemirrorMimeType$2, - languageId: languageId$2, - default: typescript -}); - -var name$4 = "JSON"; -var type$3 = "data"; -var tmScope$3 = "source.json"; -var group$3 = "JavaScript"; -var aceMode$3 = "json"; -var codemirrorMode$3 = "javascript"; -var codemirrorMimeType$3 = "application/json"; -var searchable = false; -var extensions$3 = [".json", ".avsc", ".geojson", ".gltf", ".JSON-tmLanguage", ".jsonl", ".tfstate", ".tfstate.backup", ".topojson", ".webapp", ".webmanifest"]; -var filenames$1 = [".arcconfig", ".htmlhintrc", ".tern-config", ".tern-project", "composer.lock", "mcmod.info"]; -var languageId$3 = 174; -var json$2 = { - name: name$4, - type: type$3, - tmScope: tmScope$3, - group: group$3, - aceMode: aceMode$3, - codemirrorMode: codemirrorMode$3, - codemirrorMimeType: codemirrorMimeType$3, - searchable: searchable, - extensions: extensions$3, - filenames: filenames$1, - languageId: languageId$3 -}; - -var json$3 = Object.freeze({ - name: name$4, - type: type$3, - tmScope: tmScope$3, - group: group$3, - aceMode: aceMode$3, - codemirrorMode: codemirrorMode$3, - codemirrorMimeType: codemirrorMimeType$3, - searchable: searchable, - extensions: extensions$3, - filenames: filenames$1, - languageId: languageId$3, - default: json$2 -}); - -var name$5 = "JSON with Comments"; -var type$4 = "data"; -var group$4 = "JSON"; -var tmScope$4 = "source.js"; -var aceMode$4 = "javascript"; -var codemirrorMode$4 = "javascript"; -var codemirrorMimeType$4 = "text/javascript"; -var aliases$2 = ["jsonc"]; -var extensions$4 = [".sublime-build", ".sublime-commands", ".sublime-completions", ".sublime-keymap", ".sublime-macro", ".sublime-menu", ".sublime-mousemap", ".sublime-project", ".sublime-settings", ".sublime-theme", ".sublime-workspace", ".sublime_metrics", ".sublime_session"]; -var filenames$2 = [".babelrc", ".eslintrc.json", ".jscsrc", ".jshintrc", ".jslintrc", "tsconfig.json"]; -var languageId$4 = 423; -var jsonWithComments = { - name: name$5, - type: type$4, - group: group$4, - tmScope: tmScope$4, - aceMode: aceMode$4, - codemirrorMode: codemirrorMode$4, - codemirrorMimeType: codemirrorMimeType$4, - aliases: aliases$2, - extensions: extensions$4, - filenames: filenames$2, - languageId: languageId$4 -}; - -var jsonWithComments$1 = Object.freeze({ - name: name$5, - type: type$4, - group: group$4, - tmScope: tmScope$4, - aceMode: aceMode$4, - codemirrorMode: codemirrorMode$4, - codemirrorMimeType: codemirrorMimeType$4, - aliases: aliases$2, - extensions: extensions$4, - filenames: filenames$2, - languageId: languageId$4, - default: jsonWithComments -}); - -var name$6 = "JSON5"; -var type$5 = "data"; -var extensions$5 = [".json5"]; -var tmScope$5 = "source.js"; -var aceMode$5 = "javascript"; -var codemirrorMode$5 = "javascript"; -var codemirrorMimeType$5 = "application/json"; -var languageId$5 = 175; -var json5 = { - name: name$6, - type: type$5, - extensions: extensions$5, - tmScope: tmScope$5, - aceMode: aceMode$5, - codemirrorMode: codemirrorMode$5, - codemirrorMimeType: codemirrorMimeType$5, - languageId: languageId$5 -}; - -var json5$1 = Object.freeze({ - name: name$6, - type: type$5, - extensions: extensions$5, - tmScope: tmScope$5, - aceMode: aceMode$5, - codemirrorMode: codemirrorMode$5, - codemirrorMimeType: codemirrorMimeType$5, - languageId: languageId$5, - default: json5 -}); - -var require$$0$10 = ( javascript$1 && javascript ) || javascript$1; - -var require$$1$6 = ( jsx$1 && jsx ) || jsx$1; - -var require$$2$6 = ( typescript$1 && typescript ) || typescript$1; - -var require$$3$1 = ( json$3 && json$2 ) || json$3; - -var require$$4 = ( jsonWithComments$1 && jsonWithComments ) || jsonWithComments$1; - -var require$$5 = ( json5$1 && json5 ) || json5$1; - -var languages = [languageExtend({}, require$$0$10, { - since: "0.0.0", - parsers: ["babylon", "flow"], - vscodeLanguageIds: ["javascript"] -}), { - name: "Flow", - since: "0.0.0", - parsers: ["babylon", "flow"], - extensions: [".js.flow"] -}, languageExtend({}, require$$1$6, { - since: "0.0.0", - parsers: ["babylon", "flow"], - vscodeLanguageIds: ["javascriptreact"] -}), languageExtend({}, require$$2$6, { - since: "1.4.0", - parsers: ["typescript-eslint"], - vscodeLanguageIds: ["typescript", "typescriptreact"] -}), Object.assign(languageExtend({}, require$$3$1, { - name: "JSON.stringify", - since: "1.13.0", - parsers: ["json-stringify"], - vscodeLanguageIds: ["json"] -}), // overwrite -{ - extensions: [], - // .json file defaults to json instead of json-stringify - filenames: ["package.json", "package-lock.json", "composer.json"] -}), languageExtend({}, require$$3$1, { - since: "1.5.0", - parsers: ["json"], - filenames: [".prettierrc"], - vscodeLanguageIds: ["json"] -}), languageExtend({}, require$$4, { - since: "1.5.0", - parsers: ["json"], - filenames: [".eslintrc"], - vscodeLanguageIds: ["jsonc"] -}), languageExtend({}, require$$5, { - since: "1.13.0", - parsers: ["json5"], - vscodeLanguageIds: ["json5"] -})]; -var printers = { - estree: printerEstree, - "estree-json": printerEstreeJson -}; -var languageJs = { - languages: languages, - options: options$3, - printers: printers -}; - -var index$5 = ["a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "bgsound", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "content", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "image", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "listing", "main", "map", "mark", "marquee", "math", "menu", "menuitem", "meta", "meter", "multicol", "nav", "nextid", "nobr", "noembed", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "plaintext", "pre", "progress", "q", "rb", "rbc", "rp", "rt", "rtc", "ruby", "s", "samp", "script", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "svg", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr", "xmp"]; - -var htmlTagNames = Object.freeze({ - default: index$5 -}); - -var htmlTagNames$1 = ( htmlTagNames && index$5 ) || htmlTagNames; - -function clean$3(ast, newObj, parent) { - ["raw", // front-matter - "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(function (name) { - delete newObj[name]; - }); - - if (ast.type === "yaml") { - delete newObj.value; - } // --insert-pragma - - - if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment - parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) { - /** - * something - * - * @format - */ - delete newObj.text; // standalone pragma - - if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) { - return null; - } - } - - if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") { - delete newObj.value; - } - - if (ast.type === "css-rule") { - delete newObj.params; - } - - if (ast.type === "selector-combinator") { - newObj.value = newObj.value.replace(/\s+/g, " "); - } - - if (ast.type === "media-feature") { - newObj.value = newObj.value.replace(/ /g, ""); - } - - if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].indexOf(newObj.value.replace().toLowerCase()) !== -1) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") { - newObj.value = newObj.value.toLowerCase(); - } - - if (ast.type === "css-decl") { - newObj.prop = newObj.prop.toLowerCase(); - } - - if (ast.type === "css-atrule" || ast.type === "css-import") { - newObj.name = newObj.name.toLowerCase(); - } - - if (ast.type === "value-number") { - newObj.unit = newObj.unit.toLowerCase(); - } - - if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) { - newObj.value = cleanCSSStrings(newObj.value); - } - - if (ast.type === "selector-attribute") { - newObj.attribute = newObj.attribute.trim(); - - if (newObj.namespace) { - if (typeof newObj.namespace === "string") { - newObj.namespace = newObj.namespace.trim(); - - if (newObj.namespace.length === 0) { - newObj.namespace = true; - } - } - } - - if (newObj.value) { - newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, ""); - delete newObj.quoted; - } - } - - if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) { - newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, function (match, numStr, unit) { - var num = Number(numStr); - return isNaN(num) ? match : num + unit.toLowerCase(); - }); - } - - if (ast.type === "selector-tag") { - var lowercasedValue = ast.value.toLowerCase(); - - if (htmlTagNames$1.indexOf(lowercasedValue) !== -1) { - newObj.value = lowercasedValue; - } - - if (["from", "to"].indexOf(lowercasedValue) !== -1) { - newObj.value = lowercasedValue; - } - } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func` - - - if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") { - delete newObj.value; - } // Workaround for SCSS nested properties - - - if (ast.type === "selector-unknown") { - delete newObj.value; - } -} - -function cleanCSSStrings(value) { - return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1"); -} - -var clean_1$2 = clean$3; - -var _require$$0$builders$3 = doc.builders; -var hardline$7 = _require$$0$builders$3.hardline; -var literalline$3 = _require$$0$builders$3.literalline; -var concat$8 = _require$$0$builders$3.concat; -var markAsRoot$1 = _require$$0$builders$3.markAsRoot; -var mapDoc$3 = doc.utils.mapDoc; - -function embed$2(path, print, textToDoc -/*, options */ -) { - var node = path.getValue(); - - if (node.type === "yaml") { - return markAsRoot$1(concat$8(["---", hardline$7, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, { - parser: "yaml" - })) : "", "---", hardline$7])); - } - - return null; - - function replaceNewlinesWithLiterallines(doc$$2) { - return mapDoc$3(doc$$2, function (currentDoc) { - return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$8(currentDoc.split(/(\n)/g).map(function (v, i) { - return i % 2 === 0 ? v : literalline$3; - })) : currentDoc; - }); - } -} - -var embed_1$2 = embed$2; - -var DELIMITER_MAP = { - "---": "yaml", - "+++": "toml" -}; - -function parse$3(text) { - var delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|"); - var match = text.match(new RegExp("^(".concat(delimiterRegex, ")\\n(?:([\\s\\S]*?)\\n)?\\1(\\n|$)"))); - - if (match === null) { - return { - frontMatter: null, - content: text - }; - } - - var raw = match[0].trimRight(); - var delimiter = match[1]; - var value = match[2]; - return { - frontMatter: { - type: DELIMITER_MAP[delimiter], - value: value, - raw: raw - }, - content: text.slice(raw.length) - }; -} - -var frontMatter = parse$3; - -function hasPragma$1(text) { - return pragma.hasPragma(frontMatter(text).content); -} - -function insertPragma$3(text) { - var _parseFrontMatter = frontMatter(text), - frontMatter$$1 = _parseFrontMatter.frontMatter, - content = _parseFrontMatter.content; - - return (frontMatter$$1 ? frontMatter$$1.raw + "\n\n" : "") + pragma.insertPragma(content); -} - -var pragma$2 = { - hasPragma: hasPragma$1, - insertPragma: insertPragma$3 -}; - -var colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"]; - -function getAncestorCounter(path, typeOrTypes) { - var types = [].concat(typeOrTypes); - var counter = -1; - var ancestorNode; - - while (ancestorNode = path.getParentNode(++counter)) { - if (types.indexOf(ancestorNode.type) !== -1) { - return counter; - } - } - - return -1; -} - -function getAncestorNode$1(path, typeOrTypes) { - var counter = getAncestorCounter(path, typeOrTypes); - return counter === -1 ? null : path.getParentNode(counter); -} - -function getPropOfDeclNode$1(path) { - var declAncestorNode = getAncestorNode$1(path, "css-decl"); - return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase(); -} - -function isSCSS$1(parser, text) { - var hasExplicitParserChoice = parser === "less" || parser === "scss"; - var IS_POSSIBLY_SCSS = /(\w\s*: [^}:]+|#){|@import[^\n]+(url|,)/; - return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text); -} - -function isWideKeywords$1(value) { - return ["initial", "inherit", "unset", "revert"].indexOf(value.toLowerCase()) !== -1; -} - -function isKeyframeAtRuleKeywords$1(path, value) { - var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); - return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].indexOf(value.toLowerCase()) !== -1; -} - -function maybeToLowerCase$1(value) { - return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase(); -} - -function insideValueFunctionNode$1(path, functionName) { - var funcAncestorNode = getAncestorNode$1(path, "value-func"); - return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName; -} - -function insideICSSRuleNode$1(path) { - var ruleAncestorNode = getAncestorNode$1(path, "css-rule"); - return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export")); -} - -function insideAtRuleNode$1(path, atRuleNameOrAtRuleNames) { - var atRuleNames = [].concat(atRuleNameOrAtRuleNames); - var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); - return atRuleAncestorNode && atRuleNames.indexOf(atRuleAncestorNode.name.toLowerCase()) !== -1; -} - -function insideURLFunctionInImportAtRuleNode$1(path) { - var node = path.getValue(); - var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); - return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2; -} - -function isURLFunctionNode$1(node) { - return node.type === "value-func" && node.value.toLowerCase() === "url"; -} - -function isLastNode$1(path, node) { - var parentNode = path.getParentNode(); - - if (!parentNode) { - return false; - } - - var nodes = parentNode.nodes; - return nodes && nodes.indexOf(node) === nodes.length - 1; -} - -function isHTMLTag$1(value) { - return htmlTagNames$1.indexOf(value.toLowerCase()) !== -1; -} - -function isDetachedRulesetDeclarationNode$1(node) { - // If a Less file ends up being parsed with the SCSS parser, Less - // variable declarations will be parsed as atrules with names ending - // with a colon, so keep the original case then. - if (!node.selector) { - return false; - } - - return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value); -} - -function isForKeywordNode$1(node) { - return node.type === "value-word" && ["from", "through", "end"].indexOf(node.value) !== -1; -} - -function isIfElseKeywordNode$1(node) { - return node.type === "value-word" && ["and", "or", "not"].indexOf(node.value) !== -1; -} - -function isEachKeywordNode$1(node) { - return node.type === "value-word" && node.value === "in"; -} - -function isMultiplicationNode$1(node) { - return node.type === "value-operator" && node.value === "*"; -} - -function isDivisionNode$1(node) { - return node.type === "value-operator" && node.value === "/"; -} - -function isAdditionNode$1(node) { - return node.type === "value-operator" && node.value === "+"; -} - -function isSubtractionNode$1(node) { - return node.type === "value-operator" && node.value === "-"; -} - -function isModuloNode(node) { - return node.type === "value-operator" && node.value === "%"; -} - -function isMathOperatorNode$1(node) { - return isMultiplicationNode$1(node) || isDivisionNode$1(node) || isAdditionNode$1(node) || isSubtractionNode$1(node) || isModuloNode(node); -} - -function isEqualityOperatorNode$1(node) { - return node.type === "value-word" && ["==", "!="].indexOf(node.value) !== -1; -} - -function isRelationalOperatorNode$1(node) { - return node.type === "value-word" && ["<", ">", "<=", ">="].indexOf(node.value) !== -1; -} - -function isSCSSControlDirectiveNode$1(node) { - return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].indexOf(node.name) !== -1; -} - -function isSCSSNestedPropertyNode(node) { - if (!node.selector) { - return false; - } - - return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":"); -} - -function isDetachedRulesetCallNode$1(node) { - return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params); -} - -function isPostcssSimpleVarNode$1(currentNode, nextNode) { - return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before; -} - -function hasComposesNode$1(node) { - return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes"; -} - -function hasParensAroundNode$1(node) { - return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null; -} - -function hasEmptyRawBefore$1(node) { - return node.raws && node.raws.before === ""; -} - -function isKeyValuePairNode$1(node) { - return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon"; -} - -function isKeyValuePairInParenGroupNode(node) { - return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode$1(node.groups[0]); -} - -function isSCSSMapItemNode$1(path) { - var node = path.getValue(); // Ignore empty item (i.e. `$key: ()`) - - if (node.groups.length === 0) { - return false; - } - - var parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`) - - if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) { - return false; - } - - var declNode = getAncestorNode$1(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`) - - if (declNode && declNode.prop && declNode.prop.startsWith("$")) { - return true; - } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`) - - - if (isKeyValuePairInParenGroupNode(parentParentNode)) { - return true; - } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`) - - - if (parentParentNode.type === "value-func") { - return true; - } - - return false; -} - -function isInlineValueCommentNode$1(node) { - return node.type === "value-comment" && node.inline; -} - -function isHashNode$1(node) { - return node.type === "value-word" && node.value === "#"; -} - -function isLeftCurlyBraceNode$1(node) { - return node.type === "value-word" && node.value === "{"; -} - -function isRightCurlyBraceNode$1(node) { - return node.type === "value-word" && node.value === "}"; -} - -function isWordNode$1(node) { - return ["value-word", "value-atword"].indexOf(node.type) !== -1; -} - -function isColonNode$1(node) { - return node.type === "value-colon"; -} - -function isMediaAndSupportsKeywords$1(node) { - return node.value && ["not", "and", "or"].indexOf(node.value.toLowerCase()) !== -1; -} - -function isColorAdjusterFuncNode$1(node) { - if (node.type !== "value-func") { - return false; - } - - return colorAdjusterFunctions.indexOf(node.value.toLowerCase()) !== -1; -} - -var utils$4 = { - getAncestorCounter: getAncestorCounter, - getAncestorNode: getAncestorNode$1, - getPropOfDeclNode: getPropOfDeclNode$1, - maybeToLowerCase: maybeToLowerCase$1, - insideValueFunctionNode: insideValueFunctionNode$1, - insideICSSRuleNode: insideICSSRuleNode$1, - insideAtRuleNode: insideAtRuleNode$1, - insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1, - isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1, - isHTMLTag: isHTMLTag$1, - isWideKeywords: isWideKeywords$1, - isSCSS: isSCSS$1, - isLastNode: isLastNode$1, - isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1, - isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1, - isRelationalOperatorNode: isRelationalOperatorNode$1, - isEqualityOperatorNode: isEqualityOperatorNode$1, - isMultiplicationNode: isMultiplicationNode$1, - isDivisionNode: isDivisionNode$1, - isAdditionNode: isAdditionNode$1, - isSubtractionNode: isSubtractionNode$1, - isModuloNode: isModuloNode, - isMathOperatorNode: isMathOperatorNode$1, - isEachKeywordNode: isEachKeywordNode$1, - isForKeywordNode: isForKeywordNode$1, - isURLFunctionNode: isURLFunctionNode$1, - isIfElseKeywordNode: isIfElseKeywordNode$1, - hasComposesNode: hasComposesNode$1, - hasParensAroundNode: hasParensAroundNode$1, - hasEmptyRawBefore: hasEmptyRawBefore$1, - isSCSSNestedPropertyNode: isSCSSNestedPropertyNode, - isDetachedRulesetCallNode: isDetachedRulesetCallNode$1, - isPostcssSimpleVarNode: isPostcssSimpleVarNode$1, - isKeyValuePairNode: isKeyValuePairNode$1, - isKeyValuePairInParenGroupNode: isKeyValuePairInParenGroupNode, - isSCSSMapItemNode: isSCSSMapItemNode$1, - isInlineValueCommentNode: isInlineValueCommentNode$1, - isHashNode: isHashNode$1, - isLeftCurlyBraceNode: isLeftCurlyBraceNode$1, - isRightCurlyBraceNode: isRightCurlyBraceNode$1, - isWordNode: isWordNode$1, - isColonNode: isColonNode$1, - isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1, - isColorAdjusterFuncNode: isColorAdjusterFuncNode$1 -}; - -var insertPragma$2 = pragma$2.insertPragma; -var printNumber$2 = util.printNumber; -var printString$2 = util.printString; -var hasIgnoreComment$2 = util.hasIgnoreComment; -var hasNewline$3 = util.hasNewline; -var isNextLineEmpty$3 = utilShared.isNextLineEmpty; -var _require$$3$builders = doc.builders; -var concat$7 = _require$$3$builders.concat; -var join$5 = _require$$3$builders.join; -var line$4 = _require$$3$builders.line; -var hardline$6 = _require$$3$builders.hardline; -var softline$3 = _require$$3$builders.softline; -var group$5 = _require$$3$builders.group; -var fill$3 = _require$$3$builders.fill; -var indent$5 = _require$$3$builders.indent; -var dedent$3 = _require$$3$builders.dedent; -var ifBreak$2 = _require$$3$builders.ifBreak; -var removeLines$2 = doc.utils.removeLines; -var getAncestorNode = utils$4.getAncestorNode; -var getPropOfDeclNode = utils$4.getPropOfDeclNode; -var maybeToLowerCase = utils$4.maybeToLowerCase; -var insideValueFunctionNode = utils$4.insideValueFunctionNode; -var insideICSSRuleNode = utils$4.insideICSSRuleNode; -var insideAtRuleNode = utils$4.insideAtRuleNode; -var insideURLFunctionInImportAtRuleNode = utils$4.insideURLFunctionInImportAtRuleNode; -var isKeyframeAtRuleKeywords = utils$4.isKeyframeAtRuleKeywords; -var isHTMLTag = utils$4.isHTMLTag; -var isWideKeywords = utils$4.isWideKeywords; -var isSCSS = utils$4.isSCSS; -var isLastNode = utils$4.isLastNode; -var isSCSSControlDirectiveNode = utils$4.isSCSSControlDirectiveNode; -var isDetachedRulesetDeclarationNode = utils$4.isDetachedRulesetDeclarationNode; -var isRelationalOperatorNode = utils$4.isRelationalOperatorNode; -var isEqualityOperatorNode = utils$4.isEqualityOperatorNode; -var isMultiplicationNode = utils$4.isMultiplicationNode; -var isDivisionNode = utils$4.isDivisionNode; -var isAdditionNode = utils$4.isAdditionNode; -var isSubtractionNode = utils$4.isSubtractionNode; -var isMathOperatorNode = utils$4.isMathOperatorNode; -var isEachKeywordNode = utils$4.isEachKeywordNode; -var isForKeywordNode = utils$4.isForKeywordNode; -var isURLFunctionNode = utils$4.isURLFunctionNode; -var isIfElseKeywordNode = utils$4.isIfElseKeywordNode; -var hasComposesNode = utils$4.hasComposesNode; -var hasParensAroundNode = utils$4.hasParensAroundNode; -var hasEmptyRawBefore = utils$4.hasEmptyRawBefore; -var isKeyValuePairNode = utils$4.isKeyValuePairNode; -var isDetachedRulesetCallNode = utils$4.isDetachedRulesetCallNode; -var isPostcssSimpleVarNode = utils$4.isPostcssSimpleVarNode; -var isSCSSMapItemNode = utils$4.isSCSSMapItemNode; -var isInlineValueCommentNode = utils$4.isInlineValueCommentNode; -var isHashNode = utils$4.isHashNode; -var isLeftCurlyBraceNode = utils$4.isLeftCurlyBraceNode; -var isRightCurlyBraceNode = utils$4.isRightCurlyBraceNode; -var isWordNode = utils$4.isWordNode; -var isColonNode = utils$4.isColonNode; -var isMediaAndSupportsKeywords = utils$4.isMediaAndSupportsKeywords; -var isColorAdjusterFuncNode = utils$4.isColorAdjusterFuncNode; - -function shouldPrintComma$1(options) { - switch (options.trailingComma) { - case "all": - case "es5": - return true; - - case "none": - default: - return false; - } -} - -function genericPrint$3(path, options, print) { - var node = path.getValue(); - /* istanbul ignore if */ - - if (!node) { - return ""; - } - - if (typeof node === "string") { - return node; - } - - switch (node.type) { - case "yaml": - case "toml": - return concat$7([node.raw, hardline$6]); - - case "css-root": - { - var nodes = printNodeSequence(path, options, print); - - if (nodes.parts.length) { - return concat$7([nodes, hardline$6]); - } - - return nodes; - } - - case "css-comment": - { - if (node.raws.content) { - return node.raws.content; - } - - var text = options.originalText.slice(options.locStart(node), options.locEnd(node)); - var rawText = node.raws.text || node.text; // Workaround a bug where the location is off. - // https://github.com/postcss/postcss-scss/issues/63 - - if (text.indexOf(rawText) === -1) { - if (node.raws.inline) { - return concat$7(["// ", rawText]); - } - - return concat$7(["/* ", rawText, " */"]); - } - - return text; - } - - case "css-rule": - { - return concat$7([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$7([" {", node.nodes.length > 0 ? indent$5(concat$7([hardline$6, printNodeSequence(path, options, print)])) : "", hardline$6, "}", isDetachedRulesetDeclarationNode(node) ? ";" : ""]) : ";"]); - } - - case "css-decl": - { - return concat$7([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode(path) ? node.prop : maybeToLowerCase(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode(node) ? removeLines$2(path.call(print, "value")) : path.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$7([" {", indent$5(concat$7([softline$3, printNodeSequence(path, options, print)])), softline$3, "}"]) : ";"]); - } - - case "css-atrule": - { - return concat$7(["@", // If a Less file ends up being parsed with the SCSS parser, Less - // variable declarations will be parsed as at-rules with names ending - // with a colon, so keep the original case then. - isDetachedRulesetCallNode(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase(node.name), node.params ? concat$7([isDetachedRulesetCallNode(node) ? "" : " ", path.call(print, "params")]) : "", node.selector ? indent$5(concat$7([" ", path.call(print, "selector")])) : "", node.value ? group$5(concat$7([" ", path.call(print, "value"), isSCSSControlDirectiveNode(node) ? hasParensAroundNode(node) ? " " : line$4 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$7([isSCSSControlDirectiveNode(node) ? "" : " ", "{", indent$5(concat$7([node.nodes.length > 0 ? softline$3 : "", printNodeSequence(path, options, print)])), softline$3, "}"]) : ";"]); - } - // postcss-media-query-parser - - case "media-query-list": - { - var parts = []; - path.each(function (childPath) { - var node = childPath.getValue(); - - if (node.type === "media-query" && node.value === "") { - return; - } - - parts.push(childPath.call(print)); - }, "nodes"); - return group$5(indent$5(join$5(line$4, parts))); - } - - case "media-query": - { - return concat$7([join$5(" ", path.map(print, "nodes")), isLastNode(path, node) ? "" : ","]); - } - - case "media-type": - { - return adjustNumbers(adjustStrings(node.value, options)); - } - - case "media-feature-expression": - { - if (!node.nodes) { - return node.value; - } - - return concat$7(["(", concat$7(path.map(print, "nodes")), ")"]); - } - - case "media-feature": - { - return maybeToLowerCase(adjustStrings(node.value.replace(/ +/g, " "), options)); - } - - case "media-colon": - { - return concat$7([node.value, " "]); - } - - case "media-value": - { - return adjustNumbers(adjustStrings(node.value, options)); - } - - case "media-keyword": - { - return adjustStrings(node.value, options); - } - - case "media-url": - { - return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options); - } - - case "media-unknown": - { - return node.value; - } - // postcss-selector-parser - - case "selector-root": - { - return group$5(concat$7([insideAtRuleNode(path, "custom-selector") ? concat$7([getAncestorNode(path, "css-atrule").customSelector, line$4]) : "", join$5(concat$7([",", insideAtRuleNode(path, ["extend", "custom-selector", "nest"]) ? line$4 : hardline$6]), path.map(print, "nodes"))])); - } - - case "selector-selector": - { - return group$5(indent$5(concat$7(path.map(print, "nodes")))); - } - - case "selector-comment": - { - return node.value; - } - - case "selector-string": - { - return adjustStrings(node.value, options); - } - - case "selector-tag": - { - var parentNode = path.getParentNode(); - var index = parentNode && parentNode.nodes.indexOf(node); - var prevNode = index && parentNode.nodes[index - 1]; - return concat$7([node.namespace ? concat$7([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isHTMLTag(node.value) || isKeyframeAtRuleKeywords(path, node.value) ? node.value.toLowerCase() : node.value)]); - } - - case "selector-id": - { - return concat$7(["#", node.value]); - } - - case "selector-class": - { - return concat$7([".", adjustNumbers(adjustStrings(node.value, options))]); - } - - case "selector-attribute": - { - return concat$7(["[", node.namespace ? concat$7([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]); - } - - case "selector-combinator": - { - if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") { - var _parentNode = path.getParentNode(); - - var _leading = _parentNode.type === "selector-selector" && _parentNode.nodes[0] === node ? "" : line$4; - - return concat$7([_leading, node.value, isLastNode(path, node) ? "" : " "]); - } - - var leading = node.value.trim().startsWith("(") ? line$4 : ""; - var value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$4; - return concat$7([leading, value]); - } - - case "selector-universal": - { - return concat$7([node.namespace ? concat$7([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]); - } - - case "selector-pseudo": - { - return concat$7([maybeToLowerCase(node.value), node.nodes && node.nodes.length > 0 ? concat$7(["(", join$5(", ", path.map(print, "nodes")), ")"]) : ""]); - } - - case "selector-nesting": - { - return node.value; - } - - case "selector-unknown": - { - var ruleAncestorNode = getAncestorNode(path, "css-rule"); // Nested SCSS property - - if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) { - return adjustNumbers(adjustStrings(maybeToLowerCase(node.value), options)); - } - - return node.value; - } - // postcss-values-parser - - case "value-value": - case "value-root": - { - return path.call(print, "group"); - } - - case "value-comment": - { - return concat$7([node.inline ? "//" : "/*", node.value, node.inline ? "" : "*/"]); - } - - case "value-comma_group": - { - var _parentNode2 = path.getParentNode(); - - var parentParentNode = path.getParentNode(1); - var declAncestorProp = getPropOfDeclNode(path); - var isGridValue = declAncestorProp && _parentNode2.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template")); - var atRuleAncestorNode = getAncestorNode(path, "css-atrule"); - var isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode(atRuleAncestorNode); - var printed = path.map(print, "groups"); - var _parts = []; - var insideURLFunction = insideValueFunctionNode(path, "url"); - var insideSCSSInterpolationInString = false; - var didBreak = false; - - for (var i = 0; i < node.groups.length; ++i) { - _parts.push(printed[i]); // Ignore value inside `url()` - - - if (insideURLFunction) { - continue; - } - - var iPrevNode = node.groups[i - 1]; - var iNode = node.groups[i]; - var iNextNode = node.groups[i + 1]; - var iNextNextNode = node.groups[i + 2]; // Ignore after latest node (i.e. before semicolon) - - if (!iNextNode) { - continue; - } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`) - - - var isStartSCSSinterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{"); - var isEndingSCSSinterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}"); - - if (isStartSCSSinterpolationInString || isEndingSCSSinterpolationInString) { - insideSCSSInterpolationInString = !insideSCSSInterpolationInString; - continue; - } - - if (insideSCSSInterpolationInString) { - continue; - } // Ignore colon (i.e. `:`) - - - if (isColonNode(iNode) || isColonNode(iNextNode)) { - continue; - } // Ignore `@` in Less (i.e. `@@var;`) - - - if (iNode.type === "value-atword" && iNode.value === "") { - continue; - } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`) - - - if (iNode.value === "~") { - continue; - } // Ignore `\` (i.e. `$variable: \@small;`) - - - if (iNode.value === "\\") { - continue; - } // Ignore `$$` (i.e. `background-color: $$(style)Color;`) - - - if (isPostcssSimpleVarNode(iNode, iNextNode)) { - continue; - } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`) - - - if (isHashNode(iNode) || isLeftCurlyBraceNode(iNode) || isRightCurlyBraceNode(iNextNode) || isLeftCurlyBraceNode(iNextNode) && hasEmptyRawBefore(iNextNode) || isRightCurlyBraceNode(iNode) && hasEmptyRawBefore(iNextNode)) { - continue; - } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`) - - - if (iNode.value === "--" && isHashNode(iNextNode)) { - continue; - } // Formatting math operations - - - var isMathOperator = isMathOperatorNode(iNode); - var isNextMathOperator = isMathOperatorNode(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is - // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`) - // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`) - - if ((isMathOperator && isHashNode(iNextNode) || isNextMathOperator && isRightCurlyBraceNode(iNode)) && hasEmptyRawBefore(iNextNode)) { - continue; - } // Print spaces before and after addition and subtraction math operators as is in `calc` function - // due to the fact that it is not valid syntax - // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`) - - - if (insideValueFunctionNode(path, "calc") && (isAdditionNode(iNode) || isAdditionNode(iNextNode) || isSubtractionNode(iNode) || isSubtractionNode(iNextNode)) && hasEmptyRawBefore(iNextNode)) { - continue; - } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`) - // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is. - - - var isColorAdjusterNode = (isAdditionNode(iNode) || isSubtractionNode(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode(parentParentNode) && !hasEmptyRawBefore(iNextNode); - var requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode(iNextNextNode) || iNode.type === "value-func" || isWordNode(iNode); - var requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode(iPrevNode); // Formatting `/`, `+`, `-` sign - - if (!(isMultiplicationNode(iNextNode) || isMultiplicationNode(iNode)) && !insideValueFunctionNode(path, "calc") && !isColorAdjusterNode && (isDivisionNode(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode(iNode) && !requireSpaceAfterOperator || isAdditionNode(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode(iNode) && !requireSpaceAfterOperator || isSubtractionNode(iNextNode) || isSubtractionNode(iNode)) && (hasEmptyRawBefore(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode(iPrevNode)))) { - continue; - } // Ignore inline comment, they already contain newline at end (i.e. `// Comment`) - // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`) - - - var isInlineComment = isInlineValueCommentNode(iNode); - - if (iPrevNode && isInlineValueCommentNode(iPrevNode) || isInlineComment || isInlineValueCommentNode(iNextNode)) { - if (isInlineComment) { - _parts.push(hardline$6); - } - - continue; - } // Handle keywords in SCSS control directive - - - if (isControlDirective && (isEqualityOperatorNode(iNextNode) || isRelationalOperatorNode(iNextNode) || isIfElseKeywordNode(iNextNode) || isEachKeywordNode(iNode) || isForKeywordNode(iNode))) { - _parts.push(" "); - - continue; - } // At-rule `namespace` should be in one line - - - if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") { - _parts.push(" "); - - continue; - } // Formatting `grid` property - - - if (isGridValue) { - if (iNode.source.start.line !== iNextNode.source.start.line) { - _parts.push(hardline$6); - - didBreak = true; - } else { - _parts.push(" "); - } - - continue; - } // Add `space` before next math operation - // Note: `grip` property have `/` delimiter and it is not math operation, so - // `grid` property handles above - - - if (isNextMathOperator) { - _parts.push(" "); - - continue; - } // Be default all values go through `line` - - - _parts.push(line$4); - } - - if (didBreak) { - _parts.unshift(hardline$6); - } - - if (isControlDirective) { - return group$5(indent$5(concat$7(_parts))); - } // Indent is not needed for import url when url is very long - // and node has two groups - // when type is value-comma_group - // example @import url("verylongurl") projection,tv - - - if (insideURLFunctionInImportAtRuleNode(path)) { - return group$5(fill$3(_parts)); - } - - return group$5(indent$5(fill$3(_parts))); - } - - case "value-paren_group": - { - var _parentNode3 = path.getParentNode(); - - if (_parentNode3 && isURLFunctionNode(_parentNode3) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) { - return concat$7([node.open ? path.call(print, "open") : "", join$5(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]); - } - - if (!node.open) { - var _printed = path.map(print, "groups"); - - var res = []; - - for (var _i = 0; _i < _printed.length; _i++) { - if (_i !== 0) { - res.push(concat$7([",", line$4])); - } - - res.push(_printed[_i]); - } - - return group$5(indent$5(fill$3(res))); - } - - var isSCSSMapItem = isSCSSMapItemNode(path); - return group$5(concat$7([node.open ? path.call(print, "open") : "", indent$5(concat$7([softline$3, join$5(concat$7([",", line$4]), path.map(function (childPath) { - var node = childPath.getValue(); - var printed = print(childPath); // Key/Value pair in open paren already indented - - if (isKeyValuePairNode(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") { - printed.contents.contents.parts[1] = group$5(printed.contents.contents.parts[1]); - return group$5(dedent$3(printed)); - } - - return printed; - }, "groups"))])), ifBreak$2(isSCSS(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$1(options) ? "," : ""), softline$3, node.close ? path.call(print, "close") : ""]), { - shouldBreak: isSCSSMapItem - }); - } - - case "value-func": - { - return concat$7([node.value, insideAtRuleNode(path, "supports") && isMediaAndSupportsKeywords(node) ? " " : "", path.call(print, "group")]); - } - - case "value-paren": - { - return node.value; - } - - case "value-number": - { - return concat$7([printCssNumber(node.value), maybeToLowerCase(node.unit)]); - } - - case "value-operator": - { - return node.value; - } - - case "value-word": - { - if (node.isColor && node.isHex || isWideKeywords(node.value)) { - return node.value.toLowerCase(); - } - - return node.value; - } - - case "value-colon": - { - return concat$7([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`) - insideValueFunctionNode(path, "url") ? "" : line$4]); - } - - case "value-comma": - { - return concat$7([node.value, " "]); - } - - case "value-string": - { - return printString$2(node.raws.quote + node.value + node.raws.quote, options); - } - - case "value-atword": - { - return concat$7(["@", node.value]); - } - - case "value-unicode-range": - { - return node.value; - } - - case "value-unknown": - { - return node.value; - } - - default: - /* istanbul ignore next */ - throw new Error("Unknown postcss type ".concat(JSON.stringify(node.type))); - } -} - -function printNodeSequence(path, options, print) { - var node = path.getValue(); - var parts = []; - var i = 0; - path.map(function (pathChild) { - var prevNode = node.nodes[i - 1]; - - if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") { - var childNode = pathChild.getValue(); - parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode))); - } else { - parts.push(pathChild.call(print)); - } - - if (i !== node.nodes.length - 1) { - if (node.nodes[i + 1].type === "css-comment" && !hasNewline$3(options.originalText, options.locStart(node.nodes[i + 1]), { - backwards: true - }) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml" || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") { - parts.push(" "); - } else { - parts.push(hardline$6); - - if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") { - parts.push(hardline$6); - } - } - } - - i++; - }, "nodes"); - return concat$7(parts); -} - -var STRING_REGEX = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g; -var NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g; -var STANDARD_UNIT_REGEX = /[a-zA-Z]+/g; -var WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g; -var ADJUST_NUMBERS_REGEX = RegExp(STRING_REGEX.source + "|" + "(".concat(WORD_PART_REGEX.source, ")?") + "(".concat(NUMBER_REGEX.source, ")") + "(".concat(STANDARD_UNIT_REGEX.source, ")?"), "g"); - -function adjustStrings(value, options) { - return value.replace(STRING_REGEX, function (match) { - return printString$2(match, options); - }); -} - -function quoteAttributeValue(value, options) { - var quote = options.singleQuote ? "'" : '"'; - return value.includes('"') || value.includes("'") ? value : quote + value + quote; -} - -function adjustNumbers(value) { - return value.replace(ADJUST_NUMBERS_REGEX, function (match, quote, wordPart, number, unit) { - return !wordPart && number ? (wordPart || "") + printCssNumber(number) + maybeToLowerCase(unit || "") : match; - }); -} - -function printCssNumber(rawNumber) { - return printNumber$2(rawNumber) // Remove trailing `.0`. - .replace(/\.0(?=$|e)/, ""); -} - -var printerPostcss = { - print: genericPrint$3, - embed: embed_1$2, - insertPragma: insertPragma$2, - hasPrettierIgnore: hasIgnoreComment$2, - massageAstNode: clean_1$2 -}; - -var options$6 = { - singleQuote: commonOptions.singleQuote -}; - -var name$7 = "CSS"; -var type$6 = "markup"; -var tmScope$6 = "source.css"; -var aceMode$6 = "css"; -var codemirrorMode$6 = "css"; -var codemirrorMimeType$6 = "text/css"; -var color$2 = "#563d7c"; -var extensions$6 = [".css"]; -var languageId$6 = 50; -var css$2 = { - name: name$7, - type: type$6, - tmScope: tmScope$6, - aceMode: aceMode$6, - codemirrorMode: codemirrorMode$6, - codemirrorMimeType: codemirrorMimeType$6, - color: color$2, - extensions: extensions$6, - languageId: languageId$6 -}; - -var css$3 = Object.freeze({ - name: name$7, - type: type$6, - tmScope: tmScope$6, - aceMode: aceMode$6, - codemirrorMode: codemirrorMode$6, - codemirrorMimeType: codemirrorMimeType$6, - color: color$2, - extensions: extensions$6, - languageId: languageId$6, - default: css$2 -}); - -var name$8 = "PostCSS"; -var type$7 = "markup"; -var tmScope$7 = "source.postcss"; -var group$6 = "CSS"; -var extensions$7 = [".pcss"]; -var aceMode$7 = "text"; -var languageId$7 = 262764437; -var postcss = { - name: name$8, - type: type$7, - tmScope: tmScope$7, - group: group$6, - extensions: extensions$7, - aceMode: aceMode$7, - languageId: languageId$7 -}; - -var postcss$1 = Object.freeze({ - name: name$8, - type: type$7, - tmScope: tmScope$7, - group: group$6, - extensions: extensions$7, - aceMode: aceMode$7, - languageId: languageId$7, - default: postcss -}); - -var name$9 = "Less"; -var type$8 = "markup"; -var group$7 = "CSS"; -var extensions$8 = [".less"]; -var tmScope$8 = "source.css.less"; -var aceMode$8 = "less"; -var codemirrorMode$7 = "css"; -var codemirrorMimeType$7 = "text/css"; -var languageId$8 = 198; -var less = { - name: name$9, - type: type$8, - group: group$7, - extensions: extensions$8, - tmScope: tmScope$8, - aceMode: aceMode$8, - codemirrorMode: codemirrorMode$7, - codemirrorMimeType: codemirrorMimeType$7, - languageId: languageId$8 -}; - -var less$1 = Object.freeze({ - name: name$9, - type: type$8, - group: group$7, - extensions: extensions$8, - tmScope: tmScope$8, - aceMode: aceMode$8, - codemirrorMode: codemirrorMode$7, - codemirrorMimeType: codemirrorMimeType$7, - languageId: languageId$8, - default: less -}); - -var name$10 = "SCSS"; -var type$9 = "markup"; -var tmScope$9 = "source.scss"; -var group$8 = "CSS"; -var aceMode$9 = "scss"; -var codemirrorMode$8 = "css"; -var codemirrorMimeType$8 = "text/x-scss"; -var extensions$9 = [".scss"]; -var languageId$9 = 329; -var scss = { - name: name$10, - type: type$9, - tmScope: tmScope$9, - group: group$8, - aceMode: aceMode$9, - codemirrorMode: codemirrorMode$8, - codemirrorMimeType: codemirrorMimeType$8, - extensions: extensions$9, - languageId: languageId$9 -}; - -var scss$1 = Object.freeze({ - name: name$10, - type: type$9, - tmScope: tmScope$9, - group: group$8, - aceMode: aceMode$9, - codemirrorMode: codemirrorMode$8, - codemirrorMimeType: codemirrorMimeType$8, - extensions: extensions$9, - languageId: languageId$9, - default: scss -}); - -var require$$0$12 = ( css$3 && css$2 ) || css$3; - -var require$$1$7 = ( postcss$1 && postcss ) || postcss$1; - -var require$$2$7 = ( less$1 && less ) || less$1; - -var require$$3$2 = ( scss$1 && scss ) || scss$1; - -var languages$1 = [languageExtend({}, require$$0$12, { - since: "1.4.0", - parsers: ["css"], - vscodeLanguageIds: ["css"] -}), languageExtend({}, require$$1$7, { - since: "1.4.0", - parsers: ["css"], - extensions: [".postcss"], - vscodeLanguageIds: ["postcss"] -}), languageExtend({}, require$$2$7, { - since: "1.4.0", - parsers: ["less"], - vscodeLanguageIds: ["less"] -}), languageExtend({}, require$$3$2, { - since: "1.4.0", - parsers: ["scss"], - vscodeLanguageIds: ["scss"] -})]; -var printers$1 = { - postcss: printerPostcss -}; -var languageCss = { - languages: languages$1, - options: options$6, - printers: printers$1 -}; - -function hasPragma$2(text) { - return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text); -} - -function insertPragma$5(text) { - return "# @format\n\n" + text; -} - -var pragma$4 = { - hasPragma: hasPragma$2, - insertPragma: insertPragma$5 -}; - -var _require$$0$builders$4 = doc.builders; -var concat$9 = _require$$0$builders$4.concat; -var join$6 = _require$$0$builders$4.join; -var hardline$8 = _require$$0$builders$4.hardline; -var line$5 = _require$$0$builders$4.line; -var softline$4 = _require$$0$builders$4.softline; -var group$9 = _require$$0$builders$4.group; -var indent$6 = _require$$0$builders$4.indent; -var ifBreak$3 = _require$$0$builders$4.ifBreak; -var hasIgnoreComment$3 = util.hasIgnoreComment; -var isNextLineEmpty$4 = utilShared.isNextLineEmpty; -var insertPragma$4 = pragma$4.insertPragma; - -function genericPrint$4(path, options, print) { - var n = path.getValue(); - - if (!n) { - return ""; - } - - if (typeof n === "string") { - return n; - } - - switch (n.kind) { - case "Document": - { - var parts = []; - path.map(function (pathChild, index) { - parts.push(concat$9([pathChild.call(print)])); - - if (index !== n.definitions.length - 1) { - parts.push(hardline$8); - - if (isNextLineEmpty$4(options.originalText, pathChild.getValue(), options)) { - parts.push(hardline$8); - } - } - }, "definitions"); - return concat$9([concat$9(parts), hardline$8]); - } - - case "OperationDefinition": - { - var hasOperation = options.originalText[options.locStart(n)] !== "{"; - var hasName = !!n.name; - return concat$9([hasOperation ? n.operation : "", hasOperation && hasName ? concat$9([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$9(concat$9(["(", indent$6(concat$9([softline$4, join$6(concat$9([ifBreak$3("", ", "), softline$4]), path.map(print, "variableDefinitions"))])), softline$4, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]); - } - - case "FragmentDefinition": - { - return concat$9(["fragment ", path.call(print, "name"), " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); - } - - case "SelectionSet": - { - return concat$9(["{", indent$6(concat$9([hardline$8, join$6(hardline$8, path.call(function (selectionsPath) { - return printSequence(selectionsPath, options, print); - }, "selections"))])), hardline$8, "}"]); - } - - case "Field": - { - return group$9(concat$9([n.alias ? concat$9([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$9(concat$9(["(", indent$6(concat$9([softline$4, join$6(concat$9([ifBreak$3("", ", "), softline$4]), path.call(function (argsPath) { - return printSequence(argsPath, options, print); - }, "arguments"))])), softline$4, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")])); - } - - case "Name": - { - return n.value; - } - - case "StringValue": - { - if (n.block) { - return concat$9(['"""', hardline$8, join$6(hardline$8, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$8, '"""']); - } - - return concat$9(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']); - } - - case "IntValue": - case "FloatValue": - case "EnumValue": - { - return n.value; - } - - case "BooleanValue": - { - return n.value ? "true" : "false"; - } - - case "NullValue": - { - return "null"; - } - - case "Variable": - { - return concat$9(["$", path.call(print, "name")]); - } - - case "ListValue": - { - return group$9(concat$9(["[", indent$6(concat$9([softline$4, join$6(concat$9([ifBreak$3("", ", "), softline$4]), path.map(print, "values"))])), softline$4, "]"])); - } - - case "ObjectValue": - { - return group$9(concat$9(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$6(concat$9([softline$4, join$6(concat$9([ifBreak$3("", ", "), softline$4]), path.map(print, "fields"))])), softline$4, ifBreak$3("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"])); - } - - case "ObjectField": - case "Argument": - { - return concat$9([path.call(print, "name"), ": ", path.call(print, "value")]); - } - - case "Directive": - { - return concat$9(["@", path.call(print, "name"), n.arguments.length > 0 ? group$9(concat$9(["(", indent$6(concat$9([softline$4, join$6(concat$9([ifBreak$3("", ", "), softline$4]), path.call(function (argsPath) { - return printSequence(argsPath, options, print); - }, "arguments"))])), softline$4, ")"])) : ""]); - } - - case "NamedType": - { - return path.call(print, "name"); - } - - case "VariableDefinition": - { - return concat$9([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$9([" = ", path.call(print, "defaultValue")]) : ""]); - } - - case "TypeExtensionDefinition": - { - return concat$9(["extend ", path.call(print, "definition")]); - } - - case "ObjectTypeExtension": - case "ObjectTypeDefinition": - { - return concat$9([path.call(print, "description"), n.description ? hardline$8 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$9([" implements ", join$6(determineInterfaceSeparator(options.originalText.substr(options.locStart(n), options.locEnd(n))), path.map(print, "interfaces"))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$9([" {", indent$6(concat$9([hardline$8, join$6(hardline$8, path.call(function (fieldsPath) { - return printSequence(fieldsPath, options, print); - }, "fields"))])), hardline$8, "}"]) : ""]); - } - - case "FieldDefinition": - { - return concat$9([path.call(print, "description"), n.description ? hardline$8 : "", path.call(print, "name"), n.arguments.length > 0 ? group$9(concat$9(["(", indent$6(concat$9([softline$4, join$6(concat$9([ifBreak$3("", ", "), softline$4]), path.call(function (argsPath) { - return printSequence(argsPath, options, print); - }, "arguments"))])), softline$4, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]); - } - - case "DirectiveDefinition": - { - return concat$9([path.call(print, "description"), n.description ? hardline$8 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$9(concat$9(["(", indent$6(concat$9([softline$4, join$6(concat$9([ifBreak$3("", ", "), softline$4]), path.call(function (argsPath) { - return printSequence(argsPath, options, print); - }, "arguments"))])), softline$4, ")"])) : "", concat$9([" on ", join$6(" | ", path.map(print, "locations"))])]); - } - - case "EnumTypeExtension": - case "EnumTypeDefinition": - { - return concat$9([path.call(print, "description"), n.description ? hardline$8 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$9([" {", indent$6(concat$9([hardline$8, join$6(hardline$8, path.call(function (valuesPath) { - return printSequence(valuesPath, options, print); - }, "values"))])), hardline$8, "}"]) : ""]); - } - - case "EnumValueDefinition": - { - return concat$9([path.call(print, "description"), n.description ? hardline$8 : "", path.call(print, "name"), printDirectives(path, print, n)]); - } - - case "InputValueDefinition": - { - return concat$9([path.call(print, "description"), n.description ? n.description.block ? hardline$8 : line$5 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$9([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); - } - - case "InputObjectTypeExtension": - case "InputObjectTypeDefinition": - { - return concat$9([path.call(print, "description"), n.description ? hardline$8 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$9([" {", indent$6(concat$9([hardline$8, join$6(hardline$8, path.call(function (fieldsPath) { - return printSequence(fieldsPath, options, print); - }, "fields"))])), hardline$8, "}"]) : ""]); - } - - case "SchemaDefinition": - { - return concat$9(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$6(concat$9([hardline$8, join$6(hardline$8, path.call(function (opsPath) { - return printSequence(opsPath, options, print); - }, "operationTypes"))])) : "", hardline$8, "}"]); - } - - case "OperationTypeDefinition": - { - return concat$9([path.call(print, "operation"), ": ", path.call(print, "type")]); - } - - case "InterfaceTypeExtension": - case "InterfaceTypeDefinition": - { - return concat$9([path.call(print, "description"), n.description ? hardline$8 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$9([" {", indent$6(concat$9([hardline$8, join$6(hardline$8, path.call(function (fieldsPath) { - return printSequence(fieldsPath, options, print); - }, "fields"))])), hardline$8, "}"]) : ""]); - } - - case "FragmentSpread": - { - return concat$9(["...", path.call(print, "name"), printDirectives(path, print, n)]); - } - - case "InlineFragment": - { - return concat$9(["...", n.typeCondition ? concat$9([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); - } - - case "UnionTypeExtension": - case "UnionTypeDefinition": - { - return group$9(concat$9([path.call(print, "description"), n.description ? hardline$8 : "", group$9(concat$9([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$9([" =", ifBreak$3("", " "), indent$6(concat$9([ifBreak$3(concat$9([line$5, " "])), join$6(concat$9([line$5, "| "]), path.map(print, "types"))]))]) : ""]))])); - } - - case "ScalarTypeExtension": - case "ScalarTypeDefinition": - { - return concat$9([path.call(print, "description"), n.description ? hardline$8 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]); - } - - case "NonNullType": - { - return concat$9([path.call(print, "type"), "!"]); - } - - case "ListType": - { - return concat$9(["[", path.call(print, "type"), "]"]); - } - - default: - /* istanbul ignore next */ - throw new Error("unknown graphql type: " + JSON.stringify(n.kind)); - } -} - -function printDirectives(path, print, n) { - if (n.directives.length === 0) { - return ""; - } - - return concat$9([" ", group$9(indent$6(concat$9([softline$4, join$6(concat$9([ifBreak$3("", " "), softline$4]), path.map(print, "directives"))])))]); -} - -function printSequence(sequencePath, options, print) { - var count = sequencePath.getValue().length; - return sequencePath.map(function (path, i) { - var printed = print(path); - - if (isNextLineEmpty$4(options.originalText, path.getValue(), options) && i < count - 1) { - return concat$9([printed, hardline$8]); - } - - return printed; - }); -} - -function canAttachComment$1(node) { - return node.kind && node.kind !== "Comment"; -} - -function printComment$2(commentPath) { - var comment = commentPath.getValue(); - - if (comment.kind === "Comment") { - return "#" + comment.value.trimRight(); - } - - throw new Error("Not a comment: " + JSON.stringify(comment)); -} - -function determineInterfaceSeparator(originalSource) { - var start = originalSource.indexOf("implements"); - - if (start === -1) { - throw new Error("Must implement interfaces: " + originalSource); - } - - var end = originalSource.indexOf("{"); - - if (end === -1) { - end = originalSource.length; - } - - return originalSource.substr(start, end).includes("&") ? " & " : ", "; -} - -function clean$5(node, newNode -/*, parent*/ -) { - delete newNode.loc; - delete newNode.comments; -} - -var printerGraphql = { - print: genericPrint$4, - massageAstNode: clean$5, - hasPrettierIgnore: hasIgnoreComment$3, - insertPragma: insertPragma$4, - printComment: printComment$2, - canAttachComment: canAttachComment$1 -}; - -var options$9 = { - bracketSpacing: commonOptions.bracketSpacing -}; - -var name$11 = "GraphQL"; -var type$10 = "data"; -var extensions$10 = [".graphql", ".gql"]; -var tmScope$10 = "source.graphql"; -var aceMode$10 = "text"; -var languageId$10 = 139; -var graphql = { - name: name$11, - type: type$10, - extensions: extensions$10, - tmScope: tmScope$10, - aceMode: aceMode$10, - languageId: languageId$10 -}; - -var graphql$1 = Object.freeze({ - name: name$11, - type: type$10, - extensions: extensions$10, - tmScope: tmScope$10, - aceMode: aceMode$10, - languageId: languageId$10, - default: graphql -}); - -var require$$0$13 = ( graphql$1 && graphql ) || graphql$1; - -var languages$2 = [languageExtend({}, require$$0$13, { - since: "1.5.0", - parsers: ["graphql"], - vscodeLanguageIds: ["graphql"] -})]; -var printers$2 = { - graphql: printerGraphql -}; -var languageGraphql = { - languages: languages$2, - options: options$9, - printers: printers$2 -}; - -var _require$$0$builders$6 = doc.builders; -var hardline$10 = _require$$0$builders$6.hardline; -var literalline$5 = _require$$0$builders$6.literalline; -var concat$11 = _require$$0$builders$6.concat; -var markAsRoot$3 = _require$$0$builders$6.markAsRoot; -var mapDoc$5 = doc.utils.mapDoc; - -function embed$4(path, print, textToDoc, options) { - var node = path.getValue(); - - if (node.type === "code" && node.lang !== null) { - // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk) - var langMatch = node.lang.match(/^[A-Za-z0-9_-]+/); - var lang = langMatch ? langMatch[0] : ""; - var parser = getParserName(lang); - - if (parser) { - var styleUnit = options.__inJsTemplate ? "~" : "`"; - var style = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1)); - var doc$$2 = textToDoc(node.value, { - parser: parser - }); - return markAsRoot$3(concat$11([style, node.lang, hardline$10, replaceNewlinesWithLiterallines(doc$$2), style])); - } - } - - if (node.type === "yaml") { - return markAsRoot$3(concat$11(["---", hardline$10, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, { - parser: "yaml" - })) : "", "---"])); - } - - return null; - - function getParserName(lang) { - var supportInfo = support.getSupportInfo(null, { - plugins: options.plugins - }); - var language = supportInfo.languages.find(function (language) { - return language.name.toLowerCase() === lang || language.aliases && language.aliases.indexOf(lang) !== -1 || language.extensions && language.extensions.find(function (ext) { - return ext.substring(1) === lang; - }); - }); - - if (language) { - return language.parsers[0]; - } - - return null; - } - - function replaceNewlinesWithLiterallines(doc$$2) { - return mapDoc$5(doc$$2, function (currentDoc) { - return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$11(currentDoc.split(/(\n)/g).map(function (v, i) { - return i % 2 === 0 ? v : literalline$5; - })) : currentDoc; - }); - } -} - -var embed_1$4 = embed$4; - -var pragma$6 = createCommonjsModule(function (module) { - "use strict"; - - var pragmas = ["format", "prettier"]; - - function startWithPragma(text) { - var pragma = "@(".concat(pragmas.join("|"), ")"); - var regex = new RegExp(["<!--\\s*".concat(pragma, "\\s*-->"), "<!--.*\n[\\s\\S]*(^|\n)[^\\S\n]*".concat(pragma, "[^\\S\n]*($|\n)[\\s\\S]*\n.*-->")].join("|"), "m"); - var matched = text.match(regex); - return matched && matched.index === 0; - } - - module.exports = { - startWithPragma: startWithPragma, - hasPragma: function hasPragma(text) { - return startWithPragma(frontMatter(text).content.trimLeft()); - }, - insertPragma: function insertPragma(text) { - var extracted = frontMatter(text); - var pragma = "<!-- @".concat(pragmas[0], " -->"); - return extracted.frontMatter ? "".concat(extracted.frontMatter.raw, "\n\n").concat(pragma, "\n\n").concat(extracted.content) : "".concat(pragma, "\n\n").concat(extracted.content); - } - }; -}); - -function getOrderedListItemInfo$1(orderListItem, originalText) { - var _originalText$slice$m = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/), - _originalText$slice$m2 = _slicedToArray(_originalText$slice$m, 4), - numberText = _originalText$slice$m2[1], - marker = _originalText$slice$m2[2], - leadingSpaces = _originalText$slice$m2[3]; - - return { - numberText: numberText, - marker: marker, - leadingSpaces: leadingSpaces - }; -} - -var utils$6 = { - getOrderedListItemInfo: getOrderedListItemInfo$1 -}; - -var _require$$0$builders$5 = doc.builders; -var concat$10 = _require$$0$builders$5.concat; -var join$7 = _require$$0$builders$5.join; -var line$6 = _require$$0$builders$5.line; -var literalline$4 = _require$$0$builders$5.literalline; -var markAsRoot$2 = _require$$0$builders$5.markAsRoot; -var hardline$9 = _require$$0$builders$5.hardline; -var softline$5 = _require$$0$builders$5.softline; -var fill$4 = _require$$0$builders$5.fill; -var align$2 = _require$$0$builders$5.align; -var indent$7 = _require$$0$builders$5.indent; -var group$10 = _require$$0$builders$5.group; -var mapDoc$4 = doc.utils.mapDoc; -var printDocToString$2 = doc.printer.printDocToString; -var getOrderedListItemInfo = utils$6.getOrderedListItemInfo; -var SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"]; -var SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"]; -var INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break"]; -var INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]); - -function genericPrint$5(path, options, print) { - var node = path.getValue(); - - if (shouldRemainTheSameContent(path)) { - return concat$10(util.splitText(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(function (node) { - return node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options); - })); - } - - switch (node.type) { - case "root": - if (node.children.length === 0) { - return ""; - } - - return concat$10([normalizeDoc(printRoot(path, options, print)), hardline$9]); - - case "paragraph": - return printChildren(path, options, print, { - postprocessor: fill$4 - }); - - case "sentence": - return printChildren(path, options, print); - - case "word": - return node.value.replace(/[*]/g, "\\*") // escape all `*` - .replace(new RegExp(["(^|[".concat(util.punctuationCharRange, "])(_+)"), "(_+)([".concat(util.punctuationCharRange, "]|$)")].join("|"), "g"), function (_, text1, underscore1, underscore2, text2) { - return (underscore1 ? "".concat(text1).concat(underscore1) : "".concat(underscore2).concat(text2)).replace(/_/g, "\\_"); - }); - // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis - - case "whitespace": - { - var parentNode = path.getParentNode(); - var index = parentNode.children.indexOf(node); - var nextNode = parentNode.children[index + 1]; - var proseWrap = // leading char that may cause different syntax - nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap; - return printLine(path, node.value, { - proseWrap: proseWrap - }); - } - - case "emphasis": - { - var _parentNode = path.getParentNode(); - - var _index = _parentNode.children.indexOf(node); - - var prevNode = _parentNode.children[_index - 1]; - var _nextNode = _parentNode.children[_index + 1]; - var hasPrevOrNextWord = // `1*2*3` is considered emphais but `1_2_3` is not - prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util.getLast(prevNode.children).type === "word" && !util.getLast(prevNode.children).hasTrailingPunctuation || _nextNode && _nextNode.type === "sentence" && _nextNode.children.length > 0 && _nextNode.children[0].type === "word" && !_nextNode.children[0].hasLeadingPunctuation; - var style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_"; - return concat$10([style, printChildren(path, options, print), style]); - } - - case "strong": - return concat$10(["**", printChildren(path, options, print), "**"]); - - case "delete": - return concat$10(["~~", printChildren(path, options, print), "~~"]); - - case "inlineCode": - { - var backtickCount = util.getMaxContinuousCount(node.value, "`"); - - var _style = backtickCount === 1 ? "``" : "`"; - - var gap = backtickCount ? " " : ""; - return concat$10([_style, gap, node.value, gap, _style]); - } - - case "link": - switch (options.originalText[node.position.start.offset]) { - case "<": - { - var mailto = "mailto:"; - var url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" } - node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url; - return concat$10(["<", url, ">"]); - } - - case "[": - return concat$10(["[", printChildren(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]); - - default: - return options.originalText.slice(node.position.start.offset, node.position.end.offset); - } - - case "image": - return concat$10(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]); - - case "blockquote": - return concat$10(["> ", align$2("> ", printChildren(path, options, print))]); - - case "heading": - return concat$10(["#".repeat(node.depth) + " ", printChildren(path, options, print)]); - - case "code": - { - if (node.isIndented) { - // indented code block - var alignment = " ".repeat(4); - return align$2(alignment, concat$10([alignment, join$7(hardline$9, node.value.split("\n"))])); - } // fenced code block - - - var styleUnit = options.__inJsTemplate ? "~" : "`"; - - var _style2 = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1)); - - return concat$10([_style2, node.lang || "", hardline$9, join$7(hardline$9, node.value.split("\n")), hardline$9, _style2]); - } - - case "yaml": - case "toml": - return options.originalText.slice(node.position.start.offset, node.position.end.offset); - - case "html": - { - var _parentNode2 = path.getParentNode(); - - var value = _parentNode2.type === "root" && util.getLast(_parentNode2.children) === node ? node.value.trimRight() : node.value; - var isHtmlComment = /^<!--[\s\S]*-->$/.test(value); - return replaceNewlinesWith(value, isHtmlComment ? hardline$9 : markAsRoot$2(literalline$4)); - } - - case "list": - { - var nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode()); - var isGitDiffFriendlyOrderedList = node.ordered && node.children.length > 1 && +getOrderedListItemInfo(node.children[1], options.originalText).numberText === 1; - return printChildren(path, options, print, { - processor: function processor(childPath, index) { - var prefix = getPrefix(); - return concat$10([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]); - - function getPrefix() { - var rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* "; - return node.isAligned || - /* workaround for https://github.com/remarkjs/remark/issues/315 */ - node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix; - } - } - }); - } - - case "thematicBreak": - { - var counter = getAncestorCounter$1(path, "list"); - - if (counter === -1) { - return "---"; - } - - var _nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1)); - - return _nthSiblingIndex % 2 === 0 ? "***" : "---"; - } - - case "linkReference": - return concat$10(["[", printChildren(path, options, print), "]", node.referenceType === "full" ? concat$10(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]); - - case "imageReference": - switch (node.referenceType) { - case "full": - return concat$10(["![", node.alt || "", "][", node.identifier, "]"]); - - default: - return concat$10(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]); - } - - case "definition": - { - var lineOrSpace = options.proseWrap === "always" ? line$6 : " "; - return group$10(concat$10([concat$10(["[", node.identifier, "]:"]), indent$7(concat$10([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$10([lineOrSpace, printTitle(node.title, options, false)])]))])); - } - - case "footnote": - return concat$10(["[^", printChildren(path, options, print), "]"]); - - case "footnoteReference": - return concat$10(["[^", node.identifier, "]"]); - - case "footnoteDefinition": - { - var _nextNode2 = path.getParentNode().children[path.getName() + 1]; - return concat$10(["[^", node.identifier, "]: ", group$10(concat$10([align$2(" ".repeat(options.tabWidth), printChildren(path, options, print, { - processor: function processor(childPath, index) { - return index === 0 ? group$10(concat$10([softline$5, softline$5, childPath.call(print)])) : childPath.call(print); - } - })), _nextNode2 && _nextNode2.type === "footnoteDefinition" ? softline$5 : ""]))]); - } - - case "table": - return printTable(path, options, print); - - case "tableCell": - return printChildren(path, options, print); - - case "break": - return /\s/.test(options.originalText[node.position.start.offset]) ? concat$10([" ", markAsRoot$2(literalline$4)]) : concat$10(["\\", hardline$9]); - - case "liquidNode": - return replaceNewlinesWith(node.value, hardline$9); - - case "tableRow": // handled in "table" - - case "listItem": // handled in "list" - - default: - throw new Error("Unknown markdown type ".concat(JSON.stringify(node.type))); - } -} - -function printListItem(path, options, print, listPrefix) { - var node = path.getValue(); - var prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] "; - return concat$10([prefix, printChildren(path, options, print, { - processor: function processor(childPath, index) { - if (index === 0 && childPath.getValue().type !== "list") { - return align$2(" ".repeat(prefix.length), childPath.call(print)); - } - - var alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block - ); - return concat$10([alignment, align$2(alignment, childPath.call(print))]); - } - })]); -} - -function alignListPrefix(prefix, options) { - var additionalSpaces = getAdditionalSpaces(); - return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block - ); - - function getAdditionalSpaces() { - var restSpaces = prefix.length % options.tabWidth; - return restSpaces === 0 ? 0 : options.tabWidth - restSpaces; - } -} - -function getNthListSiblingIndex(node, parentNode) { - return getNthSiblingIndex(node, parentNode, function (siblingNode) { - return siblingNode.ordered === node.ordered; - }); -} - -function replaceNewlinesWith(str, doc$$2) { - return join$7(doc$$2, str.split("\n")); -} - -function getNthSiblingIndex(node, parentNode, condition) { - condition = condition || function () { - return true; - }; - - var index = -1; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = parentNode.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var childNode = _step.value; - - if (childNode.type === node.type && condition(childNode)) { - index++; - } else { - index = -1; - } - - if (childNode === node) { - return index; - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } -} - -function getAncestorCounter$1(path, typeOrTypes) { - var types = [].concat(typeOrTypes); - var counter = -1; - var ancestorNode; - - while (ancestorNode = path.getParentNode(++counter)) { - if (types.indexOf(ancestorNode.type) !== -1) { - return counter; - } - } - - return -1; -} - -function getAncestorNode$2(path, typeOrTypes) { - var counter = getAncestorCounter$1(path, typeOrTypes); - return counter === -1 ? null : path.getParentNode(counter); -} - -function printLine(path, value, options) { - if (options.proseWrap === "preserve" && value === "\n") { - return hardline$9; - } - - var isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES); - return value !== "" ? isBreakable ? line$6 : " " : isBreakable ? softline$5 : ""; -} - -function printTable(path, options, print) { - var node = path.getValue(); - var contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } } - - path.map(function (rowPath) { - var rowContents = []; - rowPath.map(function (cellPath) { - rowContents.push(printDocToString$2(cellPath.call(print), options).formatted); - }, "children"); - contents.push(rowContents); - }, "children"); - var columnMaxWidths = contents.reduce(function (currentWidths, rowContents) { - return currentWidths.map(function (width, columnIndex) { - return Math.max(width, util.getStringWidth(rowContents[columnIndex])); - }); - }, contents[0].map(function () { - return 3; - }) // minimum width = 3 (---, :--, :-:, --:) - ); - return join$7(hardline$9, [printRow(contents[0]), printSeparator(), join$7(hardline$9, contents.slice(1).map(printRow))]); - - function printSeparator() { - return concat$10(["| ", join$7(" | ", columnMaxWidths.map(function (width, index) { - switch (node.align[index]) { - case "left": - return ":" + "-".repeat(width - 1); - - case "right": - return "-".repeat(width - 1) + ":"; - - case "center": - return ":" + "-".repeat(width - 2) + ":"; - - default: - return "-".repeat(width); - } - })), " |"]); - } - - function printRow(rowContents) { - return concat$10(["| ", join$7(" | ", rowContents.map(function (rowContent, columnIndex) { - switch (node.align[columnIndex]) { - case "right": - return alignRight(rowContent, columnMaxWidths[columnIndex]); - - case "center": - return alignCenter(rowContent, columnMaxWidths[columnIndex]); - - default: - return alignLeft(rowContent, columnMaxWidths[columnIndex]); - } - })), " |"]); - } - - function alignLeft(text, width) { - return concat$10([text, " ".repeat(width - util.getStringWidth(text))]); - } - - function alignRight(text, width) { - return concat$10([" ".repeat(width - util.getStringWidth(text)), text]); - } - - function alignCenter(text, width) { - var spaces = width - util.getStringWidth(text); - var left = Math.floor(spaces / 2); - var right = spaces - left; - return concat$10([" ".repeat(left), text, " ".repeat(right)]); - } -} - -function printRoot(path, options, print) { - /** @typedef {{ index: number, offset: number }} IgnorePosition */ - - /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */ - var ignoreRanges = []; - /** @type {IgnorePosition | null} */ - - var ignoreStart = null; - var children = path.getValue().children; - children.forEach(function (childNode, index) { - switch (isPrettierIgnore(childNode)) { - case "start": - if (ignoreStart === null) { - ignoreStart = { - index: index, - offset: childNode.position.end.offset - }; - } - - break; - - case "end": - if (ignoreStart !== null) { - ignoreRanges.push({ - start: ignoreStart, - end: { - index: index, - offset: childNode.position.start.offset - } - }); - ignoreStart = null; - } - - break; - - default: - // do nothing - break; - } - }); - return printChildren(path, options, print, { - processor: function processor(childPath, index) { - if (ignoreRanges.length !== 0) { - var ignoreRange = ignoreRanges[0]; - - if (index === ignoreRange.start.index) { - return concat$10([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]); - } - - if (ignoreRange.start.index < index && index < ignoreRange.end.index) { - return false; - } - - if (index === ignoreRange.end.index) { - ignoreRanges.shift(); - return false; - } - } - - return childPath.call(print); - } - }); -} - -function printChildren(path, options, print, events) { - events = events || {}; - var postprocessor = events.postprocessor || concat$10; - - var processor = events.processor || function (childPath) { - return childPath.call(print); - }; - - var node = path.getValue(); - var parts = []; - var lastChildNode; - path.map(function (childPath, index) { - var childNode = childPath.getValue(); - var result = processor(childPath, index); - - if (result !== false) { - var data = { - parts: parts, - prevNode: lastChildNode, - parentNode: node, - options: options - }; - - if (!shouldNotPrePrintHardline(childNode, data)) { - parts.push(hardline$9); - - if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) { - parts.push(hardline$9); - } - - if (shouldPrePrintTripleHardline(childNode, data)) { - parts.push(hardline$9); - } - } - - parts.push(result); - lastChildNode = childNode; - } - }, "children"); - return postprocessor(parts); -} -/** @return {false | 'next' | 'start' | 'end'} */ - - -function isPrettierIgnore(node) { - if (node.type !== "html") { - return false; - } - - var match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/); - return match === null ? false : match[1] ? match[1] : "next"; -} - -function shouldNotPrePrintHardline(node, data) { - var isFirstNode = data.parts.length === 0; - var isInlineNode = INLINE_NODE_TYPES.indexOf(node.type) !== -1; - var isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES.indexOf(data.parentNode.type) !== -1; - return isFirstNode || isInlineNode || isInlineHTML; -} - -function shouldPrePrintDoubleHardline(node, data) { - var isSequence = (data.prevNode && data.prevNode.type) === node.type; - var isSiblingNode = isSequence && SIBLING_NODE_TYPES.indexOf(node.type) !== -1; - var isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose; - var isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose; - var isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next"; - var isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line; - return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml); -} - -function shouldPrePrintTripleHardline(node, data) { - var isPrevNodeList = data.prevNode && data.prevNode.type === "list"; - var isIndentedCode = node.type === "code" && node.isIndented; - return isPrevNodeList && isIndentedCode; -} - -function shouldRemainTheSameContent(path) { - var ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]); - return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full"); -} - -function normalizeDoc(doc$$2) { - return mapDoc$4(doc$$2, function (currentDoc) { - if (!currentDoc.parts) { - return currentDoc; - } - - if (currentDoc.type === "concat" && currentDoc.parts.length === 1) { - return currentDoc.parts[0]; - } - - var parts = []; - currentDoc.parts.forEach(function (part) { - if (part.type === "concat") { - parts.push.apply(parts, part.parts); - } else if (part !== "") { - parts.push(part); - } - }); - return Object.assign({}, currentDoc, { - parts: normalizeParts(parts) - }); - }); -} - -function printUrl(url, dangerousCharOrChars) { - var dangerousChars = [" "].concat(dangerousCharOrChars || []); - return new RegExp(dangerousChars.map(function (x) { - return "\\".concat(x); - }).join("|")).test(url) ? "<".concat(url, ">") : url; -} - -function printTitle(title, options, printSpace) { - if (printSpace == null) { - printSpace = true; - } - - if (!title) { - return ""; - } - - if (printSpace) { - return " " + printTitle(title, options, false); - } - - if (title.includes('"') && title.includes("'") && !title.includes(")")) { - return "(".concat(title, ")"); // avoid escaped quotes - } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split - - - var singleCount = title.split("'").length - 1; - var doubleCount = title.split('"').length - 1; - var quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"'; - title = title.replace(new RegExp("(".concat(quote, ")"), "g"), "\\$1"); - return "".concat(quote).concat(title).concat(quote); -} - -function normalizeParts(parts) { - return parts.reduce(function (current, part) { - var lastPart = util.getLast(current); - - if (typeof lastPart === "string" && typeof part === "string") { - current.splice(-1, 1, lastPart + part); - } else { - current.push(part); - } - - return current; - }, []); -} - -function clamp(value, min, max) { - return value < min ? min : value > max ? max : value; -} - -function clean$6(ast, newObj, parent) { - delete newObj.position; - delete newObj.raw; // front-matter - // for codeblock - - if (ast.type === "code" || ast.type === "yaml") { - delete newObj.value; - } - - if (ast.type === "list") { - delete newObj.isAligned; - } // for whitespace: "\n" and " " are considered the same - - - if (ast.type === "whitespace" && ast.value === "\n") { - newObj.value = " "; - } // for insert pragma - - - if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || (parent.children[0].type === "yaml" || parent.children[0].type === "toml") && parent.children[1] === ast) && ast.type === "html" && pragma$6.startWithPragma(ast.value)) { - return null; - } -} - -function hasPrettierIgnore$1(path) { - var index = +path.getName(); - - if (index === 0) { - return false; - } - - var prevNode = path.getParentNode().children[index - 1]; - return isPrettierIgnore(prevNode) === "next"; -} - -var printerMarkdown = { - print: genericPrint$5, - embed: embed_1$4, - massageAstNode: clean$6, - hasPrettierIgnore: hasPrettierIgnore$1, - insertPragma: pragma$6.insertPragma -}; - -var options$12 = { - proseWrap: commonOptions.proseWrap, - singleQuote: commonOptions.singleQuote -}; - -var name$12 = "Markdown"; -var type$11 = "prose"; -var aliases$3 = ["pandoc"]; -var aceMode$11 = "markdown"; -var codemirrorMode$9 = "gfm"; -var codemirrorMimeType$9 = "text/x-gfm"; -var wrap = true; -var extensions$11 = [".md", ".markdown", ".mdown", ".mdwn", ".mkd", ".mkdn", ".mkdown", ".ronn", ".workbook"]; -var tmScope$11 = "source.gfm"; -var languageId$11 = 222; -var markdown = { - name: name$12, - type: type$11, - aliases: aliases$3, - aceMode: aceMode$11, - codemirrorMode: codemirrorMode$9, - codemirrorMimeType: codemirrorMimeType$9, - wrap: wrap, - extensions: extensions$11, - tmScope: tmScope$11, - languageId: languageId$11 -}; - -var markdown$1 = Object.freeze({ - name: name$12, - type: type$11, - aliases: aliases$3, - aceMode: aceMode$11, - codemirrorMode: codemirrorMode$9, - codemirrorMimeType: codemirrorMimeType$9, - wrap: wrap, - extensions: extensions$11, - tmScope: tmScope$11, - languageId: languageId$11, - default: markdown -}); - -var require$$0$14 = ( markdown$1 && markdown ) || markdown$1; - -var languages$3 = [languageExtend({}, require$$0$14, { - since: "1.8.0", - parsers: ["remark"], - filenames: ["README"], - vscodeLanguageIds: ["markdown"] -})]; -var printers$3 = { - mdast: printerMarkdown -}; -var languageMarkdown = { - languages: languages$3, - options: options$12, - printers: printers$3 -}; - -var _require$$0$builders$8 = doc.builders; -var concat$13 = _require$$0$builders$8.concat; -var hardline$12 = _require$$0$builders$8.hardline; - -function embed$6(path, print, textToDoc, options) { - var node = path.getValue(); - var parent = path.getParentNode(); - - if (!parent || parent.tag !== "root" || node.unary) { - return null; - } - - var parser; - - if (node.tag === "style") { - var langAttr = node.attrs.find(function (attr) { - return attr.name === "lang"; - }); - - if (!langAttr || langAttr.value === "postcss") { - parser = "css"; - } else if (langAttr.value === "scss") { - parser = "scss"; - } else if (langAttr.value === "less") { - parser = "less"; - } - } - - if (node.tag === "script") { - var _langAttr = node.attrs.find(function (attr) { - return attr.name === "lang"; - }); - - if (!_langAttr) { - parser = "babylon"; - } else if (_langAttr.value === "ts" || _langAttr.value === "tsx") { - parser = "typescript"; - } - } - - if (!parser) { - return null; - } - - return concat$13([options.originalText.slice(node.start, node.contentStart), hardline$12, textToDoc(options.originalText.slice(node.contentStart, node.contentEnd), { - parser: parser - }), options.originalText.slice(node.contentEnd, node.end)]); -} - -var embed_1$6 = embed$6; - -function hasPragma$3(text) { - return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text); -} - -function insertPragma$7(text) { - return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, ""); -} - -var pragma$9 = { - hasPragma: hasPragma$3, - insertPragma: insertPragma$7 -}; - -var _require$$0$builders$7 = doc.builders; -var concat$12 = _require$$0$builders$7.concat; -var hardline$11 = _require$$0$builders$7.hardline; -var insertPragma$6 = pragma$9.insertPragma; - -function genericPrint$6(path, options, print) { - var n = path.getValue(); - var res = []; - var index = n.start; - path.each(function (childPath) { - var child = childPath.getValue(); - res.push(options.originalText.slice(index, child.start)); - res.push(childPath.call(print)); - index = child.end; - }, "children"); // If there are no children, we just print the node from start to end. - // Otherwise, index should point to the end of the last child, and we - // need to print the closing tag. - - res.push(options.originalText.slice(index, n.end)); // Only force a trailing newline if there were any contents. - - if (n.tag === "root" && n.children.length) { - res.push(hardline$11); - } - - return concat$12(res); -} - -var clean$7 = function clean(ast, newObj) { - delete newObj.start; - delete newObj.end; - delete newObj.contentStart; - delete newObj.contentEnd; -}; - -var printerVue = { - print: genericPrint$6, - embed: embed_1$6, - insertPragma: insertPragma$6, - massageAstNode: clean$7, - canAttachComment: function canAttachComment(node) { - return typeof node.tag === "string"; - } -}; - -var name$13 = "Vue"; -var type$12 = "markup"; -var color$3 = "#2c3e50"; -var extensions$12 = [".vue"]; -var tmScope$12 = "text.html.vue"; -var aceMode$12 = "html"; -var languageId$12 = 391; -var vue = { - name: name$13, - type: type$12, - color: color$3, - extensions: extensions$12, - tmScope: tmScope$12, - aceMode: aceMode$12, - languageId: languageId$12 -}; - -var vue$1 = Object.freeze({ - name: name$13, - type: type$12, - color: color$3, - extensions: extensions$12, - tmScope: tmScope$12, - aceMode: aceMode$12, - languageId: languageId$12, - default: vue -}); - -var require$$0$15 = ( vue$1 && vue ) || vue$1; - -var languages$4 = [languageExtend({}, require$$0$15, { - since: "1.10.0", - parsers: ["vue"], - vscodeLanguageIds: ["vue"] -})]; -var printers$4 = { - vue: printerVue -}; -var languageVue = { - languages: languages$4, - printers: printers$4 -}; - -function isPragma$1(text) { - return /^\s*@(prettier|format)\s*$/.test(text); -} - -function hasPragma$4(text) { - return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text); -} - -function insertPragma$9(text) { - return "# @format\n\n".concat(text); -} - -var pragma$11 = { - isPragma: isPragma$1, - hasPragma: hasPragma$4, - insertPragma: insertPragma$9 -}; - -function getLast$6(array) { - return array[array.length - 1]; -} - -function getAncestorCount$1(path, filter) { - var counter = 0; - var pathStackLength = path.stack.length - 1; - - for (var i = 0; i < pathStackLength; i++) { - var value = path.stack[i]; - - if (isNode$1(value) && filter(value)) { - counter++; - } - } - - return counter; -} - -function isNode$1(value) { - return value && typeof value.type === "string"; -} - -function mapNode(node, callback, parent) { - return callback("children" in node ? Object.assign({}, node, { - children: node.children.map(function (childNode) { - return mapNode(childNode, callback, node); - }) - }) : node, parent); -} - -function defineShortcut(x, key, getter) { - Object.defineProperty(x, key, { - get: getter, - enumerable: false - }); -} - -function createNull() { - return { - type: "null", - position: { - start: { - line: -1, - column: -1, - offset: -1 - }, - end: { - line: -1, - column: -1, - offset: -1 - } - } - }; -} - -function isNextLineEmpty$6(node, text) { - var newlineCount = 0; - var textLength = text.length; - - for (var i = node.position.end.offset - 1; i < textLength; i++) { - var char = text[i]; - - if (char === "\n") { - newlineCount++; - } - - if (newlineCount === 1 && /\S/.test(char)) { - return false; - } - - if (newlineCount === 2) { - return true; - } - } - - return false; -} - -function isLastDescendantNode$1(path) { - var node = path.getValue(); - - switch (node.type) { - case "comment": - case "verbatimTag": - case "shorthandTag": - case "nonSpecificTag": - return false; - } - - var pathStackLength = path.stack.length; - - for (var i = 1; i < pathStackLength; i++) { - var item = path.stack[i]; - var parentItem = path.stack[i - 1]; - - if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) { - return false; - } - } - - return true; -} - -function getLastDescendantNode$1(node) { - return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$6(node.children)) : node; -} - -function isPrettierIgnore$1(comment) { - return comment.value.trim() === "prettier-ignore"; -} - -function hasPrettierIgnore$3(path) { - var node = path.getValue(); - - if (node.type === "documentBody") { - var document = path.getParentNode(); - return document.head.children.length !== 0 && function (lastItem) { - return lastItem.type === "comment" && isPrettierIgnore$1(lastItem); - }(getLast$6(document.head.children)); - } - - return "leadingComments" in node && node.leadingComments.length !== 0 && isPrettierIgnore$1(getLast$6(node.leadingComments)); -} - -function hasExplicitDocumentEndMarker$1(document, text) { - return text.slice(document.position.end.offset - 4, document.position.end.offset) === "\n..."; -} - -function isBlockValue$1(node) { - switch (node.type) { - case "blockFolded": - case "blockLiteral": - return true; - - default: - return false; - } -} - -function hasLeadingComments$1(node) { - return "leadingComments" in node && node.leadingComments.length !== 0; -} - -function hasMiddleComments$1(node) { - return "middleComments" in node && node.middleComments.length !== 0; -} - -function hasTrailingComments$1(node) { - return "trailingComments" in node && node.trailingComments.length !== 0; -} - -function hasEndComments$1(node) { - return "endComments" in node && node.endComments.length !== 0; -} -/** - * " a b c d e f " -> [" a b", "c d", "e f "] - */ - - -function splitWithSingleSpace(text) { - var parts = []; - var lastPart = undefined; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = text.split(/( +)/g)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var part = _step.value; - - if (part !== " ") { - if (lastPart === " ") { - parts.push(part); - } else { - parts.push((parts.pop() || "") + part); - } - } else if (lastPart === undefined) { - parts.unshift(""); - } - - lastPart = part; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - if (lastPart === " ") { - parts.push((parts.pop() || "") + " "); - } - - if (parts[0] === "") { - parts.shift(); - parts.unshift(" " + (parts.shift() || "")); - } - - return parts; -} - -function getFlowScalarLineContents$1(nodeType, content, options) { - var rawLineContents = content.split("\n").map(function (lineContent, index, lineContents) { - return index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimRight() : lineContent.trimLeft(); - }); - - if (options.proseWrap === "preserve") { - return rawLineContents.map(function (lineContent) { - return lineContent.length === 0 ? [] : [lineContent]; - }); - } - - return rawLineContents.map(function (lineContent) { - return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent); - }).reduce(function (reduced, lineContentWords, index) { - return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved - nodeType === "quoteDouble" && getLast$6(getLast$6(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]); - }, []).map(function (lineContentWords) { - return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords; - }); -} - -function getBlockValueLineContents$1(node, _ref) { - var parentIndent = _ref.parentIndent, - isLastDescendant = _ref.isLastDescendant, - options = _ref.options; - var content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|` - .match(/^[^\n]*?\n([\s\S]*)$/)[1]; - var leadingSpaceCount = node.indent === null ? function (match) { - return match ? match[1].length : Infinity; - }(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent; - var rawLineContents = content.split("\n").map(function (lineContent) { - return lineContent.slice(leadingSpaceCount); - }); - - if (options.proseWrap === "preserve" || node.type === "blockLiteral") { - return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) { - return lineContent.length === 0 ? [] : [lineContent]; - })); - } - - return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) { - return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent); - }).reduce(function (reduced, lineContentWords, index) { - return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$6(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]); - }, []).map(function (lineContentWords) { - return lineContentWords.reduce(function (reduced, word) { - return (// disallow trailing spaces - reduced.length !== 0 && /\s$/.test(getLast$6(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word) - ); - }, []); - }).map(function (lineContentWords) { - return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords; - })); - - function removeUnnecessaryTrailingNewlines(lineContents) { - if (node.chomping === "keep") { - return getLast$6(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents; - } - - var trailingNewlineCount = 0; - - for (var i = lineContents.length - 1; i >= 0; i--) { - if (lineContents[i].length === 0) { - trailingNewlineCount++; - } else { - break; - } - } - - return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line - lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount); - } -} - -var utils$8 = { - getLast: getLast$6, - getAncestorCount: getAncestorCount$1, - isNode: isNode$1, - isBlockValue: isBlockValue$1, - mapNode: mapNode, - defineShortcut: defineShortcut, - createNull: createNull, - isNextLineEmpty: isNextLineEmpty$6, - isLastDescendantNode: isLastDescendantNode$1, - getBlockValueLineContents: getBlockValueLineContents$1, - getFlowScalarLineContents: getFlowScalarLineContents$1, - getLastDescendantNode: getLastDescendantNode$1, - hasPrettierIgnore: hasPrettierIgnore$3, - hasLeadingComments: hasLeadingComments$1, - hasMiddleComments: hasMiddleComments$1, - hasTrailingComments: hasTrailingComments$1, - hasEndComments: hasEndComments$1, - hasExplicitDocumentEndMarker: hasExplicitDocumentEndMarker$1 -}; - -var insertPragma$8 = pragma$11.insertPragma; -var isPragma = pragma$11.isPragma; -var getAncestorCount = utils$8.getAncestorCount; -var getBlockValueLineContents = utils$8.getBlockValueLineContents; -var getFlowScalarLineContents = utils$8.getFlowScalarLineContents; -var getLast$5 = utils$8.getLast; -var getLastDescendantNode = utils$8.getLastDescendantNode; -var hasExplicitDocumentEndMarker = utils$8.hasExplicitDocumentEndMarker; -var hasLeadingComments = utils$8.hasLeadingComments; -var hasMiddleComments = utils$8.hasMiddleComments; -var hasTrailingComments = utils$8.hasTrailingComments; -var hasEndComments = utils$8.hasEndComments; -var hasPrettierIgnore$2 = utils$8.hasPrettierIgnore; -var isLastDescendantNode = utils$8.isLastDescendantNode; -var isNextLineEmpty$5 = utils$8.isNextLineEmpty; -var isNode = utils$8.isNode; -var isBlockValue = utils$8.isBlockValue; -var docBuilders$3 = doc.builders; -var conditionalGroup$2 = docBuilders$3.conditionalGroup; -var breakParent$3 = docBuilders$3.breakParent; -var concat$14 = docBuilders$3.concat; -var dedent$4 = docBuilders$3.dedent; -var dedentToRoot$2 = docBuilders$3.dedentToRoot; -var fill$5 = docBuilders$3.fill; -var group$11 = docBuilders$3.group; -var hardline$13 = docBuilders$3.hardline; -var ifBreak$4 = docBuilders$3.ifBreak; -var join$8 = docBuilders$3.join; -var line$7 = docBuilders$3.line; -var lineSuffix$2 = docBuilders$3.lineSuffix; -var literalline$6 = docBuilders$3.literalline; -var markAsRoot$4 = docBuilders$3.markAsRoot; -var softline$6 = docBuilders$3.softline; - -function genericPrint$7(path, options, print) { - var node = path.getValue(); - var parentNode = path.getParentNode(); - var tag = "tag" in node && node.tag.type !== "null" ? path.call(print, "tag") : ""; - var anchor = "anchor" in node && node.anchor.type !== "null" ? path.call(print, "anchor") : ""; - var nextEmptyLine = (node.type === "mapping" || node.type === "sequence" || node.type === "comment" || node.type === "directive" || node.type === "mappingItem" || node.type === "sequenceItem") && !isLastDescendantNode(path) ? printNextEmptyLine(path, options.originalText) : ""; - return concat$14([node.type !== "mappingValue" && hasLeadingComments(node) ? concat$14([join$8(hardline$13, path.map(print, "leadingComments")), hardline$13]) : "", tag, tag && anchor ? " " : "", anchor, (node.type === "sequence" || node.type === "mapping") && node.middleComments.length === 0 ? tag || anchor ? hardline$13 : "" : tag || anchor ? " " : "", hasMiddleComments(node) ? concat$14([node.middleComments.length === 1 ? "" : hardline$13, join$8(hardline$13, path.map(print, "middleComments")), hardline$13]) : "", hasPrettierIgnore$2(path) ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : group$11(_print(node, parentNode, path, options, print)), !isBlockValue(node) && hasTrailingComments(node) // trailing comments for block value are handled themselves - ? lineSuffix$2(concat$14([" ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$3, join$8(hardline$13, path.map(print, "trailingComments"))])) : "", nextEmptyLine, hasEndComments(node) ? function (endComments) { - return node.type === "sequenceItem" ? align$3(2, endComments) : endComments; - }(concat$14([hardline$13, join$8(hardline$13, path.map(print, "endComments"))])) : ""]); -} - -function _print(node, parentNode, path, options, print) { - switch (node.type) { - case "root": - return concat$14([concat$14(path.map(function (childPath, index) { - return index === node.children.length - 1 ? print(childPath) : concat$14([print(childPath), hasTrailingComments(node.children[index]) || childPath.call(hasPrettierIgnore$2, "body") && hasExplicitDocumentEndMarker(node.children[index], options.originalText) ? "" : concat$14([hardline$13, "..."]), hardline$13]); - }, "children")), node.children.length === 0 || function (lastDescendantNode) { - return isBlockValue(lastDescendantNode) && lastDescendantNode.chomping === "keep"; - }(getLastDescendantNode(node)) ? "" : hardline$13]); - - case "document": - return concat$14([node.head.children.length === 0 ? path.call(print, "body") : join$8(hardline$13, [path.call(print, "head"), "---"].concat(node.body.children.length === 0 ? [] : path.call(print, "body"))), hasTrailingComments(node) ? concat$14([hardline$13, "..."]) : ""]); - - case "documentHead": - case "documentBody": - return join$8(hardline$13, path.map(print, "children")); - - case "directive": - return concat$14(["%", join$8(" ", [node.name].concat(node.parameters))]); - - case "comment": - return concat$14(["#", node.value]); - - case "alias": - return concat$14(["*", node.value]); - - case "null": - return ""; - - case "verbatimTag": - return concat$14(["!<", node.value, ">"]); - - case "shorthandTag": - return concat$14([node.handle, node.suffix]); - - case "nonSpecificTag": - return "!"; - - case "anchor": - return concat$14(["&", node.value]); - - case "plain": - return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options); - - case "quoteDouble": - case "quoteSingle": - { - var singleQuote = "'"; - var doubleQuote = '"'; - var raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1); - - if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) { - // only quoteDouble can use escape chars - // and quoteSingle do not need to escape backslashes - var originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote; - return concat$14([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]); - } else if (raw.includes(doubleQuote)) { - return concat$14([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? // double quote needs to be escaped by backslash in quoteDouble - raw.replace(/\\"/g, doubleQuote) : raw, options), singleQuote]); - } - - if (raw.includes(singleQuote)) { - return concat$14([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle - raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]); - } - - var quote = options.singleQuote ? singleQuote : doubleQuote; - return concat$14([quote, printFlowScalarContent(node.type, raw, options), quote]); - } - - case "blockFolded": - case "blockLiteral": - { - var parentIndent = getAncestorCount(path, function (ancestorNode) { - return ancestorNode.type === "sequence" || ancestorNode.type === "mapping"; - }); - var isLastDescendant = isLastDescendantNode(path); - return concat$14([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasTrailingComments(node) ? concat$14([" ", join$8(hardline$13, path.map(print, "trailingComments"))]) : "", (node.indent === null ? dedent$4 : dedentToRoot$2)(align$3(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$14(getBlockValueLineContents(node, { - parentIndent: parentIndent, - isLastDescendant: isLastDescendant, - options: options - }).reduce(function (reduced, lineWords, index, lineContents) { - return reduced.concat(index === 0 ? hardline$13 : lineContents[index - 1].length === 0 ? hardline$13 : index === lineContents.length - 1 && lineWords.length === 0 ? dedentToRoot$2(literalline$6) : markAsRoot$4(literalline$6), fill$5(join$8(line$7, lineWords).parts), index === lineContents.length - 1 && node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 || !getLast$5(lineWords).endsWith(" ") ? dedentToRoot$2(hardline$13) : dedentToRoot$2(literalline$6) : []); - }, []))))]); - } - - case "sequence": - return join$8(hardline$13, path.map(print, "children")); - - case "sequenceItem": - return concat$14(["- ", align$3(2, path.call(print, "node"))]); - - case "mappingKey": - return path.call(print, "node"); - - case "mappingValue": - return path.call(print, "node"); - - case "mapping": - return join$8(hardline$13, path.map(print, "children")); - - case "mappingItem": - case "flowMappingItem": - { - if (node.key.type === "null" && node.value.type === "null") { - return concat$14([":", line$7]); - } - - var key = path.call(print, "key"); - var value = path.call(print, "value"); - - if (node.value.type === "null") { - return node.type === "flowMappingItem" && path.getParentNode().type !== "flowSequence" ? key : concat$14(["? ", align$3(2, key)]); - } - - if (node.key.type === "null") { - return concat$14([":", node.value.node.type === "null" ? "" : " ", align$3(2, value)]); - } - - var groupId = Symbol("mappingKey"); - var forceExplicitKey = hasLeadingComments(node.value) || node.key.type !== "null" && !isInlineNode(node.key.node); - return forceExplicitKey ? concat$14(["? ", align$3(2, key), hardline$13, join$8("", path.map(print, "value", "leadingComments").map(function (comment) { - return concat$14([comment, hardline$13]); - })), ": ", align$3(2, value)]) : conditionalGroup$2([concat$14([group$11(concat$14([ifBreak$4("? "), group$11(align$3(2, key), { - id: groupId - })])), ifBreak$4(concat$14([hardline$13, ": ", align$3(2, value)]), indent(concat$14([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments(node.value.node) || parentNode.type === "mapping" && hasTrailingComments(node.key.node) && isInlineNode(node.value.node) || (node.value.node.type === "mapping" || node.value.node.type === "sequence") && node.value.node.tag.type === "null" && node.value.node.anchor.type === "null" ? hardline$13 : node.value.node.type === "null" ? "" : line$7, value])), { - groupId: groupId - })])]); - } - - case "flowMapping": - case "flowSequence": - { - var openMarker = node.type === "flowMapping" ? "{" : "["; - var closeMarker = node.type === "flowMapping" ? "}" : "]"; - var bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$7 : softline$6; - - var isLastItemEmptyMappingItem = node.children.length !== 0 && function (lastItem) { - return lastItem.type === "flowMappingItem" && lastItem.key.type === "null" && lastItem.value.type === "null"; - }(getLast$5(node.children)); - - return concat$14([openMarker, indent(concat$14([bracketSpacing, concat$14(path.map(function (childPath, index) { - return concat$14([print(childPath), index === node.children.length - 1 ? "" : concat$14([",", line$7, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]); - }, "children")), ifBreak$4(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]); - } - - case "flowSequenceItem": - return path.call(print, "node"); - // istanbul ignore next - - default: - throw new Error("Unexpected node type ".concat(node.type)); - } - - function indent(doc$$2) { - return docBuilders$3.align(" ".repeat(options.tabWidth), doc$$2); - } -} - -function align$3(n, doc$$2) { - return typeof n === "number" && n > 0 ? docBuilders$3.align(" ".repeat(n), doc$$2) : docBuilders$3.align(n, doc$$2); -} - -function isInlineNode(node) { - switch (node.type) { - case "plain": - case "quoteDouble": - case "quoteSingle": - case "alias": - case "flowMapping": - case "flowSequence": - case "null": - return true; - - default: - return false; - } -} - -function needsSpaceInFrontOfMappingValue(node) { - // istanbul ignore else - if (node.key.type !== "null") { - switch (node.key.node.type) { - case "alias": - return true; - } - } - - return false; -} - -function printNextEmptyLine(path, originalText) { - var node = path.getValue(); - var root = path.stack[0]; - root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || []; - - if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) { - if (isNextLineEmpty$5(node, originalText)) { - root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true; - return softline$6; - } - } - - return ""; -} - -function printFlowScalarContent(nodeType, content, options) { - var lineContents = getFlowScalarLineContents(nodeType, content, options); - return join$8(hardline$13, lineContents.map(function (lineContentWords) { - return fill$5(join$8(line$7, lineContentWords).parts); - })); -} - -function clean$8(node, newNode -/*, parent */ -) { - if (isNode(newNode)) { - delete newNode.position; - - switch (newNode.type) { - case "comment": - // insert pragma - if (isPragma(newNode.value)) { - return null; - } - - break; - - case "quoteDouble": - case "quoteSingle": - newNode.type = "quote"; - break; - } - } -} - -var printerYaml = { - print: genericPrint$7, - massageAstNode: clean$8, - insertPragma: insertPragma$8 -}; - -var options$15 = { - bracketSpacing: commonOptions.bracketSpacing, - singleQuote: commonOptions.singleQuote, - proseWrap: commonOptions.proseWrap -}; - -var name$14 = "YAML"; -var type$13 = "data"; -var tmScope$13 = "source.yaml"; -var aliases$4 = ["yml"]; -var extensions$13 = [".yml", ".mir", ".reek", ".rviz", ".sublime-syntax", ".syntax", ".yaml", ".yaml-tmlanguage", ".yml.mysql"]; -var filenames$3 = [".clang-format", ".clang-tidy", ".gemrc", "glide.lock"]; -var aceMode$13 = "yaml"; -var codemirrorMode$10 = "yaml"; -var codemirrorMimeType$10 = "text/x-yaml"; -var languageId$13 = 407; -var yaml = { - name: name$14, - type: type$13, - tmScope: tmScope$13, - aliases: aliases$4, - extensions: extensions$13, - filenames: filenames$3, - aceMode: aceMode$13, - codemirrorMode: codemirrorMode$10, - codemirrorMimeType: codemirrorMimeType$10, - languageId: languageId$13 -}; - -var yaml$1 = Object.freeze({ - name: name$14, - type: type$13, - tmScope: tmScope$13, - aliases: aliases$4, - extensions: extensions$13, - filenames: filenames$3, - aceMode: aceMode$13, - codemirrorMode: codemirrorMode$10, - codemirrorMimeType: codemirrorMimeType$10, - languageId: languageId$13, - default: yaml -}); - -var require$$0$17 = ( yaml$1 && yaml ) || yaml$1; - -var languages$5 = [languageExtend({}, require$$0$17, { - since: "1.14.0", - parsers: ["yaml"], - vscodeLanguageIds: ["yaml"] -})]; -var languageYaml = { - languages: languages$5, - printers: { - yaml: printerYaml - }, - options: options$15 -}; - -var version = require$$0.version; -var getSupportInfo = support.getSupportInfo; -var internalPlugins = [languageJs, languageCss, languageGraphql, languageMarkdown, languageVue, languageYaml]; - -var isArray = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) === "[object Array]"; -}; // Luckily `opts` is always the 2nd argument - - -function withPlugins(fn) { - return function () { - var args = Array.from(arguments); - var plugins = args[1] && args[1].plugins || []; - - if (!isArray(plugins)) { - plugins = Object.values(plugins); - } - - args[1] = Object.assign({}, args[1], { - plugins: internalPlugins.concat(plugins) - }); - return fn.apply(null, args); - }; -} - -var formatWithCursor = withPlugins(core.formatWithCursor); -var standalone = { - formatWithCursor: formatWithCursor, - format: function format(text, opts) { - return formatWithCursor(text, opts).formatted; - }, - check: function check(text, opts) { - var formatted = formatWithCursor(text, opts).formatted; - return formatted === text; - }, - doc: doc, - getSupportInfo: withPlugins(getSupportInfo), - version: version, - util: utilShared, - __debug: { - parse: withPlugins(core.parse), - formatAST: withPlugins(core.formatAST), - formatDoc: withPlugins(core.formatDoc), - printToDoc: withPlugins(core.printToDoc), - printDocToString: withPlugins(core.printDocToString) - } -}; - -return standalone; - -}))); diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0.xml b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5.xml similarity index 90% rename from bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0.xml rename to bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5.xml index d327c02d0c..3e3397c516 100644 --- a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0.xml +++ b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5.xml @@ -14,7 +14,7 @@ </item> <item> <key> <string>id</string> </key> - <value> <string>prettier@1.14.0</string> </value> + <value> <string>prettier@2.0.5</string> </value> </item> <item> <key> <string>title</string> </key> diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/parser-babel.js.js b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/parser-babel.js.js new file mode 100644 index 0000000000..e2a5863645 --- /dev/null +++ b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/parser-babel.js.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(((t=t||self).prettierPlugins=t.prettierPlugins||{},t.prettierPlugins.babel={}))}(this,(function(t){"use strict";var e=function(t,e){const s=new SyntaxError(t+" ("+e.start.line+":"+e.start.column+")");return s.loc=e,s};function s(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function i(t,e){return t(e={exports:{}},e.exports),e.exports}var r=Object.freeze({__proto__:null,default:{EOL:"\n"}});const a=t=>{if("string"!=typeof t)throw new TypeError("Expected a string");const e=t.match(/(?:\r?\n)/g)||[];if(0===e.length)return;const s=e.filter(t=>"\r\n"===t).length;return s>e.length-s?"\r\n":"\n"};var n=a;n.graceful=t=>"string"==typeof t&&a(t)||"\n";var o,h=(o=r)&&o.default||o,p=i((function(t,e){function s(){const t=h;return s=function(){return t},t}function i(){const t=(e=n)&&e.__esModule?e:{default:e};var e;return i=function(){return t},t}Object.defineProperty(e,"__esModule",{value:!0}),e.extract=function(t){const e=t.match(o);return e?e[0].trimLeft():""},e.strip=function(t){const e=t.match(o);return e&&e[0]?t.substring(e[0].length):t},e.parse=function(t){return m(t).pragmas},e.parseWithComments=m,e.print=function({comments:t="",pragmas:e={}}){const r=(0,i().default)(t)||s().EOL,a=Object.keys(e),n=a.map(t=>f(t,e[t])).reduce((t,e)=>t.concat(e),[]).map(t=>" * "+t+r).join("");if(!t){if(0===a.length)return"";if(1===a.length&&!Array.isArray(e[a[0]])){const t=e[a[0]];return"".concat("/**"," ").concat(f(a[0],t)[0]).concat(" */")}}const o=t.split(r).map(t=>"".concat(" *"," ").concat(t)).join(r)+r;return"/**"+r+(t?o:"")+(t&&a.length?" *"+r:"")+n+" */"};const r=/\*\/$/,a=/^\/\*\*/,o=/^\s*(\/\*\*?(.|\r?\n)*?\*\/)/,p=/(^|\s+)\/\/([^\r\n]*)/g,c=/^(\r?\n)+/,u=/(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g,l=/(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g,d=/(\r?\n|^) *\* ?/g;function m(t){const e=(0,i().default)(t)||s().EOL;t=t.replace(a,"").replace(r,"").replace(d,"$1");let n="";for(;n!==t;)n=t,t=t.replace(u,"".concat(e,"$1 $2").concat(e));t=t.replace(c,"").trimRight();const o=Object.create(null),h=t.replace(l,"").replace(c,"").trimRight();let m;for(;m=l.exec(t);){const t=m[2].replace(p,"");"string"==typeof o[m[1]]||Array.isArray(o[m[1]])?o[m[1]]=[].concat(o[m[1]],t):o[m[1]]=t}return{comments:h,pragmas:o}}function f(t,e){return[].concat(e).map(e=>"@".concat(t," ").concat(e).trim())}}));s(p);p.extract,p.strip,p.parse,p.parseWithComments,p.print;var c={hasPragma:function(t){const e=Object.keys(p.parse(p.extract(t)));return e.includes("prettier")||e.includes("format")},insertPragma:function(t){const e=p.parseWithComments(p.extract(t)),s=Object.assign({format:""},e.pragmas),i=p.print({pragmas:s,comments:e.comments.replace(/^(\s+?\r?\n)+/,"")}).replace(/(\r\n|\r)/g,"\n"),r=p.strip(t);return i+(r.startsWith("\n")?"\n":"\n\n")+r}},u=t=>t[t.length-1];function l(t,e){return!(e=e||{}).ignoreDecorators&&t.declaration&&t.declaration.decorators&&t.declaration.decorators.length>0?l(t.declaration.decorators[0]):!e.ignoreDecorators&&t.decorators&&t.decorators.length>0?l(t.decorators[0]):t.__location?t.__location.startOffset:t.range?t.range[0]:"number"==typeof t.start?t.start:t.loc?t.loc.start:null}function d(t){const e=t.nodes&&u(t.nodes);if(e&&t.source&&!t.source.end&&(t=e),t.__location)return t.__location.endOffset;const s=t.range?t.range[1]:"number"==typeof t.end?t.end:null;return t.typeAnnotation?Math.max(s,d(t.typeAnnotation)):t.loc&&!s?t.loc.end:s}var m={locStart:l,locEnd:d,composeLoc:function(t,e=t){const s="number"==typeof e?e:-1,i=l(t),r=-1!==s?i+s:d(e),a=t.loc.start;return{start:i,end:r,range:[i,r],loc:{start:a,end:-1!==s?{line:a.line,column:a.column+s}:e.loc.end}}}},f=t=>"string"==typeof t?t.replace((({onlyFirst:t=!1}={})=>{const e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(e,t?void 0:"g")})(),""):t;const D=t=>!Number.isNaN(t)&&(t>=4352&&(t<=4447||9001===t||9002===t||11904<=t&&t<=12871&&12351!==t||12880<=t&&t<=19903||19968<=t&&t<=42182||43360<=t&&t<=43388||44032<=t&&t<=55203||63744<=t&&t<=64255||65040<=t&&t<=65049||65072<=t&&t<=65131||65281<=t&&t<=65376||65504<=t&&t<=65510||110592<=t&&t<=110593||127488<=t&&t<=127569||131072<=t&&t<=262141));var y=D,x=D;y.default=x;const g=t=>{if("string"!=typeof(t=t.replace(/\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\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g," "))||0===t.length)return 0;t=f(t);let e=0;for(let s=0;s<t.length;s++){const i=t.codePointAt(s);i<=31||i>=127&&i<=159||(i>=768&&i<=879||(i>65535&&s++,e+=y(i)?2:1))}return e};var P=g,E=g;P.default=E;const C=/[|\\{}()[\]^$+*?.-]/g;var b=t=>{if("string"!=typeof t)throw new TypeError("Expected a string");return t.replace(C,"\\$&")};const T=/[^\x20-\x7F]/;function A(t){return(e,s,i)=>{const r=i&&i.backwards;if(!1===s)return!1;const{length:a}=e;let n=s;for(;n>=0&&n<a;){const s=e.charAt(n);if(t instanceof RegExp){if(!t.test(s))return n}else if(!t.includes(s))return n;r?n--:n++}return(-1===n||n===a)&&n}}const w=A(/\s/),S=A(" \t"),N=A(",; \t"),F=A(/[^\r\n]/);function k(t,e){if(!1===e)return!1;if("/"===t.charAt(e)&&"*"===t.charAt(e+1))for(let s=e+2;s<t.length;++s)if("*"===t.charAt(s)&&"/"===t.charAt(s+1))return s+2;return e}function I(t,e){return!1!==e&&("/"===t.charAt(e)&&"/"===t.charAt(e+1)?F(t,e):e)}function v(t,e,s){const i=s&&s.backwards;if(!1===e)return!1;const r=t.charAt(e);if(i){if("\r"===t.charAt(e-1)&&"\n"===r)return e-2;if("\n"===r||"\r"===r||"\u2028"===r||"\u2029"===r)return e-1}else{if("\r"===r&&"\n"===t.charAt(e+1))return e+2;if("\n"===r||"\r"===r||"\u2028"===r||"\u2029"===r)return e+1}return e}function L(t,e,s){const i=S(t,(s=s||{}).backwards?e-1:e,s);return i!==v(t,i,s)}function B(t,e){let s=null,i=e;for(;i!==s;)s=i,i=N(t,i),i=k(t,i),i=S(t,i);return i=I(t,i),i=v(t,i),!1!==i&&L(t,i)}function M(t,e){let s=null,i=e;for(;i!==s;)s=i,i=S(t,i),i=k(t,i),i=I(t,i),i=v(t,i);return i}function O(t,e,s){return M(t,s(e))}const R={};function _(t){return R[t]}[["|>"],["??"],["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]].forEach((t,e)=>{t.forEach(t=>{R[t]=e})});const j={"==":!0,"!=":!0,"===":!0,"!==":!0},U={"*":!0,"/":!0,"%":!0},q={">>":!0,">>>":!0,"<<":!0};function V(t,e,s){let i=0;for(let r=s=s||0;r<t.length;++r)"\t"===t[r]?i=i+e-i%e:i++;return i}function z(t,e){const s=t.slice(1,-1),i={quote:'"',regex:/"/g},r={quote:"'",regex:/'/g},a="'"===e?r:i,n=a===r?i:r;let o=a.quote;if(s.includes(a.quote)||s.includes(n.quote)){o=(s.match(a.regex)||[]).length>(s.match(n.regex)||[]).length?n.quote:a.quote}return o}function H(t,e,s){const i='"'===e?"'":'"',r=t.replace(/\\([\s\S])|(['"])/g,(t,r,a)=>r===i?r:a===e?"\\"+a:a||(s&&/^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(r)?r:"\\"+r));return e+r+e}function W(t){return t&&(t.comments&&t.comments.length>0&&t.comments.some(t=>K(t)&&!t.unignore)||t.prettierIgnore)}function K(t){return"prettier-ignore"===t.value.trim()}function J(t,e){(t.comments||(t.comments=[])).push(e),e.printed=!1,"JSXText"===t.type&&(e.printed=!0)}var X={replaceEndOfLineWith:function(t,e){const s=[];for(const i of t.split("\n"))0!==s.length&&s.push(e),s.push(i);return s},getStringWidth:function(t){return t?T.test(t)?P(t):t.length:0},getMaxContinuousCount:function(t,e){const s=t.match(new RegExp("(".concat(b(e),")+"),"g"));return null===s?0:s.reduce((t,s)=>Math.max(t,s.length/e.length),0)},getMinNotPresentContinuousCount:function(t,e){const s=t.match(new RegExp("(".concat(b(e),")+"),"g"));if(null===s)return 0;const i=new Map;let r=0;for(const t of s){const s=t.length/e.length;i.set(s,!0),s>r&&(r=s)}for(let t=1;t<r;t++)if(!i.get(t))return t;return r+1},getPrecedence:_,shouldFlatten:function(t,e){return _(e)===_(t)&&("**"!==t&&((!j[t]||!j[e])&&(!("%"===e&&U[t]||"%"===t&&U[e])&&((e===t||!U[e]||!U[t])&&(!q[t]||!q[e])))))},isBitwiseOperator:function(t){return!!q[t]||"|"===t||"^"===t||"&"===t},getPenultimate:function(t){return t.length>1?t[t.length-2]:null},getLast:u,getNextNonSpaceNonCommentCharacterIndexWithStartIndex:M,getNextNonSpaceNonCommentCharacterIndex:O,getNextNonSpaceNonCommentCharacter:function(t,e,s){return t.charAt(O(t,e,s))},skip:A,skipWhitespace:w,skipSpaces:S,skipToLineEnd:N,skipEverythingButNewLine:F,skipInlineComment:k,skipTrailingComment:I,skipNewline:v,isNextLineEmptyAfterIndex:B,isNextLineEmpty:function(t,e,s){return B(t,s(e))},isPreviousLineEmpty:function(t,e,s){let i=s(e)-1;return i=S(t,i,{backwards:!0}),i=v(t,i,{backwards:!0}),i=S(t,i,{backwards:!0}),i!==v(t,i,{backwards:!0})},hasNewline:L,hasNewlineInRange:function(t,e,s){for(let i=e;i<s;++i)if("\n"===t.charAt(i))return!0;return!1},hasSpaces:function(t,e,s){return S(t,(s=s||{}).backwards?e-1:e,s)!==e},setLocStart:function(t,e){t.range?t.range[0]=e:t.start=e},setLocEnd:function(t,e){t.range?t.range[1]=e:t.end=e},startsWithNoLookaheadToken:function t(e,s){switch((e=function t(e){if(e.left)return t(e.left);return e}(e)).type){case"FunctionExpression":case"ClassExpression":case"DoExpression":return s;case"ObjectExpression":return!0;case"MemberExpression":case"OptionalMemberExpression":return t(e.object,s);case"TaggedTemplateExpression":return"FunctionExpression"!==e.tag.type&&t(e.tag,s);case"CallExpression":case"OptionalCallExpression":return"FunctionExpression"!==e.callee.type&&t(e.callee,s);case"ConditionalExpression":return t(e.test,s);case"UpdateExpression":return!e.prefix&&t(e.argument,s);case"BindExpression":return e.object&&t(e.object,s);case"SequenceExpression":return t(e.expressions[0],s);case"TSAsExpression":return t(e.expression,s);default:return!1}},getAlignmentSize:V,getIndentSize:function(t,e){const s=t.lastIndexOf("\n");return-1===s?0:V(t.slice(s+1).match(/^[ \t]*/)[0],e)},getPreferredQuote:z,printString:function(t,e,s){const i=t.slice(1,-1),r=!i.includes('"')&&!i.includes("'"),a="json"===e.parser?'"':e.__isInHtmlAttribute?"'":z(t,e.singleQuote?"'":'"');return s?r?a+i+a:t:H(i,a,!("css"===e.parser||"less"===e.parser||"scss"===e.parser||e.embeddedInHtml))},printNumber:function(t){return t.toLowerCase().replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/,"$1$2$3").replace(/^([+-]?[\d.]+)e[+-]?0+$/,"$1").replace(/^([+-])?\./,"$10.").replace(/(\.\d+?)0+(?=e|$)/,"$1").replace(/\.(?=e|$)/,"")},hasIgnoreComment:function(t){return W(t.getValue())},hasNodeIgnoreComment:W,isNodeIgnoreComment:K,makeString:H,addLeadingComment:function(t,e){e.leading=!0,e.trailing=!1,J(t,e)},addDanglingComment:function(t,e){e.leading=!1,e.trailing=!1,J(t,e)},addTrailingComment:function(t,e){e.leading=!1,e.trailing=!0,J(t,e)},isWithinParentArrayProperty:function(t,e){const s=t.getValue(),i=t.getParentNode();if(null==i)return!1;if(!Array.isArray(i[e]))return!1;const r=t.getName();return i[e][r]===s}};const{getMaxContinuousCount:G,getStringWidth:Q,getAlignmentSize:Y,getIndentSize:$,skip:Z,skipWhitespace:tt,skipSpaces:et,skipNewline:st,skipToLineEnd:it,skipEverythingButNewLine:rt,skipInlineComment:at,skipTrailingComment:nt,hasNewline:ot,hasNewlineInRange:ht,hasSpaces:pt,isNextLineEmpty:ct,isNextLineEmptyAfterIndex:ut,isPreviousLineEmpty:lt,getNextNonSpaceNonCommentCharacterIndex:dt,makeString:mt,addLeadingComment:ft,addDanglingComment:Dt,addTrailingComment:yt}=X;var xt={getMaxContinuousCount:G,getStringWidth:Q,getAlignmentSize:Y,getIndentSize:$,skip:Z,skipWhitespace:tt,skipSpaces:et,skipNewline:st,skipToLineEnd:it,skipEverythingButNewLine:rt,skipInlineComment:at,skipTrailingComment:nt,hasNewline:ot,hasNewlineInRange:ht,hasSpaces:pt,isNextLineEmpty:ct,isNextLineEmptyAfterIndex:ut,isPreviousLineEmpty:lt,getNextNonSpaceNonCommentCharacterIndex:dt,makeString:mt,addLeadingComment:ft,addDanglingComment:Dt,addTrailingComment:yt};const{addLeadingComment:gt,addTrailingComment:Pt,addDanglingComment:Et,getNextNonSpaceNonCommentCharacterIndex:Ct}=xt;function bt(t,e){const s=t.body.filter(t=>"EmptyStatement"!==t.type);0===s.length?Et(t,e):gt(s[0],e)}function Tt(t,e){"BlockStatement"===t.type?bt(t,e):gt(t,e)}function At(t,e,s,i,r,a){if(!s||"IfStatement"!==s.type||!i)return!1;return")"===X.getNextNonSpaceNonCommentCharacter(t,r,a.locEnd)?(Pt(e,r),!0):e===s.consequent&&i===s.alternate?("BlockStatement"===e.type?Pt(e,r):Et(s,r),!0):"BlockStatement"===i.type?(bt(i,r),!0):"IfStatement"===i.type?(Tt(i.consequent,r),!0):s.consequent===i&&(gt(i,r),!0)}function wt(t,e,s,i,r,a){if(!s||"WhileStatement"!==s.type||!i)return!1;return")"===X.getNextNonSpaceNonCommentCharacter(t,r,a.locEnd)?(Pt(e,r),!0):"BlockStatement"===i.type&&(bt(i,r),!0)}function St(t,e,s,i){return!(!t||"TryStatement"!==t.type&&"CatchClause"!==t.type||!s)&&("CatchClause"===t.type&&e?(Pt(e,i),!0):"BlockStatement"===s.type?(bt(s,i),!0):"TryStatement"===s.type?(Tt(s.finalizer,i),!0):"CatchClause"===s.type&&(Tt(s.body,i),!0))}function Nt(t,e,s,i){return!(!(t&&("ClassDeclaration"===t.type||"ClassExpression"===t.type)&&t.decorators&&t.decorators.length>0)||s&&"Decorator"===s.type)&&(t.decorators&&0!==t.decorators.length?Pt(t.decorators[t.decorators.length-1],i):gt(t,i),!0)}function Ft(t,e,s,i,r){return e&&s&&("Property"===e.type||"TSDeclareMethod"===e.type||"TSAbstractMethodDefinition"===e.type)&&"Identifier"===s.type&&e.key===s&&":"!==X.getNextNonSpaceNonCommentCharacter(t,s,r.locEnd)?(Pt(s,i),!0):!(!s||!e||"Decorator"!==s.type||"ClassMethod"!==e.type&&"ClassProperty"!==e.type&&"TSAbstractClassProperty"!==e.type&&"TSAbstractMethodDefinition"!==e.type&&"TSDeclareMethod"!==e.type&&"MethodDefinition"!==e.type)&&(Pt(s,i),!0)}function kt(t,e,s,i,r,a){if(e&&"FunctionTypeParam"===e.type&&s&&"FunctionTypeAnnotation"===s.type&&i&&"FunctionTypeParam"!==i.type)return Pt(e,r),!0;if(e&&("Identifier"===e.type||"AssignmentPattern"===e.type)&&s&&Mt(s)&&")"===X.getNextNonSpaceNonCommentCharacter(t,r,a.locEnd))return Pt(e,r),!0;if(s&&"FunctionDeclaration"===s.type&&i&&"BlockStatement"===i.type){const e=(()=>{if(0!==(s.params||s.parameters).length)return X.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(t,a.locEnd(X.getLast(s.params||s.parameters)));const e=X.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(t,a.locEnd(s.id));return X.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(t,e+1)})();if(a.locStart(r)>e)return bt(i,r),!0}return!1}function It(t,e){return!(!t||"ImportSpecifier"!==t.type)&&(gt(t,e),!0)}function vt(t,e){return!(!t||"LabeledStatement"!==t.type)&&(gt(t,e),!0)}function Lt(t,e,s,i){return e&&e.body&&0===e.body.length?(i?Et(e,s):gt(e,s),!0):!(!t||"Program"!==t.type||0!==t.body.length||!t.directives||0!==t.directives.length)&&(i?Et(t,s):gt(t,s),!0)}function Bt(t){return"Block"===t.type||"CommentBlock"===t.type}function Mt(t){return"ArrowFunctionExpression"===t.type||"FunctionExpression"===t.type||"FunctionDeclaration"===t.type||"ObjectMethod"===t.type||"ClassMethod"===t.type||"TSDeclareFunction"===t.type||"TSCallSignatureDeclaration"===t.type||"TSConstructSignatureDeclaration"===t.type||"TSConstructSignatureDeclaration"===t.type||"TSMethodSignature"===t.type||"TSConstructorType"===t.type||"TSFunctionType"===t.type||"TSDeclareMethod"===t.type}function Ot(t){return Bt(t)&&"*"===t.value[0]&&/@type\b/.test(t.value)}var Rt={handleOwnLineComment:function(t,e,s,i,r){const{precedingNode:a,enclosingNode:n,followingNode:o}=t;return kt(e,a,n,o,t,s)||function(t,e,s){if(t&&("MemberExpression"===t.type||"OptionalMemberExpression"===t.type)&&e&&"Identifier"===e.type)return gt(t,s),!0;return!1}(n,o,t)||At(e,a,n,o,t,s)||wt(e,a,n,o,t,s)||St(n,a,o,t)||Nt(n,a,o,t)||It(n,t)||function(t,e,s){if(t&&("ForInStatement"===t.type||"ForOfStatement"===t.type))return gt(t,s),!0;return!1}(n,0,t)||function(t,e,s,i){if(e&&("UnionTypeAnnotation"===e.type||"TSUnionType"===e.type))return X.isNodeIgnoreComment(i)&&(s.prettierIgnore=!0,i.unignore=!0),!!t&&(Pt(t,i),!0);s&&("UnionTypeAnnotation"===s.type||"TSUnionType"===s.type)&&X.isNodeIgnoreComment(i)&&(s.types[0].prettierIgnore=!0,i.unignore=!0);return!1}(a,n,o,t)||Lt(n,i,t,r)||function(t,e,s,i,r){if(s&&"ImportSpecifier"===s.type&&e&&"ImportDeclaration"===e.type&&X.hasNewline(t,r.locEnd(i)))return Pt(s,i),!0;return!1}(e,n,a,t,s)||function(t,e){if(t&&"AssignmentPattern"===t.type)return gt(t,e),!0;return!1}(n,t)||Ft(e,n,a,t,s)||vt(n,t)},handleEndOfLineComment:function(t,e,s,i,r){const{precedingNode:a,enclosingNode:n,followingNode:o}=t;return function(t,e){if(t&&Ot(e))return gt(t,e),!0;return!1}(o,t)||kt(e,a,n,o,t,s)||function(t,e,s,i,r,a){const n=e&&!X.hasNewlineInRange(r,a.locEnd(e),a.locStart(i));if((!e||!n)&&t&&"ConditionalExpression"===t.type&&s)return gt(s,i),!0;return!1}(n,a,o,t,e,s)||It(n,t)||At(e,a,n,o,t,s)||wt(e,a,n,o,t,s)||St(n,a,o,t)||Nt(n,a,o,t)||vt(n,t)||function(t,e,s){if(e&&("CallExpression"===e.type||"OptionalCallExpression"===e.type)&&t&&e.callee===t&&e.arguments.length>0)return gt(e.arguments[0],s),!0;return!1}(a,n,t)||function(t,e){if(t&&("Property"===t.type||"ObjectProperty"===t.type))return gt(t,e),!0;return!1}(n,t)||Lt(n,i,t,r)||function(t,e,s){if(t&&"TypeAlias"===t.type)return gt(t,s),!0;return!1}(n,0,t)||function(t,e,s){if(t&&("VariableDeclarator"===t.type||"AssignmentExpression"===t.type)&&e&&("ObjectExpression"===e.type||"ArrayExpression"===e.type||"TemplateLiteral"===e.type||"TaggedTemplateExpression"===e.type||Bt(s)))return gt(e,s),!0;return!1}(n,o,t)},handleRemainingComment:function(t,e,s,i,r){const{precedingNode:a,enclosingNode:n,followingNode:o}=t;return!!(At(e,a,n,o,t,s)||wt(e,a,n,o,t,s)||function(t,e,s){if(t&&("ObjectProperty"===t.type||"Property"===t.type)&&t.shorthand&&t.key===e&&"AssignmentPattern"===t.value.type)return Pt(t.value.left,s),!0;return!1}(n,a,t)||function(t,e,s,i){if(")"!==X.getNextNonSpaceNonCommentCharacter(t,s,i.locEnd))return!1;if(e&&(Mt(e)&&0===(e.params||e.parameters).length||("CallExpression"===e.type||"OptionalCallExpression"===e.type||"NewExpression"===e.type)&&0===e.arguments.length))return Et(e,s),!0;if(e&&"MethodDefinition"===e.type&&0===e.value.params.length)return Et(e.value,s),!0;return!1}(e,n,t,s)||Ft(e,n,a,t,s)||Lt(n,i,t,r)||function(t,e,s,i){if(!e||"ArrowFunctionExpression"!==e.type)return!1;const r=Ct(t,s,i.locEnd);if("=>"===t.slice(r,r+2))return Et(e,s),!0;return!1}(e,n,t,s)||function(t,e,s,i,r){if("("!==X.getNextNonSpaceNonCommentCharacter(t,i,r.locEnd))return!1;if(s&&e&&("FunctionDeclaration"===e.type||"FunctionExpression"===e.type||"ClassMethod"===e.type||"MethodDefinition"===e.type||"ObjectMethod"===e.type))return Pt(s,i),!0;return!1}(e,n,a,t,s)||function(t,e,s,i,r){if(!e||"TSMappedType"!==e.type)return!1;if(i&&"TSTypeParameter"===i.type&&i.name)return gt(i.name,r),!0;if(s&&"TSTypeParameter"===s.type&&s.constraint)return Pt(s.constraint,r),!0;return!1}(0,n,a,o,t)||function(t,e){if(t&&("ContinueStatement"===t.type||"BreakStatement"===t.type)&&!t.label)return Pt(t,e),!0;return!1}(n,t)||function(t,e,s,i,r){if(!s&&e&&("TSMethodSignature"===e.type||"TSDeclareFunction"===e.type||"TSAbstractMethodDefinition"===e.type)&&";"===X.getNextNonSpaceNonCommentCharacter(t,i,r.locEnd))return Pt(e,i),!0;return!1}(e,n,o,t,s))},hasLeadingComment:function(t,e=(()=>!0)){return t.leadingComments?t.leadingComments.some(e):!!t.comments&&t.comments.some(t=>t.leading&&e(t))},isBlockComment:Bt,isTypeCastComment:Ot,getGapRegex:function(t){if(t&&"BinaryExpression"!==t.type&&"LogicalExpression"!==t.type)return/^[\s(&|]*$/},getCommentChildNodes:function(t,e){if(("typescript"===e.parser||"flow"===e.parser)&&"MethodDefinition"===t.type&&t.value&&"FunctionExpression"===t.value.type&&0===t.value.params.length&&!t.value.returnType&&(!t.value.typeParameters||0===t.value.typeParameters.length)&&t.value.body)return[...t.decorators||[],t.key,t.value.body]}};const{getLast:_t,getNextNonSpaceNonCommentCharacter:jt}=X,{composeLoc:Ut,locEnd:qt}=m,{isTypeCastComment:Vt}=Rt;function zt(t,e,s,i){if(!t||"object"!=typeof t)return;if(Array.isArray(t)){for(let s=0;s<t.length;s++)zt(t[s],e,t,s);return}if("string"!=typeof t.type)return;for(const s of Object.keys(t))zt(t[s],e,t,s);const r=e(t);r&&(s[i]=r)}function Ht(t){return"LogicalExpression"===t.type&&"LogicalExpression"===t.right.type&&t.operator===t.right.operator}var Wt=function(t,e){if("typescript"!==e.parser&&"flow"!==e.parser){const e=new Set;zt(t,t=>{t.leadingComments&&t.leadingComments.some(Vt)&&e.add(t.start)}),zt(t,t=>{if("ParenthesizedExpression"===t.type&&!e.has(t.start)){const{expression:e}=t;return e.extra||(e.extra={}),e.extra.parenthesized=!0,e.extra.parenStart=t.start,e}})}return zt(t,t=>{switch(t.type){case"LogicalExpression":if(Ht(t))return function t(e){if(!Ht(e))return e;return t(Object.assign({type:"LogicalExpression",operator:e.operator,left:t(Object.assign({type:"LogicalExpression",operator:e.operator,left:e.left,right:e.right.left},Ut(e.left,e.right.left))),right:e.right.right},Ut(e)))}(t);break;case"VariableDeclaration":{const s=_t(t.declarations);s&&s.init&&function(t,s){if(";"===e.originalText[qt(s)])return;Array.isArray(t.range)?t.range=[t.range[0],s.range[1]]:t.end=s.end;t.loc=Object.assign({},t.loc,{end:t.loc.end})}(t,s);break}case"TSParenthesizedType":return Object.assign({},t.typeAnnotation,{},Ut(t));case"TSUnionType":case"TSIntersectionType":if(1===t.types.length)return Object.assign({},t.types[0],{},Ut(t));break;case"TSTypeParameter":"string"==typeof t.name&&(t.name=Object.assign({type:"Identifier",name:t.name},Ut(t,t.name.length)));break;case"SequenceExpression":t.end&&t.end>_t(t.expressions).end&&(t.end=_t(t.expressions).end);break;case"ClassProperty":t.key&&"TSPrivateIdentifier"===t.key.type&&"?"===jt(e.originalText,t.key,qt)&&(t.optional=!0)}}),t},Kt=i((function(t,e){Object.defineProperty(e,"__esModule",{value:!0});class s{constructor(t,e={}){this.label=t,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.rightAssociative=!!e.rightAssociative,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=null!=e.binop?e.binop:null,this.updateContext=null}}const i=new Map;function r(t,e={}){e.keyword=t;const r=new s(t,e);return i.set(t,r),r}function a(t,e){return new s(t,{beforeExpr:!0,binop:e})}const n={num:new s("num",{startsExpr:!0}),bigint:new s("bigint",{startsExpr:!0}),regexp:new s("regexp",{startsExpr:!0}),string:new s("string",{startsExpr:!0}),name:new s("name",{startsExpr:!0}),eof:new s("eof"),bracketL:new s("[",{beforeExpr:!0,startsExpr:!0}),bracketHashL:new s("#[",{beforeExpr:!0,startsExpr:!0}),bracketBarL:new s("[|",{beforeExpr:!0,startsExpr:!0}),bracketR:new s("]"),bracketBarR:new s("|]"),braceL:new s("{",{beforeExpr:!0,startsExpr:!0}),braceBarL:new s("{|",{beforeExpr:!0,startsExpr:!0}),braceHashL:new s("#{",{beforeExpr:!0,startsExpr:!0}),braceR:new s("}"),braceBarR:new s("|}"),parenL:new s("(",{beforeExpr:!0,startsExpr:!0}),parenR:new s(")"),comma:new s(",",{beforeExpr:!0}),semi:new s(";",{beforeExpr:!0}),colon:new s(":",{beforeExpr:!0}),doubleColon:new s("::",{beforeExpr:!0}),dot:new s("."),question:new s("?",{beforeExpr:!0}),questionDot:new s("?."),arrow:new s("=>",{beforeExpr:!0}),template:new s("template"),ellipsis:new s("...",{beforeExpr:!0}),backQuote:new s("`",{startsExpr:!0}),dollarBraceL:new s("${",{beforeExpr:!0,startsExpr:!0}),at:new s("@"),hash:new s("#",{startsExpr:!0}),interpreterDirective:new s("#!..."),eq:new s("=",{beforeExpr:!0,isAssign:!0}),assign:new s("_=",{beforeExpr:!0,isAssign:!0}),incDec:new s("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),bang:new s("!",{beforeExpr:!0,prefix:!0,startsExpr:!0}),tilde:new s("~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),pipeline:a("|>",0),nullishCoalescing:a("??",1),logicalOR:a("||",1),logicalAND:a("&&",2),bitwiseOR:a("|",3),bitwiseXOR:a("^",4),bitwiseAND:a("&",5),equality:a("==/!=/===/!==",6),relational:a("</>/<=/>=",7),bitShift:a("<</>>/>>>",8),plusMin:new s("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:new s("%",{beforeExpr:!0,binop:10,startsExpr:!0}),star:a("*",10),slash:a("/",10),exponent:new s("**",{beforeExpr:!0,binop:11,rightAssociative:!0}),_break:r("break"),_case:r("case",{beforeExpr:!0}),_catch:r("catch"),_continue:r("continue"),_debugger:r("debugger"),_default:r("default",{beforeExpr:!0}),_do:r("do",{isLoop:!0,beforeExpr:!0}),_else:r("else",{beforeExpr:!0}),_finally:r("finally"),_for:r("for",{isLoop:!0}),_function:r("function",{startsExpr:!0}),_if:r("if"),_return:r("return",{beforeExpr:!0}),_switch:r("switch"),_throw:r("throw",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_try:r("try"),_var:r("var"),_const:r("const"),_while:r("while",{isLoop:!0}),_with:r("with"),_new:r("new",{beforeExpr:!0,startsExpr:!0}),_this:r("this",{startsExpr:!0}),_super:r("super",{startsExpr:!0}),_class:r("class",{startsExpr:!0}),_extends:r("extends",{beforeExpr:!0}),_export:r("export"),_import:r("import",{startsExpr:!0}),_null:r("null",{startsExpr:!0}),_true:r("true",{startsExpr:!0}),_false:r("false",{startsExpr:!0}),_in:r("in",{beforeExpr:!0,binop:7}),_instanceof:r("instanceof",{beforeExpr:!0,binop:7}),_typeof:r("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:r("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:r("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},o=/\r\n?|[\n\u2028\u2029]/,h=new RegExp(o.source,"g");function p(t){switch(t){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}const c=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;function u(t){switch(t){case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8239:case 8287:case 12288:case 65279:return!0;default:return!1}}class l{constructor(t,e){this.line=t,this.column=e}}class d{constructor(t,e){this.start=t,this.end=e}}function m(t){return t[t.length-1]}const f=Object.freeze({ArgumentsDisallowedInInitializer:"'arguments' is not allowed in class field initializer",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function",AwaitExpressionFormalParameter:"await is not allowed in async function parameters",AwaitNotInAsyncFunction:"Can not use keyword 'await' outside an async function",BadGetterArity:"getter must not have any formal parameters",BadSetterArity:"setter must have exactly one formal parameter",BadSetterRestParameter:"setter function argument must not be a rest parameter",ConstructorClassField:"Classes may not have a field named 'constructor'",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'",ConstructorIsAccessor:"Class constructor may not be an accessor",ConstructorIsAsync:"Constructor can't be an async function",ConstructorIsGenerator:"Constructor can't be a generator",DeclarationMissingInitializer:"%0 require an initialization value",DecoratorBeforeExport:"Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorExportClass:"Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",DecoratorSemicolon:"Decorators must not be followed by a semicolon",DeletePrivateField:"Deleting a private field is not allowed",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:"`%0` has already been exported. Exported identifiers must be unique.",DuplicateProto:"Redefinition of __proto__ property",DuplicateRegExpFlags:"Duplicate regular expression flag",ElementAfterRest:"Rest element must be last element",EscapedCharNotAnIdentifier:"Invalid Unicode escape",ForInOfLoopInitializer:"%0 loop variable declaration may not have an initializer",GeneratorInSingleStatementContext:"Generators can only be declared at the top level or inside a block",IllegalBreakContinue:"Unsyntactic %0",IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list",IllegalReturn:"'return' outside of function",ImportCallArgumentTrailingComma:"Trailing comma is disallowed inside import(...) arguments",ImportCallArity:"import() requires exactly one argument",ImportCallArityLtOne:"Dynamic imports require a parameter: import('a.js')",ImportCallNotNewExpression:"Cannot use new with import(...)",ImportCallSpreadArgument:"... is not allowed in import()",ImportMetaOutsideModule:"import.meta may appear only with 'sourceType: \"module\"'",ImportOutsideModule:"'import' and 'export' may appear only with 'sourceType: \"module\"'",InvalidCodePoint:"Code point out of bounds",InvalidDigit:"Expected number in radix %0",InvalidEscapeSequence:"Bad character escape sequence",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template",InvalidEscapedReservedWord:"Escape sequence in keyword %0",InvalidIdentifier:"Invalid identifier %0",InvalidLhs:"Invalid left-hand side in %0",InvalidLhsBinding:"Binding invalid left-hand side in %0",InvalidNumber:"Invalid number",InvalidOrUnexpectedToken:"Unexpected character '%0'",InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern",InvalidPrivateFieldResolution:"Private name #%0 is not defined",InvalidPropertyBindingPattern:"Binding member expression",InvalidRestAssignmentPattern:"Invalid rest operator's argument",LabelRedeclaration:"Label '%0' is already declared",LetInLexicalBinding:"'let' is not allowed to be used as a name in 'let' or 'const' declarations.",MalformedRegExpFlags:"Invalid regular expression flag",MissingClassName:"A class name is required",MissingEqInAssignment:"Only '=' operator can be used for specifying default value.",MissingUnicodeEscape:"Expecting Unicode escape sequence \\uXXXX",MixingCoalesceWithLogical:"Nullish coalescing operator(??) requires parens when mixing with logical operators",ModuleExportUndefined:"Export '%0' is not defined",MultipleDefaultsInSwitch:"Multiple default clauses",NewlineAfterThrow:"Illegal newline after throw",NoCatchOrFinally:"Missing catch or finally clause",NumberIdentifier:"Identifier directly after number",NumericSeparatorInEscapeSequence:"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",ObsoleteAwaitStar:"await* has been removed from the async functions proposal. Use Promise.all() instead.",OptionalChainingNoNew:"constructors in/after an Optional Chain are not allowed",OptionalChainingNoTemplate:"Tagged Template Literals are not allowed in optionalChain",ParamDupe:"Argument name clash",PatternHasAccessor:"Object pattern can't contain getter or setter",PatternHasMethod:"Object pattern can't contain methods",PipelineBodyNoArrow:'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',PipelineBodySequenceExpression:"Pipeline body may not be a comma-separated sequence expression",PipelineHeadSequenceExpression:"Pipeline head should not be a comma-separated sequence expression",PipelineTopicUnused:"Pipeline is in topic style but does not use topic reference",PrimaryTopicNotAllowed:"Topic reference was used in a lexical context without topic binding",PrimaryTopicRequiresSmartPipeline:"Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",PrivateNameRedeclaration:"Duplicate private name #%0",RecordExpressionBarIncorrectEndSyntaxType:"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",RecordExpressionBarIncorrectStartSyntaxType:"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",RecordExpressionHashIncorrectStartSyntaxType:"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",RestTrailingComma:"Unexpected trailing comma after rest element",SloppyFunction:"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement",StaticPrototype:"Classes may not have static property named prototype",StrictDelete:"Deleting local variable in strict mode",StrictEvalArguments:"Assigning to '%0' in strict mode",StrictEvalArgumentsBinding:"Binding '%0' in strict mode",StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block",StrictOctalLiteral:"Legacy octal literals are not allowed in strict mode",StrictWith:"'with' in strict mode",SuperNotAllowed:"super() is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",SuperPrivateField:"Private fields can't be accessed on super",TrailingDecorator:"Decorators must be attached to a class element",TupleExpressionBarIncorrectEndSyntaxType:"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",TupleExpressionBarIncorrectStartSyntaxType:"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",TupleExpressionHashIncorrectStartSyntaxType:"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",UnexpectedArgumentPlaceholder:"Unexpected argument placeholder",UnexpectedAwaitAfterPipelineBody:'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',UnexpectedDigitAfterHash:"Unexpected digit after hash token",UnexpectedImportExport:"'import' and 'export' may only appear at the top level",UnexpectedKeyword:"Unexpected keyword '%0'",UnexpectedLeadingDecorator:"Leading decorators must be attached to a class declaration",UnexpectedLexicalDeclaration:"Lexical declaration cannot appear in a single-statement context",UnexpectedNewTarget:"new.target can only be used in functions",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits",UnexpectedPrivateField:"Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",UnexpectedReservedWord:"Unexpected reserved word '%0'",UnexpectedSuper:"super is only allowed in object methods and classes",UnexpectedToken:"Unexpected token '%'",UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnsupportedBind:"Binding should be performed on object property.",UnsupportedDecoratorExport:"A decorated export must export a class declaration",UnsupportedDefaultExport:"Only expressions, functions or classes are allowed as the `default` export.",UnsupportedImport:"import can only be used in import() or import.meta",UnsupportedMetaProperty:"The only valid meta property for %0 is %0.%1",UnsupportedParameterDecorator:"Decorators cannot be used to decorate parameters",UnsupportedPropertyDecorator:"Decorators cannot be used to decorate object literal properties",UnsupportedSuper:"super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",UnterminatedComment:"Unterminated comment",UnterminatedRegExp:"Unterminated regular expression",UnterminatedString:"Unterminated string constant",UnterminatedTemplate:"Unterminated template",VarRedeclaration:"Identifier '%0' has already been declared",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator",YieldInParameter:"yield is not allowed in generator parameters",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0"});function D(t){return null!=t&&"Property"===t.type&&"init"===t.kind&&!1===t.method}class y{constructor(t,e,s,i){this.token=t,this.isExpr=!!e,this.preserveSpace=!!s,this.override=i}}const x={braceStatement:new y("{",!1),braceExpression:new y("{",!0),templateQuasi:new y("${",!1),parenStatement:new y("(",!1),parenExpression:new y("(",!0),template:new y("`",!0,!0,t=>t.readTmplToken()),functionExpression:new y("function",!0),functionStatement:new y("function",!1)};n.parenR.updateContext=n.braceR.updateContext=function(){if(1===this.state.context.length)return void(this.state.exprAllowed=!0);let t=this.state.context.pop();t===x.braceStatement&&"function"===this.curContext().token&&(t=this.state.context.pop()),this.state.exprAllowed=!t.isExpr},n.name.updateContext=function(t){let e=!1;t!==n.dot&&("of"===this.state.value&&!this.state.exprAllowed||"yield"===this.state.value&&this.prodParam.hasYield)&&(e=!0),this.state.exprAllowed=e,this.state.isIterator&&(this.state.isIterator=!1)},n.braceL.updateContext=function(t){this.state.context.push(this.braceIsBlock(t)?x.braceStatement:x.braceExpression),this.state.exprAllowed=!0},n.dollarBraceL.updateContext=function(){this.state.context.push(x.templateQuasi),this.state.exprAllowed=!0},n.parenL.updateContext=function(t){const e=t===n._if||t===n._for||t===n._with||t===n._while;this.state.context.push(e?x.parenStatement:x.parenExpression),this.state.exprAllowed=!0},n.incDec.updateContext=function(){},n._function.updateContext=n._class.updateContext=function(t){!t.beforeExpr||t===n.semi||t===n._else||t===n._return&&o.test(this.input.slice(this.state.lastTokEnd,this.state.start))||(t===n.colon||t===n.braceL)&&this.curContext()===x.b_stat?this.state.context.push(x.functionStatement):this.state.context.push(x.functionExpression),this.state.exprAllowed=!1},n.backQuote.updateContext=function(){this.curContext()===x.template?this.state.context.pop():this.state.context.push(x.template),this.state.exprAllowed=!1};let g="ªµºÀ-ÖØ-öø-ˈ-Ë‘Ë -ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ÒÒŠ-Ô¯Ô±-Õ–Õ™Õ -Öˆ×-תׯ-×²Ø -يٮٯٱ-Û“Û•Û¥Û¦Û®Û¯Ûº-Û¼Û¿ÜÜ’-ܯÝ-ޥޱߊ-ßªß´ßµßºà €-à •à šà ¤à ¨à¡€-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽà¥à¥˜-ॡॱ-ঀঅ-ঌà¦à¦à¦“-নপ-রলশ-হঽৎড়à§à§Ÿ-ৡৰৱৼਅ-ਊà¨à¨à¨“-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-àªàª-ઑઓ-નપ-રલળવ-હઽà«à« ૡૹଅ-ଌà¬à¬à¬“-ନପ-ରଲଳଵ-ହଽàœààŸ-à¡à±à®ƒà®…-ஊஎ-à®à®’-கஙசஜஞடணதந-பம-ஹà¯à°…-ఌఎ-à°à°’-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-à²à²’-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-à´à´’-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-à·†à¸-ะาำเ-ๆàºàº‚ຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿá-á•áš-áá¡á¥á¦á®-á°áµ-á‚á‚Žá‚ -ჅჇáƒáƒ-ჺჼ-ቈቊ-á‰á‰-ቖቘቚ-á‰á‰ -ኈኊ-áŠáŠ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-áŒáŒ’-ጕጘ-ášáŽ€-áŽáŽ -áµá¸-á½á-ᙬᙯ-ᙿáš-áššáš -ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱá€-á‘á -á¬á®-á°áž€-ឳៗៜá -ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞá¥-á¥á¥°-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳá…-á‹á®ƒ-ᮠᮮᮯᮺ-ᯥᰀ-á°£á±-á±á±š-ᱽᲀ-ᲈá²-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-á¼á¼ -ὅὈ-á½á½-ὗὙὛá½á½Ÿ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-á¿Œá¿-á¿“á¿–-Ίῠ-Ῥῲ-ῴῶ-ῼâ±â¿â‚-ₜℂℇℊ-ℓℕ℘-â„ℤΩℨK-ℹℼ-â„¿â……-â…‰â…Žâ… -ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧâ´â´°-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-â·Žâ·-â·–â·˜-ⷞ々-〇〡-〩〱-〵〸-〼ã-ã‚–ã‚›-ã‚Ÿã‚¡-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿã€-䶿一-鿼ꀀ-ê’Œê“-ꓽꔀ-ꘌê˜-ꘟꘪꘫꙀ-ꙮꙿ-êšêš -ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ê ê ƒ-ê …ê ‡-ê Šê Œ-ê ¢ê¡€-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ê¥†ê¥ -ꥼꦄ-ꦲê§ê§ -ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ê©‚ê©„-ê©‹ê© -ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ê«ê« -ꫪꫲ-ê«´ê¬-ꬆꬉ-ꬎꬑ-ê¬–ê¬ -ꬦꬨ-ꬮꬰ-êšêœ-ê©ê°-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-ï©ï©°-龎ff-stﬓ-ﬗï¬ï¬Ÿ-ﬨשׁ-זּטּ-לּמּï€ïïƒï„ï†-ﮱﯓ-ï´½ïµ-ï¶ï¶’-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Zï½-zヲ-하-ᅦᅧ-ï¿ï¿’-ï¿—ï¿š-ï¿œ",P="‌â€Â·Ì€-ͯ·҃-Ò‡Ö‘-Ö½Ö¿×ׇׂׅׄØ-ØšÙ‹-٩ٰۖ-ۜ۟-Û¤Û§Û¨Ûª-ÛÛ°-۹ܑܰ-ÝŠÞ¦-ް߀-߉߫-ß³ß½à –-à ™à ›-à £à ¥-à §à ©-à à¡™-࡛࣓-ࣣ࣡-ःऺ-़ा-à¥à¥‘-ॗॢॣ०-९à¦-ঃ়া-ৄেৈো-à§à§—ৢৣ০-৯৾à¨-ਃ਼ਾ-ੂੇੈੋ-à©à©‘੦-ੱੵàª-ઃ઼ા-ૅે-ૉો-à«à«¢à«£à«¦-૯ૺ-à«¿à¬-ଃ଼ା-à„à‡àˆà‹-àà•-à—à¢à£à¦-à¯à®‚ா-ூெ-ைொ-à¯à¯—௦-௯ఀ-à°„à°¾-ౄె-ైొ-à±à±•à±–ౢౣ౦-౯à²-ಃ಼ಾ-ೄೆ-ೈೊ-à³à³•à³–ೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-àµàµ—ൢൣ൦-൯à¶-ඃ්à·-ුූෘ-à·Ÿà·¦-෯ෲෳัิ-ฺ็-๎à¹-๙ັິ-ຼ່-à»à»-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇à¾-ྗྙ-ྼ࿆ါ-ှá€-á‰á–-á™áž-á á¢-á¤á§-áá±-á´á‚‚-á‚á‚-á‚á-áŸá©-á±áœ’-᜔ᜲ-᜴á’á“á²á³áž´-៓áŸáŸ -áŸ©á ‹-á á -á ™á¢©á¤ -ᤫᤰ-᤻᥆-á¥á§-᧚ᨗ-ᨛᩕ-á©žá© -᩿᩼-᪉áª-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-á„á-á™á«-á³á®€-ᮂᮡ-á®á®°-᮹᯦-᯳ᰤ-á°·á±€-᱉á±-á±™á³-á³’á³”-᳨á³á³´á³·-᳹᷀-᷹᷻-᷿‿â€â”âƒ-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-ã€¯ã‚™ã‚šê˜ -꘩꙯ꙴ-ê™½êšžêšŸê›°ê›±ê ‚ê †ê ‹ê £-ê §ê ¬ê¢€ê¢ê¢´-ꣅê£-ê£™ê£ -꣱ꣿ-꤉ꤦ-ê¤ê¥‡-꥓ꦀ-ꦃ꦳-꧀ê§-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌê©ê©-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿ê«ê««-ꫯꫵ꫶ꯣ-ꯪ꯬ê¯ê¯°-꯹ﬞ︀-ï¸ï¸ -︯︳︴ï¹-ï¹ï¼-9_";const E=new RegExp("["+g+"]"),C=new RegExp("["+g+P+"]");g=P=null;const b=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938],T=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function A(t,e){let s=65536;for(let i=0,r=e.length;i<r;i+=2){if(s+=e[i],s>t)return!1;if(s+=e[i+1],s>=t)return!0}return!1}function w(t){return t<65?36===t:t<=90||(t<97?95===t:t<=122||(t<=65535?t>=170&&E.test(String.fromCharCode(t)):A(t,b)))}function S(t){return t<48?36===t:t<58||!(t<65)&&(t<=90||(t<97?95===t:t<=122||(t<=65535?t>=170&&C.test(String.fromCharCode(t)):A(t,b)||A(t,T))))}const N=["implements","interface","let","package","private","protected","public","static","yield"],F=["eval","arguments"],k=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete"]),I=new Set(N),v=new Set(F);function L(t,e){return e&&"await"===t||"enum"===t}function B(t,e){return L(t,e)||I.has(t)}function M(t){return v.has(t)}function O(t,e){return B(t,e)||M(t)}const R=/^in(stanceof)?$/;const _=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),j=Object.freeze({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module",AssignReservedType:"Cannot overwrite reserved type %0",DeclareClassElement:"The `declare` modifier can only appear on class fields.",DeclareClassFieldInitializer:"Initializers are not allowed in fields with the `declare` modifier.",DuplicateDeclareModuleExports:"Duplicate `declare module.exports` statement",EnumBooleanMemberNotInitialized:"Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",EnumDuplicateMemberName:"Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",EnumInconsistentMemberValues:"Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",EnumInvalidExplicitType:"Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",EnumInvalidExplicitTypeUnknownSupplied:"Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",EnumInvalidMemberInitializerPrimaryType:"Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",EnumInvalidMemberInitializerSymbolType:"Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",EnumInvalidMemberInitializerUnknownType:"The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",EnumInvalidMemberName:"Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",EnumNumberMemberNotInitialized:"Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",EnumStringMemberInconsistentlyInitailized:"String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",ImportTypeShorthandOnlyInPureImport:"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements",InexactInsideExact:"Explicit inexact syntax cannot appear inside an explicit exact object type",InexactInsideNonObject:"Explicit inexact syntax cannot appear in class or interface definitions",InexactVariance:"Explicit inexact syntax cannot have variance",InvalidNonTypeImportInDeclareModule:"Imports within a `declare module` body must always be `import type` or `import typeof`",MissingTypeParamDefault:"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",NestedDeclareModule:"`declare module` cannot be used inside another `declare module`",NestedFlowComment:"Cannot have a flow comment inside another flow comment",OptionalBindingPattern:"A binding pattern parameter cannot be optional in an implementation signature.",SpreadVariance:"Spread properties cannot have variance",TypeBeforeInitializer:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",TypeCastInPattern:"The type cast expression is expected to be wrapped with parenthesis",UnexpectedExplicitInexactInObject:"Explicit inexact syntax must appear at the end of an inexact object",UnexpectedReservedType:"Unexpected reserved type %0",UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint"',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration",UnsupportedDeclareExportKind:"`declare export %0` is not supported. Use `%1` instead",UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module",UnterminatedFlowComment:"Unterminated flow-comment"});function U(t){return"type"===t.importKind||"typeof"===t.importKind}function q(t){return(t.type===n.name||!!t.type.keyword)&&"from"!==t.value}const V={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};const z=/\*?\s*@((?:no)?flow)\b/;const H={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"Â¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"Â",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Ã",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Ã…",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"ÃŒ",Iacute:"Ã",Icirc:"ÃŽ",Iuml:"Ã",ETH:"Ã",Ntilde:"Ñ",Ograve:"Ã’",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ãœ",Yacute:"Ã",THORN:"Þ",szlig:"ß",agrave:"à ",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"Ã¥",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"Ã",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Å’",oelig:"Å“",Scaron:"Å ",scaron:"Å¡",Yuml:"Ÿ",fnof:"Æ’",circ:"ˆ",tilde:"Ëœ",Alpha:"Α",Beta:"Î’",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Îœ",Nu:"Î",Xi:"Ξ",Omicron:"Ο",Pi:"Î ",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Î¥",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"Ï€",rho:"Ï",sigmaf:"Ï‚",sigma:"σ",tau:"Ï„",upsilon:"Ï…",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"Ï‘",upsih:"Ï’",piv:"Ï–",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"â€",lrm:"‎",rlm:"â€",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"â€",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"â„",euro:"€",image:"â„‘",weierp:"℘",real:"â„œ",trade:"â„¢",alefsym:"ℵ",larr:"â†",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"â‡",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"âˆ",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"âˆ",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"â‹…",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"â—Š",spades:"â™ ",clubs:"♣",hearts:"♥",diams:"♦"},W=/^[\da-fA-F]+$/,K=/^\d+$/,J=Object.freeze({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression",MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>",MissingClosingTagElement:"Expected corresponding JSX closing tag for <%0>",UnsupportedJsxValue:"JSX value should be either an expression or a quoted JSX text",UnterminatedJsxContent:"Unterminated JSX contents",UnwrappedAdjacentJSXElements:"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"});function X(t){return!!t&&("JSXOpeningFragment"===t.type||"JSXClosingFragment"===t.type)}function G(t){if("JSXIdentifier"===t.type)return t.name;if("JSXNamespacedName"===t.type)return t.namespace.name+":"+t.name.name;if("JSXMemberExpression"===t.type)return G(t.object)+"."+G(t.property);throw new Error("Node had unexpected type: "+t.type)}x.j_oTag=new y("<tag",!1),x.j_cTag=new y("</tag",!1),x.j_expr=new y("<tag>...</tag>",!0,!0),n.jsxName=new s("jsxName"),n.jsxText=new s("jsxText",{beforeExpr:!0}),n.jsxTagStart=new s("jsxTagStart",{startsExpr:!0}),n.jsxTagEnd=new s("jsxTagEnd"),n.jsxTagStart.updateContext=function(){this.state.context.push(x.j_expr),this.state.context.push(x.j_oTag),this.state.exprAllowed=!1},n.jsxTagEnd.updateContext=function(t){const e=this.state.context.pop();e===x.j_oTag&&t===n.slash||e===x.j_cTag?(this.state.context.pop(),this.state.exprAllowed=this.curContext()===x.j_expr):this.state.exprAllowed=!0};class Q{constructor(t){this.var=[],this.lexical=[],this.functions=[],this.flags=t}}class Y{constructor(t,e){this.scopeStack=[],this.undefinedExports=new Map,this.undefinedPrivateNames=new Map,this.raise=t,this.inModule=e}get inFunction(){return(2&this.currentVarScope().flags)>0}get allowSuper(){return(16&this.currentThisScope().flags)>0}get allowDirectSuper(){return(32&this.currentThisScope().flags)>0}get inClass(){return(64&this.currentThisScope().flags)>0}get inNonArrowFunction(){return(2&this.currentThisScope().flags)>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(t){return new Q(t)}enter(t){this.scopeStack.push(this.createScope(t))}exit(){this.scopeStack.pop()}treatFunctionsAsVarInScope(t){return!!(2&t.flags||!this.inModule&&1&t.flags)}declareName(t,e,s){let i=this.currentScope();if(8&e||16&e)this.checkRedeclarationInScope(i,t,e,s),16&e?i.functions.push(t):i.lexical.push(t),8&e&&this.maybeExportDefined(i,t);else if(4&e)for(let r=this.scopeStack.length-1;r>=0&&(i=this.scopeStack[r],this.checkRedeclarationInScope(i,t,e,s),i.var.push(t),this.maybeExportDefined(i,t),!(131&i.flags));--r);this.inModule&&1&i.flags&&this.undefinedExports.delete(t)}maybeExportDefined(t,e){this.inModule&&1&t.flags&&this.undefinedExports.delete(e)}checkRedeclarationInScope(t,e,s,i){this.isRedeclaredInScope(t,e,s)&&this.raise(i,f.VarRedeclaration,e)}isRedeclaredInScope(t,e,s){return!!(1&s)&&(8&s?t.lexical.indexOf(e)>-1||t.functions.indexOf(e)>-1||t.var.indexOf(e)>-1:16&s?t.lexical.indexOf(e)>-1||!this.treatFunctionsAsVarInScope(t)&&t.var.indexOf(e)>-1:t.lexical.indexOf(e)>-1&&!(8&t.flags&&t.lexical[0]===e)||!this.treatFunctionsAsVarInScope(t)&&t.functions.indexOf(e)>-1)}checkLocalExport(t){-1===this.scopeStack[0].lexical.indexOf(t.name)&&-1===this.scopeStack[0].var.indexOf(t.name)&&-1===this.scopeStack[0].functions.indexOf(t.name)&&this.undefinedExports.set(t.name,t.start)}currentScope(){return this.scopeStack[this.scopeStack.length-1]}currentVarScope(){for(let t=this.scopeStack.length-1;;t--){const e=this.scopeStack[t];if(131&e.flags)return e}}currentThisScope(){for(let t=this.scopeStack.length-1;;t--){const e=this.scopeStack[t];if((131&e.flags||64&e.flags)&&!(4&e.flags))return e}}}class $ extends Q{constructor(...t){super(...t),this.types=[],this.enums=[],this.constEnums=[],this.classes=[],this.exportOnlyBindings=[]}}class Z extends Y{createScope(t){return new $(t)}declareName(t,e,s){const i=this.currentScope();if(1024&e)return this.maybeExportDefined(i,t),void i.exportOnlyBindings.push(t);super.declareName(...arguments),2&e&&(1&e||(this.checkRedeclarationInScope(i,t,e,s),this.maybeExportDefined(i,t)),i.types.push(t)),256&e&&i.enums.push(t),512&e&&i.constEnums.push(t),128&e&&i.classes.push(t)}isRedeclaredInScope(t,e,s){if(t.enums.indexOf(e)>-1){if(256&s){return!!(512&s)!==t.constEnums.indexOf(e)>-1}return!0}return 128&s&&t.classes.indexOf(e)>-1?t.lexical.indexOf(e)>-1&&!!(1&s):!!(2&s&&t.types.indexOf(e)>-1)||super.isRedeclaredInScope(...arguments)}checkLocalExport(t){-1===this.scopeStack[0].types.indexOf(t.name)&&-1===this.scopeStack[0].exportOnlyBindings.indexOf(t.name)&&super.checkLocalExport(t)}}class tt{constructor(){this.stacks=[]}enter(t){this.stacks.push(t)}exit(){this.stacks.pop()}currentFlags(){return this.stacks[this.stacks.length-1]}get hasAwait(){return(2&this.currentFlags())>0}get hasYield(){return(1&this.currentFlags())>0}get hasReturn(){return(4&this.currentFlags())>0}}function et(t,e){return(t?2:0)|(e?1:0)}function st(t){if(null==t)throw new Error("Unexpected ".concat(t," value."));return t}function it(t){if(!t)throw new Error("Assert fail")}const rt=Object.freeze({ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier",DeclareClassFieldHasInitializer:"'declare' class fields cannot have an initializer",DuplicateModifier:"Duplicate modifier: '%0'",EmptyHeritageClauseType:"'%0' list cannot be empty.",IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier",IndexSignatureHasAccessibility:"Index signatures cannot have an accessibility modifier ('%0')",IndexSignatureHasStatic:"Index signatures cannot have the 'static' modifier",OptionalTypeBeforeRequired:"A required element cannot follow an optional element.",PatternIsOptional:"A binding pattern parameter cannot be optional in an implementation signature.",PrivateElementHasAbstract:"Private elements cannot have the 'abstract' modifier.",PrivateElementHasAccessibility:"Private elements cannot have an accessibility modifier ('%0')",TemplateTypeHasSubstitution:"Template literal types cannot have any substitution",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",UnexpectedReadonly:"'readonly' type modifier is only permitted on array and tuple literal types.",UnexpectedTypeAnnotation:"Did not expect a type annotation here.",UnexpectedTypeCastInParameter:"Unexpected type cast in parameter position.",UnsupportedImportTypeArgument:"Argument in a type import must be a string literal",UnsupportedParameterPropertyKind:"A parameter property may not be declared using a binding pattern.",UnsupportedSignatureParameterKind:"Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"});n.placeholder=new s("%%",{startsExpr:!0});function at(t,e){return t.some(t=>Array.isArray(t)?t[0]===e:t===e)}function nt(t,e,s){const i=t.find(t=>Array.isArray(t)?t[0]===e:t===e);return i&&Array.isArray(i)?i[1][s]:null}const ot=["minimal","smart","fsharp"],ht=["hash","bar"];const pt={estree:t=>class extends t{estreeParseRegExpLiteral({pattern:t,flags:e}){let s=null;try{s=new RegExp(t,e)}catch(t){}const i=this.estreeParseLiteral(s);return i.regex={pattern:t,flags:e},i}estreeParseBigIntLiteral(t){const e="undefined"!=typeof BigInt?BigInt(t):null,s=this.estreeParseLiteral(e);return s.bigint=String(s.value||t),s}estreeParseLiteral(t){return this.parseLiteral(t,"Literal")}directiveToStmt(t){const e=t.value,s=this.startNodeAt(t.start,t.loc.start),i=this.startNodeAt(e.start,e.loc.start);return i.value=e.value,i.raw=e.extra.raw,s.expression=this.finishNodeAt(i,"Literal",e.end,e.loc.end),s.directive=e.extra.raw.slice(1,-1),this.finishNodeAt(s,"ExpressionStatement",t.end,t.loc.end)}initFunction(t,e){super.initFunction(t,e),t.expression=!1}checkDeclaration(t){D(t)?this.checkDeclaration(t.value):super.checkDeclaration(t)}checkGetterSetterParams(t){const e=t,s="get"===e.kind?0:1,i=e.start;e.value.params.length!==s?"get"===t.kind?this.raise(i,f.BadGetterArity):this.raise(i,f.BadSetterArity):"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raise(i,f.BadSetterRestParameter)}checkLVal(t,e=64,s,i,r){switch(t.type){case"ObjectPattern":t.properties.forEach(t=>{this.checkLVal("Property"===t.type?t.value:t,e,s,"object destructuring pattern",r)});break;default:super.checkLVal(t,e,s,i,r)}}checkDuplicatedProto(t,e,s){if("SpreadElement"===t.type||t.computed||t.method||t.shorthand)return;const i=t.key;"__proto__"===("Identifier"===i.type?i.name:String(i.value))&&"init"===t.kind&&(e.used&&(s&&-1===s.doubleProto?s.doubleProto=i.start:this.raise(i.start,f.DuplicateProto)),e.used=!0)}isValidDirective(t){return!("ExpressionStatement"!==t.type||"Literal"!==t.expression.type||"string"!=typeof t.expression.value||t.expression.extra&&t.expression.extra.parenthesized)}stmtToDirective(t){const e=super.stmtToDirective(t),s=t.expression.value;return e.value.value=s,e}parseBlockBody(t,e,s,i){super.parseBlockBody(t,e,s,i);const r=t.directives.map(t=>this.directiveToStmt(t));t.body=r.concat(t.body),delete t.directives}pushClassMethod(t,e,s,i,r,a){this.parseMethod(e,s,i,r,a,"ClassMethod",!0),e.typeParameters&&(e.value.typeParameters=e.typeParameters,delete e.typeParameters),t.body.push(e)}parseExprAtom(t){switch(this.state.type){case n.num:case n.string:return this.estreeParseLiteral(this.state.value);case n.regexp:return this.estreeParseRegExpLiteral(this.state.value);case n.bigint:return this.estreeParseBigIntLiteral(this.state.value);case n._null:return this.estreeParseLiteral(null);case n._true:return this.estreeParseLiteral(!0);case n._false:return this.estreeParseLiteral(!1);default:return super.parseExprAtom(t)}}parseLiteral(t,e,s,i){const r=super.parseLiteral(t,e,s,i);return r.raw=r.extra.raw,delete r.extra,r}parseFunctionBody(t,e,s=!1){super.parseFunctionBody(t,e,s),t.expression="BlockStatement"!==t.body.type}parseMethod(t,e,s,i,r,a,n=!1){let o=this.startNode();return o.kind=t.kind,o=super.parseMethod(o,e,s,i,r,a,n),o.type="FunctionExpression",delete o.kind,t.value=o,a="ClassMethod"===a?"MethodDefinition":a,this.finishNode(t,a)}parseObjectMethod(t,e,s,i,r){const a=super.parseObjectMethod(t,e,s,i,r);return a&&(a.type="Property","method"===a.kind&&(a.kind="init"),a.shorthand=!1),a}parseObjectProperty(t,e,s,i,r){const a=super.parseObjectProperty(t,e,s,i,r);return a&&(a.kind="init",a.type="Property"),a}toAssignable(t){return D(t)?(this.toAssignable(t.value),t):super.toAssignable(t)}toAssignableObjectExpressionProp(t,e){if("get"===t.kind||"set"===t.kind)throw this.raise(t.key.start,f.PatternHasAccessor);if(t.method)throw this.raise(t.key.start,f.PatternHasMethod);super.toAssignableObjectExpressionProp(t,e)}finishCallExpression(t,e){return super.finishCallExpression(t,e),"Import"===t.callee.type&&(t.type="ImportExpression",t.source=t.arguments[0],delete t.arguments,delete t.callee),t}toReferencedListDeep(t,e){t&&super.toReferencedListDeep(t,e)}parseExport(t){switch(super.parseExport(t),t.type){case"ExportAllDeclaration":t.exported=null;break;case"ExportNamedDeclaration":1===t.specifiers.length&&"ExportNamespaceSpecifier"===t.specifiers[0].type&&(t.type="ExportAllDeclaration",t.exported=t.specifiers[0].exported,delete t.specifiers)}return t}},jsx:t=>class extends t{jsxReadToken(){let t="",e=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(this.state.start,J.UnterminatedJsxContent);const s=this.input.charCodeAt(this.state.pos);switch(s){case 60:case 123:return this.state.pos===this.state.start?60===s&&this.state.exprAllowed?(++this.state.pos,this.finishToken(n.jsxTagStart)):super.getTokenFromCode(s):(t+=this.input.slice(e,this.state.pos),this.finishToken(n.jsxText,t));case 38:t+=this.input.slice(e,this.state.pos),t+=this.jsxReadEntity(),e=this.state.pos;break;default:p(s)?(t+=this.input.slice(e,this.state.pos),t+=this.jsxReadNewLine(!0),e=this.state.pos):++this.state.pos}}}jsxReadNewLine(t){const e=this.input.charCodeAt(this.state.pos);let s;return++this.state.pos,13===e&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,s=t?"\n":"\r\n"):s=String.fromCharCode(e),++this.state.curLine,this.state.lineStart=this.state.pos,s}jsxReadString(t){let e="",s=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(this.state.start,f.UnterminatedString);const i=this.input.charCodeAt(this.state.pos);if(i===t)break;38===i?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadEntity(),s=this.state.pos):p(i)?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadNewLine(!1),s=this.state.pos):++this.state.pos}return e+=this.input.slice(s,this.state.pos++),this.finishToken(n.string,e)}jsxReadEntity(){let t,e="",s=0,i=this.input[this.state.pos];const r=++this.state.pos;for(;this.state.pos<this.length&&s++<10;){if(i=this.input[this.state.pos++],";"===i){"#"===e[0]?"x"===e[1]?(e=e.substr(2),W.test(e)&&(t=String.fromCodePoint(parseInt(e,16)))):(e=e.substr(1),K.test(e)&&(t=String.fromCodePoint(parseInt(e,10)))):t=H[e];break}e+=i}return t||(this.state.pos=r,"&")}jsxReadWord(){let t;const e=this.state.pos;do{t=this.input.charCodeAt(++this.state.pos)}while(S(t)||45===t);return this.finishToken(n.jsxName,this.input.slice(e,this.state.pos))}jsxParseIdentifier(){const t=this.startNode();return this.match(n.jsxName)?t.name=this.state.value:this.state.type.keyword?t.name=this.state.type.keyword:this.unexpected(),this.next(),this.finishNode(t,"JSXIdentifier")}jsxParseNamespacedName(){const t=this.state.start,e=this.state.startLoc,s=this.jsxParseIdentifier();if(!this.eat(n.colon))return s;const i=this.startNodeAt(t,e);return i.namespace=s,i.name=this.jsxParseIdentifier(),this.finishNode(i,"JSXNamespacedName")}jsxParseElementName(){const t=this.state.start,e=this.state.startLoc;let s=this.jsxParseNamespacedName();if("JSXNamespacedName"===s.type)return s;for(;this.eat(n.dot);){const i=this.startNodeAt(t,e);i.object=s,i.property=this.jsxParseIdentifier(),s=this.finishNode(i,"JSXMemberExpression")}return s}jsxParseAttributeValue(){let t;switch(this.state.type){case n.braceL:return t=this.startNode(),this.next(),t=this.jsxParseExpressionContainer(t),"JSXEmptyExpression"===t.expression.type&&this.raise(t.start,J.AttributeIsEmpty),t;case n.jsxTagStart:case n.string:return this.parseExprAtom();default:throw this.raise(this.state.start,J.UnsupportedJsxValue)}}jsxParseEmptyExpression(){const t=this.startNodeAt(this.state.lastTokEnd,this.state.lastTokEndLoc);return this.finishNodeAt(t,"JSXEmptyExpression",this.state.start,this.state.startLoc)}jsxParseSpreadChild(t){return this.next(),t.expression=this.parseExpression(),this.expect(n.braceR),this.finishNode(t,"JSXSpreadChild")}jsxParseExpressionContainer(t){return this.match(n.braceR)?t.expression=this.jsxParseEmptyExpression():t.expression=this.parseExpression(),this.expect(n.braceR),this.finishNode(t,"JSXExpressionContainer")}jsxParseAttribute(){const t=this.startNode();return this.eat(n.braceL)?(this.expect(n.ellipsis),t.argument=this.parseMaybeAssign(),this.expect(n.braceR),this.finishNode(t,"JSXSpreadAttribute")):(t.name=this.jsxParseNamespacedName(),t.value=this.eat(n.eq)?this.jsxParseAttributeValue():null,this.finishNode(t,"JSXAttribute"))}jsxParseOpeningElementAt(t,e){const s=this.startNodeAt(t,e);return this.match(n.jsxTagEnd)?(this.expect(n.jsxTagEnd),this.finishNode(s,"JSXOpeningFragment")):(s.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(s))}jsxParseOpeningElementAfterName(t){const e=[];for(;!this.match(n.slash)&&!this.match(n.jsxTagEnd);)e.push(this.jsxParseAttribute());return t.attributes=e,t.selfClosing=this.eat(n.slash),this.expect(n.jsxTagEnd),this.finishNode(t,"JSXOpeningElement")}jsxParseClosingElementAt(t,e){const s=this.startNodeAt(t,e);return this.match(n.jsxTagEnd)?(this.expect(n.jsxTagEnd),this.finishNode(s,"JSXClosingFragment")):(s.name=this.jsxParseElementName(),this.expect(n.jsxTagEnd),this.finishNode(s,"JSXClosingElement"))}jsxParseElementAt(t,e){const s=this.startNodeAt(t,e),i=[],r=this.jsxParseOpeningElementAt(t,e);let a=null;if(!r.selfClosing){t:for(;;)switch(this.state.type){case n.jsxTagStart:if(t=this.state.start,e=this.state.startLoc,this.next(),this.eat(n.slash)){a=this.jsxParseClosingElementAt(t,e);break t}i.push(this.jsxParseElementAt(t,e));break;case n.jsxText:i.push(this.parseExprAtom());break;case n.braceL:{const t=this.startNode();this.next(),this.match(n.ellipsis)?i.push(this.jsxParseSpreadChild(t)):i.push(this.jsxParseExpressionContainer(t));break}default:throw this.unexpected()}X(r)&&!X(a)?this.raise(a.start,J.MissingClosingTagFragment):!X(r)&&X(a)?this.raise(a.start,J.MissingClosingTagElement,G(r.name)):X(r)||X(a)||G(a.name)!==G(r.name)&&this.raise(a.start,J.MissingClosingTagElement,G(r.name))}if(X(r)?(s.openingFragment=r,s.closingFragment=a):(s.openingElement=r,s.closingElement=a),s.children=i,this.isRelational("<"))throw this.raise(this.state.start,J.UnwrappedAdjacentJSXElements);return X(r)?this.finishNode(s,"JSXFragment"):this.finishNode(s,"JSXElement")}jsxParseElement(){const t=this.state.start,e=this.state.startLoc;return this.next(),this.jsxParseElementAt(t,e)}parseExprAtom(t){return this.match(n.jsxText)?this.parseLiteral(this.state.value,"JSXText"):this.match(n.jsxTagStart)?this.jsxParseElement():this.isRelational("<")&&33!==this.input.charCodeAt(this.state.pos)?(this.finishToken(n.jsxTagStart),this.jsxParseElement()):super.parseExprAtom(t)}getTokenFromCode(t){if(this.state.inPropertyName)return super.getTokenFromCode(t);const e=this.curContext();if(e===x.j_expr)return this.jsxReadToken();if(e===x.j_oTag||e===x.j_cTag){if(w(t))return this.jsxReadWord();if(62===t)return++this.state.pos,this.finishToken(n.jsxTagEnd);if((34===t||39===t)&&e===x.j_oTag)return this.jsxReadString(t)}return 60===t&&this.state.exprAllowed&&33!==this.input.charCodeAt(this.state.pos+1)?(++this.state.pos,this.finishToken(n.jsxTagStart)):super.getTokenFromCode(t)}updateContext(t){if(this.match(n.braceL)){const e=this.curContext();e===x.j_oTag?this.state.context.push(x.braceExpression):e===x.j_expr?this.state.context.push(x.templateQuasi):super.updateContext(t),this.state.exprAllowed=!0}else{if(!this.match(n.slash)||t!==n.jsxTagStart)return super.updateContext(t);this.state.context.length-=2,this.state.context.push(x.j_cTag),this.state.exprAllowed=!1}}},flow:t=>class extends t{constructor(t,e){super(t,e),this.flowPragma=void 0}shouldParseTypes(){return this.getPluginOption("flow","all")||"flow"===this.flowPragma}shouldParseEnums(){return!!this.getPluginOption("flow","enums")}finishToken(t,e){return t!==n.string&&t!==n.semi&&t!==n.interpreterDirective&&void 0===this.flowPragma&&(this.flowPragma=null),super.finishToken(t,e)}addComment(t){if(void 0===this.flowPragma){const e=z.exec(t.value);if(e)if("flow"===e[1])this.flowPragma="flow";else{if("noflow"!==e[1])throw new Error("Unexpected flow pragma");this.flowPragma="noflow"}else;}return super.addComment(t)}flowParseTypeInitialiser(t){const e=this.state.inType;this.state.inType=!0,this.expect(t||n.colon);const s=this.flowParseType();return this.state.inType=e,s}flowParsePredicate(){const t=this.startNode(),e=this.state.startLoc,s=this.state.start;this.expect(n.modulo);const i=this.state.startLoc;return this.expectContextual("checks"),e.line===i.line&&e.column===i.column-1||this.raise(s,j.UnexpectedSpaceBetweenModuloChecks),this.eat(n.parenL)?(t.value=this.parseExpression(),this.expect(n.parenR),this.finishNode(t,"DeclaredPredicate")):this.finishNode(t,"InferredPredicate")}flowParseTypeAndPredicateInitialiser(){const t=this.state.inType;this.state.inType=!0,this.expect(n.colon);let e=null,s=null;return this.match(n.modulo)?(this.state.inType=t,s=this.flowParsePredicate()):(e=this.flowParseType(),this.state.inType=t,this.match(n.modulo)&&(s=this.flowParsePredicate())),[e,s]}flowParseDeclareClass(t){return this.next(),this.flowParseInterfaceish(t,!0),this.finishNode(t,"DeclareClass")}flowParseDeclareFunction(t){this.next();const e=t.id=this.parseIdentifier(),s=this.startNode(),i=this.startNode();this.isRelational("<")?s.typeParameters=this.flowParseTypeParameterDeclaration():s.typeParameters=null,this.expect(n.parenL);const r=this.flowParseFunctionTypeParams();return s.params=r.params,s.rest=r.rest,this.expect(n.parenR),[s.returnType,t.predicate]=this.flowParseTypeAndPredicateInitialiser(),i.typeAnnotation=this.finishNode(s,"FunctionTypeAnnotation"),e.typeAnnotation=this.finishNode(i,"TypeAnnotation"),this.resetEndLocation(e),this.semicolon(),this.finishNode(t,"DeclareFunction")}flowParseDeclare(t,e){if(this.match(n._class))return this.flowParseDeclareClass(t);if(this.match(n._function))return this.flowParseDeclareFunction(t);if(this.match(n._var))return this.flowParseDeclareVariable(t);if(this.eatContextual("module"))return this.match(n.dot)?this.flowParseDeclareModuleExports(t):(e&&this.raise(this.state.lastTokStart,j.NestedDeclareModule),this.flowParseDeclareModule(t));if(this.isContextual("type"))return this.flowParseDeclareTypeAlias(t);if(this.isContextual("opaque"))return this.flowParseDeclareOpaqueType(t);if(this.isContextual("interface"))return this.flowParseDeclareInterface(t);if(this.match(n._export))return this.flowParseDeclareExportDeclaration(t,e);throw this.unexpected()}flowParseDeclareVariable(t){return this.next(),t.id=this.flowParseTypeAnnotatableIdentifier(!0),this.scope.declareName(t.id.name,5,t.id.start),this.semicolon(),this.finishNode(t,"DeclareVariable")}flowParseDeclareModule(t){this.scope.enter(0),this.match(n.string)?t.id=this.parseExprAtom():t.id=this.parseIdentifier();const e=t.body=this.startNode(),s=e.body=[];for(this.expect(n.braceL);!this.match(n.braceR);){let t=this.startNode();this.match(n._import)?(this.next(),this.isContextual("type")||this.match(n._typeof)||this.raise(this.state.lastTokStart,j.InvalidNonTypeImportInDeclareModule),this.parseImport(t)):(this.expectContextual("declare",j.UnsupportedStatementInDeclareModule),t=this.flowParseDeclare(t,!0)),s.push(t)}this.scope.exit(),this.expect(n.braceR),this.finishNode(e,"BlockStatement");let i=null,r=!1;return s.forEach(t=>{!function(t){return"DeclareExportAllDeclaration"===t.type||"DeclareExportDeclaration"===t.type&&(!t.declaration||"TypeAlias"!==t.declaration.type&&"InterfaceDeclaration"!==t.declaration.type)}(t)?"DeclareModuleExports"===t.type&&(r&&this.raise(t.start,j.DuplicateDeclareModuleExports),"ES"===i&&this.raise(t.start,j.AmbiguousDeclareModuleKind),i="CommonJS",r=!0):("CommonJS"===i&&this.raise(t.start,j.AmbiguousDeclareModuleKind),i="ES")}),t.kind=i||"CommonJS",this.finishNode(t,"DeclareModule")}flowParseDeclareExportDeclaration(t,e){if(this.expect(n._export),this.eat(n._default))return this.match(n._function)||this.match(n._class)?t.declaration=this.flowParseDeclare(this.startNode()):(t.declaration=this.flowParseType(),this.semicolon()),t.default=!0,this.finishNode(t,"DeclareExportDeclaration");if(this.match(n._const)||this.isLet()||(this.isContextual("type")||this.isContextual("interface"))&&!e){const t=this.state.value,e=V[t];throw this.raise(this.state.start,j.UnsupportedDeclareExportKind,t,e)}if(this.match(n._var)||this.match(n._function)||this.match(n._class)||this.isContextual("opaque"))return t.declaration=this.flowParseDeclare(this.startNode()),t.default=!1,this.finishNode(t,"DeclareExportDeclaration");if(this.match(n.star)||this.match(n.braceL)||this.isContextual("interface")||this.isContextual("type")||this.isContextual("opaque"))return"ExportNamedDeclaration"===(t=this.parseExport(t)).type&&(t.type="ExportDeclaration",t.default=!1,delete t.exportKind),t.type="Declare"+t.type,t;throw this.unexpected()}flowParseDeclareModuleExports(t){return this.next(),this.expectContextual("exports"),t.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(t,"DeclareModuleExports")}flowParseDeclareTypeAlias(t){return this.next(),this.flowParseTypeAlias(t),t.type="DeclareTypeAlias",t}flowParseDeclareOpaqueType(t){return this.next(),this.flowParseOpaqueType(t,!0),t.type="DeclareOpaqueType",t}flowParseDeclareInterface(t){return this.next(),this.flowParseInterfaceish(t),this.finishNode(t,"DeclareInterface")}flowParseInterfaceish(t,e=!1){if(t.id=this.flowParseRestrictedIdentifier(!e,!0),this.scope.declareName(t.id.name,e?17:9,t.id.start),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.extends=[],t.implements=[],t.mixins=[],this.eat(n._extends))do{t.extends.push(this.flowParseInterfaceExtends())}while(!e&&this.eat(n.comma));if(this.isContextual("mixins")){this.next();do{t.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(n.comma))}if(this.isContextual("implements")){this.next();do{t.implements.push(this.flowParseInterfaceExtends())}while(this.eat(n.comma))}t.body=this.flowParseObjectType({allowStatic:e,allowExact:!1,allowSpread:!1,allowProto:e,allowInexact:!1})}flowParseInterfaceExtends(){const t=this.startNode();return t.id=this.flowParseQualifiedTypeIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterInstantiation():t.typeParameters=null,this.finishNode(t,"InterfaceExtends")}flowParseInterface(t){return this.flowParseInterfaceish(t),this.finishNode(t,"InterfaceDeclaration")}checkNotUnderscore(t){"_"===t&&this.raise(this.state.start,j.UnexpectedReservedUnderscore)}checkReservedType(t,e,s){_.has(t)&&this.raise(e,s?j.AssignReservedType:j.UnexpectedReservedType,t)}flowParseRestrictedIdentifier(t,e){return this.checkReservedType(this.state.value,this.state.start,e),this.parseIdentifier(t)}flowParseTypeAlias(t){return t.id=this.flowParseRestrictedIdentifier(!1,!0),this.scope.declareName(t.id.name,9,t.id.start),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.right=this.flowParseTypeInitialiser(n.eq),this.semicolon(),this.finishNode(t,"TypeAlias")}flowParseOpaqueType(t,e){return this.expectContextual("type"),t.id=this.flowParseRestrictedIdentifier(!0,!0),this.scope.declareName(t.id.name,9,t.id.start),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.supertype=null,this.match(n.colon)&&(t.supertype=this.flowParseTypeInitialiser(n.colon)),t.impltype=null,e||(t.impltype=this.flowParseTypeInitialiser(n.eq)),this.semicolon(),this.finishNode(t,"OpaqueType")}flowParseTypeParameter(t=!1){const e=this.state.start,s=this.startNode(),i=this.flowParseVariance(),r=this.flowParseTypeAnnotatableIdentifier();return s.name=r.name,s.variance=i,s.bound=r.typeAnnotation,this.match(n.eq)?(this.eat(n.eq),s.default=this.flowParseType()):t&&this.raise(e,j.MissingTypeParamDefault),this.finishNode(s,"TypeParameter")}flowParseTypeParameterDeclaration(){const t=this.state.inType,e=this.startNode();e.params=[],this.state.inType=!0,this.isRelational("<")||this.match(n.jsxTagStart)?this.next():this.unexpected();let s=!1;do{const t=this.flowParseTypeParameter(s);e.params.push(t),t.default&&(s=!0),this.isRelational(">")||this.expect(n.comma)}while(!this.isRelational(">"));return this.expectRelational(">"),this.state.inType=t,this.finishNode(e,"TypeParameterDeclaration")}flowParseTypeParameterInstantiation(){const t=this.startNode(),e=this.state.inType;t.params=[],this.state.inType=!0,this.expectRelational("<");const s=this.state.noAnonFunctionType;for(this.state.noAnonFunctionType=!1;!this.isRelational(">");)t.params.push(this.flowParseType()),this.isRelational(">")||this.expect(n.comma);return this.state.noAnonFunctionType=s,this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){const t=this.startNode(),e=this.state.inType;for(t.params=[],this.state.inType=!0,this.expectRelational("<");!this.isRelational(">");)t.params.push(this.flowParseTypeOrImplicitInstantiation()),this.isRelational(">")||this.expect(n.comma);return this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterInstantiation")}flowParseInterfaceType(){const t=this.startNode();if(this.expectContextual("interface"),t.extends=[],this.eat(n._extends))do{t.extends.push(this.flowParseInterfaceExtends())}while(this.eat(n.comma));return t.body=this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!1,allowProto:!1,allowInexact:!1}),this.finishNode(t,"InterfaceTypeAnnotation")}flowParseObjectPropertyKey(){return this.match(n.num)||this.match(n.string)?this.parseExprAtom():this.parseIdentifier(!0)}flowParseObjectTypeIndexer(t,e,s){return t.static=e,this.lookahead().type===n.colon?(t.id=this.flowParseObjectPropertyKey(),t.key=this.flowParseTypeInitialiser()):(t.id=null,t.key=this.flowParseType()),this.expect(n.bracketR),t.value=this.flowParseTypeInitialiser(),t.variance=s,this.finishNode(t,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(t,e){return t.static=e,t.id=this.flowParseObjectPropertyKey(),this.expect(n.bracketR),this.expect(n.bracketR),this.isRelational("<")||this.match(n.parenL)?(t.method=!0,t.optional=!1,t.value=this.flowParseObjectTypeMethodish(this.startNodeAt(t.start,t.loc.start))):(t.method=!1,this.eat(n.question)&&(t.optional=!0),t.value=this.flowParseTypeInitialiser()),this.finishNode(t,"ObjectTypeInternalSlot")}flowParseObjectTypeMethodish(t){for(t.params=[],t.rest=null,t.typeParameters=null,this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(n.parenL);!this.match(n.parenR)&&!this.match(n.ellipsis);)t.params.push(this.flowParseFunctionTypeParam()),this.match(n.parenR)||this.expect(n.comma);return this.eat(n.ellipsis)&&(t.rest=this.flowParseFunctionTypeParam()),this.expect(n.parenR),t.returnType=this.flowParseTypeInitialiser(),this.finishNode(t,"FunctionTypeAnnotation")}flowParseObjectTypeCallProperty(t,e){const s=this.startNode();return t.static=e,t.value=this.flowParseObjectTypeMethodish(s),this.finishNode(t,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:t,allowExact:e,allowSpread:s,allowProto:i,allowInexact:r}){const a=this.state.inType;this.state.inType=!0;const o=this.startNode();let h,p;o.callProperties=[],o.properties=[],o.indexers=[],o.internalSlots=[];let c=!1;for(e&&this.match(n.braceBarL)?(this.expect(n.braceBarL),h=n.braceBarR,p=!0):(this.expect(n.braceL),h=n.braceR,p=!1),o.exact=p;!this.match(h);){let e=!1,a=null,h=null;const u=this.startNode();if(i&&this.isContextual("proto")){const e=this.lookahead();e.type!==n.colon&&e.type!==n.question&&(this.next(),a=this.state.start,t=!1)}if(t&&this.isContextual("static")){const t=this.lookahead();t.type!==n.colon&&t.type!==n.question&&(this.next(),e=!0)}const l=this.flowParseVariance();if(this.eat(n.bracketL))null!=a&&this.unexpected(a),this.eat(n.bracketL)?(l&&this.unexpected(l.start),o.internalSlots.push(this.flowParseObjectTypeInternalSlot(u,e))):o.indexers.push(this.flowParseObjectTypeIndexer(u,e,l));else if(this.match(n.parenL)||this.isRelational("<"))null!=a&&this.unexpected(a),l&&this.unexpected(l.start),o.callProperties.push(this.flowParseObjectTypeCallProperty(u,e));else{let t="init";if(this.isContextual("get")||this.isContextual("set")){const e=this.lookahead();e.type!==n.name&&e.type!==n.string&&e.type!==n.num||(t=this.state.value,this.next())}const i=this.flowParseObjectTypeProperty(u,e,a,l,t,s,null!=r?r:!p);null===i?(c=!0,h=this.state.lastTokStart):o.properties.push(i)}this.flowObjectTypeSemicolon(),!h||this.match(n.braceR)||this.match(n.braceBarR)||this.raise(h,j.UnexpectedExplicitInexactInObject)}this.expect(h),s&&(o.inexact=c);const u=this.finishNode(o,"ObjectTypeAnnotation");return this.state.inType=a,u}flowParseObjectTypeProperty(t,e,s,i,r,a,o){if(this.eat(n.ellipsis)){return this.match(n.comma)||this.match(n.semi)||this.match(n.braceR)||this.match(n.braceBarR)?(a?o||this.raise(this.state.lastTokStart,j.InexactInsideExact):this.raise(this.state.lastTokStart,j.InexactInsideNonObject),i&&this.raise(i.start,j.InexactVariance),null):(a||this.raise(this.state.lastTokStart,j.UnexpectedSpreadType),null!=s&&this.unexpected(s),i&&this.raise(i.start,j.SpreadVariance),t.argument=this.flowParseType(),this.finishNode(t,"ObjectTypeSpreadProperty"))}{t.key=this.flowParseObjectPropertyKey(),t.static=e,t.proto=null!=s,t.kind=r;let a=!1;return this.isRelational("<")||this.match(n.parenL)?(t.method=!0,null!=s&&this.unexpected(s),i&&this.unexpected(i.start),t.value=this.flowParseObjectTypeMethodish(this.startNodeAt(t.start,t.loc.start)),"get"!==r&&"set"!==r||this.flowCheckGetterSetterParams(t)):("init"!==r&&this.unexpected(),t.method=!1,this.eat(n.question)&&(a=!0),t.value=this.flowParseTypeInitialiser(),t.variance=i),t.optional=a,this.finishNode(t,"ObjectTypeProperty")}}flowCheckGetterSetterParams(t){const e="get"===t.kind?0:1,s=t.start;t.value.params.length+(t.value.rest?1:0)!==e&&("get"===t.kind?this.raise(s,f.BadGetterArity):this.raise(s,f.BadSetterArity)),"set"===t.kind&&t.value.rest&&this.raise(s,f.BadSetterRestParameter)}flowObjectTypeSemicolon(){this.eat(n.semi)||this.eat(n.comma)||this.match(n.braceR)||this.match(n.braceBarR)||this.unexpected()}flowParseQualifiedTypeIdentifier(t,e,s){t=t||this.state.start,e=e||this.state.startLoc;let i=s||this.flowParseRestrictedIdentifier(!0);for(;this.eat(n.dot);){const s=this.startNodeAt(t,e);s.qualification=i,s.id=this.flowParseRestrictedIdentifier(!0),i=this.finishNode(s,"QualifiedTypeIdentifier")}return i}flowParseGenericType(t,e,s){const i=this.startNodeAt(t,e);return i.typeParameters=null,i.id=this.flowParseQualifiedTypeIdentifier(t,e,s),this.isRelational("<")&&(i.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(i,"GenericTypeAnnotation")}flowParseTypeofType(){const t=this.startNode();return this.expect(n._typeof),t.argument=this.flowParsePrimaryType(),this.finishNode(t,"TypeofTypeAnnotation")}flowParseTupleType(){const t=this.startNode();for(t.types=[],this.expect(n.bracketL);this.state.pos<this.length&&!this.match(n.bracketR)&&(t.types.push(this.flowParseType()),!this.match(n.bracketR));)this.expect(n.comma);return this.expect(n.bracketR),this.finishNode(t,"TupleTypeAnnotation")}flowParseFunctionTypeParam(){let t=null,e=!1,s=null;const i=this.startNode(),r=this.lookahead();return r.type===n.colon||r.type===n.question?(t=this.parseIdentifier(),this.eat(n.question)&&(e=!0),s=this.flowParseTypeInitialiser()):s=this.flowParseType(),i.name=t,i.optional=e,i.typeAnnotation=s,this.finishNode(i,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(t){const e=this.startNodeAt(t.start,t.loc.start);return e.name=null,e.optional=!1,e.typeAnnotation=t,this.finishNode(e,"FunctionTypeParam")}flowParseFunctionTypeParams(t=[]){let e=null;for(;!this.match(n.parenR)&&!this.match(n.ellipsis);)t.push(this.flowParseFunctionTypeParam()),this.match(n.parenR)||this.expect(n.comma);return this.eat(n.ellipsis)&&(e=this.flowParseFunctionTypeParam()),{params:t,rest:e}}flowIdentToTypeAnnotation(t,e,s,i){switch(i.name){case"any":return this.finishNode(s,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(s,"BooleanTypeAnnotation");case"mixed":return this.finishNode(s,"MixedTypeAnnotation");case"empty":return this.finishNode(s,"EmptyTypeAnnotation");case"number":return this.finishNode(s,"NumberTypeAnnotation");case"string":return this.finishNode(s,"StringTypeAnnotation");case"symbol":return this.finishNode(s,"SymbolTypeAnnotation");default:return this.checkNotUnderscore(i.name),this.flowParseGenericType(t,e,i)}}flowParsePrimaryType(){const t=this.state.start,e=this.state.startLoc,s=this.startNode();let i,r,a=!1;const o=this.state.noAnonFunctionType;switch(this.state.type){case n.name:return this.isContextual("interface")?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(t,e,s,this.parseIdentifier());case n.braceL:return this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!0,allowProto:!1,allowInexact:!0});case n.braceBarL:return this.flowParseObjectType({allowStatic:!1,allowExact:!0,allowSpread:!0,allowProto:!1,allowInexact:!1});case n.bracketL:return this.state.noAnonFunctionType=!1,r=this.flowParseTupleType(),this.state.noAnonFunctionType=o,r;case n.relational:if("<"===this.state.value)return s.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(n.parenL),i=this.flowParseFunctionTypeParams(),s.params=i.params,s.rest=i.rest,this.expect(n.parenR),this.expect(n.arrow),s.returnType=this.flowParseType(),this.finishNode(s,"FunctionTypeAnnotation");break;case n.parenL:if(this.next(),!this.match(n.parenR)&&!this.match(n.ellipsis))if(this.match(n.name)){const t=this.lookahead().type;a=t!==n.question&&t!==n.colon}else a=!0;if(a){if(this.state.noAnonFunctionType=!1,r=this.flowParseType(),this.state.noAnonFunctionType=o,this.state.noAnonFunctionType||!(this.match(n.comma)||this.match(n.parenR)&&this.lookahead().type===n.arrow))return this.expect(n.parenR),r;this.eat(n.comma)}return i=r?this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(r)]):this.flowParseFunctionTypeParams(),s.params=i.params,s.rest=i.rest,this.expect(n.parenR),this.expect(n.arrow),s.returnType=this.flowParseType(),s.typeParameters=null,this.finishNode(s,"FunctionTypeAnnotation");case n.string:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case n._true:case n._false:return s.value=this.match(n._true),this.next(),this.finishNode(s,"BooleanLiteralTypeAnnotation");case n.plusMin:if("-"===this.state.value){if(this.next(),this.match(n.num))return this.parseLiteral(-this.state.value,"NumberLiteralTypeAnnotation",s.start,s.loc.start);if(this.match(n.bigint))return this.parseLiteral(-this.state.value,"BigIntLiteralTypeAnnotation",s.start,s.loc.start);throw this.raise(this.state.start,j.UnexpectedSubtractionOperand)}throw this.unexpected();case n.num:return this.parseLiteral(this.state.value,"NumberLiteralTypeAnnotation");case n.bigint:return this.parseLiteral(this.state.value,"BigIntLiteralTypeAnnotation");case n._void:return this.next(),this.finishNode(s,"VoidTypeAnnotation");case n._null:return this.next(),this.finishNode(s,"NullLiteralTypeAnnotation");case n._this:return this.next(),this.finishNode(s,"ThisTypeAnnotation");case n.star:return this.next(),this.finishNode(s,"ExistsTypeAnnotation");default:if("typeof"===this.state.type.keyword)return this.flowParseTypeofType();if(this.state.type.keyword){const t=this.state.type.label;return this.next(),super.createIdentifier(s,t)}}throw this.unexpected()}flowParsePostfixType(){const t=this.state.start,e=this.state.startLoc;let s=this.flowParsePrimaryType();for(;this.match(n.bracketL)&&!this.canInsertSemicolon();){const i=this.startNodeAt(t,e);i.elementType=s,this.expect(n.bracketL),this.expect(n.bracketR),s=this.finishNode(i,"ArrayTypeAnnotation")}return s}flowParsePrefixType(){const t=this.startNode();return this.eat(n.question)?(t.typeAnnotation=this.flowParsePrefixType(),this.finishNode(t,"NullableTypeAnnotation")):this.flowParsePostfixType()}flowParseAnonFunctionWithoutParens(){const t=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(n.arrow)){const e=this.startNodeAt(t.start,t.loc.start);return e.params=[this.reinterpretTypeAsFunctionTypeParam(t)],e.rest=null,e.returnType=this.flowParseType(),e.typeParameters=null,this.finishNode(e,"FunctionTypeAnnotation")}return t}flowParseIntersectionType(){const t=this.startNode();this.eat(n.bitwiseAND);const e=this.flowParseAnonFunctionWithoutParens();for(t.types=[e];this.eat(n.bitwiseAND);)t.types.push(this.flowParseAnonFunctionWithoutParens());return 1===t.types.length?e:this.finishNode(t,"IntersectionTypeAnnotation")}flowParseUnionType(){const t=this.startNode();this.eat(n.bitwiseOR);const e=this.flowParseIntersectionType();for(t.types=[e];this.eat(n.bitwiseOR);)t.types.push(this.flowParseIntersectionType());return 1===t.types.length?e:this.finishNode(t,"UnionTypeAnnotation")}flowParseType(){const t=this.state.inType;this.state.inType=!0;const e=this.flowParseUnionType();return this.state.inType=t,this.state.exprAllowed=this.state.exprAllowed||this.state.noAnonFunctionType,e}flowParseTypeOrImplicitInstantiation(){if(this.state.type===n.name&&"_"===this.state.value){const t=this.state.start,e=this.state.startLoc,s=this.parseIdentifier();return this.flowParseGenericType(t,e,s)}return this.flowParseType()}flowParseTypeAnnotation(){const t=this.startNode();return t.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(t,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(t){const e=t?this.parseIdentifier():this.flowParseRestrictedIdentifier();return this.match(n.colon)&&(e.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(e)),e}typeCastToParameter(t){return t.expression.typeAnnotation=t.typeAnnotation,this.resetEndLocation(t.expression,t.typeAnnotation.end,t.typeAnnotation.loc.end),t.expression}flowParseVariance(){let t=null;return this.match(n.plusMin)&&(t=this.startNode(),"+"===this.state.value?t.kind="plus":t.kind="minus",this.next(),this.finishNode(t,"Variance")),t}parseFunctionBody(t,e,s=!1){return e?this.forwardNoArrowParamsConversionAt(t,()=>super.parseFunctionBody(t,!0,s)):super.parseFunctionBody(t,!1,s)}parseFunctionBodyAndFinish(t,e,s=!1){if(this.match(n.colon)){const e=this.startNode();[e.typeAnnotation,t.predicate]=this.flowParseTypeAndPredicateInitialiser(),t.returnType=e.typeAnnotation?this.finishNode(e,"TypeAnnotation"):null}super.parseFunctionBodyAndFinish(t,e,s)}parseStatement(t,e){if(this.state.strict&&this.match(n.name)&&"interface"===this.state.value){const t=this.startNode();return this.next(),this.flowParseInterface(t)}if(this.shouldParseEnums()&&this.isContextual("enum")){const t=this.startNode();return this.next(),this.flowParseEnumDeclaration(t)}{const s=super.parseStatement(t,e);return void 0!==this.flowPragma||this.isValidDirective(s)||(this.flowPragma=null),s}}parseExpressionStatement(t,e){if("Identifier"===e.type)if("declare"===e.name){if(this.match(n._class)||this.match(n.name)||this.match(n._function)||this.match(n._var)||this.match(n._export))return this.flowParseDeclare(t)}else if(this.match(n.name)){if("interface"===e.name)return this.flowParseInterface(t);if("type"===e.name)return this.flowParseTypeAlias(t);if("opaque"===e.name)return this.flowParseOpaqueType(t,!1)}return super.parseExpressionStatement(t,e)}shouldParseExportDeclaration(){return this.isContextual("type")||this.isContextual("interface")||this.isContextual("opaque")||this.shouldParseEnums()&&this.isContextual("enum")||super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){return(!this.match(n.name)||!("type"===this.state.value||"interface"===this.state.value||"opaque"===this.state.value||this.shouldParseEnums()&&"enum"===this.state.value))&&super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.shouldParseEnums()&&this.isContextual("enum")){const t=this.startNode();return this.next(),this.flowParseEnumDeclaration(t)}return super.parseExportDefaultExpression()}parseConditional(t,e,s,i,r){if(!this.match(n.question))return t;if(r){const a=this.tryParse(()=>super.parseConditional(t,e,s,i));return a.node?(a.error&&(this.state=a.failState),a.node):(r.start=a.error.pos||this.state.start,t)}this.expect(n.question);const a=this.state.clone(),o=this.state.noArrowAt,h=this.startNodeAt(s,i);let{consequent:p,failed:c}=this.tryParseConditionalConsequent(),[u,l]=this.getArrowLikeExpressions(p);if(c||l.length>0){const t=[...o];if(l.length>0){this.state=a,this.state.noArrowAt=t;for(let e=0;e<l.length;e++)t.push(l[e].start);({consequent:p,failed:c}=this.tryParseConditionalConsequent()),[u,l]=this.getArrowLikeExpressions(p)}c&&u.length>1&&this.raise(a.start,j.AmbiguousConditionalArrow),c&&1===u.length&&(this.state=a,this.state.noArrowAt=t.concat(u[0].start),({consequent:p,failed:c}=this.tryParseConditionalConsequent()))}return this.getArrowLikeExpressions(p,!0),this.state.noArrowAt=o,this.expect(n.colon),h.test=t,h.consequent=p,h.alternate=this.forwardNoArrowParamsConversionAt(h,()=>this.parseMaybeAssign(e,void 0,void 0,void 0)),this.finishNode(h,"ConditionalExpression")}tryParseConditionalConsequent(){this.state.noArrowParamsConversionAt.push(this.state.start);const t=this.parseMaybeAssign(),e=!this.match(n.colon);return this.state.noArrowParamsConversionAt.pop(),{consequent:t,failed:e}}getArrowLikeExpressions(t,e){const s=[t],i=[];for(;0!==s.length;){const t=s.pop();"ArrowFunctionExpression"===t.type?(t.typeParameters||!t.returnType?this.finishArrowValidation(t):i.push(t),s.push(t.body)):"ConditionalExpression"===t.type&&(s.push(t.consequent),s.push(t.alternate))}return e?(i.forEach(t=>this.finishArrowValidation(t)),[i,[]]):function(t,e){const s=[],i=[];for(let r=0;r<t.length;r++)(e(t[r],r,t)?s:i).push(t[r]);return[s,i]}(i,t=>t.params.every(t=>this.isAssignable(t,!0)))}finishArrowValidation(t){var e;this.toAssignableList(t.params,null==(e=t.extra)?void 0:e.trailingComma),this.scope.enter(6),super.checkParams(t,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(t,e){let s;return-1!==this.state.noArrowParamsConversionAt.indexOf(t.start)?(this.state.noArrowParamsConversionAt.push(this.state.start),s=e(),this.state.noArrowParamsConversionAt.pop()):s=e(),s}parseParenItem(t,e,s){if(t=super.parseParenItem(t,e,s),this.eat(n.question)&&(t.optional=!0,this.resetEndLocation(t)),this.match(n.colon)){const i=this.startNodeAt(e,s);return i.expression=t,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")}return t}assertModuleNodeAllowed(t){"ImportDeclaration"===t.type&&("type"===t.importKind||"typeof"===t.importKind)||"ExportNamedDeclaration"===t.type&&"type"===t.exportKind||"ExportAllDeclaration"===t.type&&"type"===t.exportKind||super.assertModuleNodeAllowed(t)}parseExport(t){const e=super.parseExport(t);return"ExportNamedDeclaration"!==e.type&&"ExportAllDeclaration"!==e.type||(e.exportKind=e.exportKind||"value"),e}parseExportDeclaration(t){if(this.isContextual("type")){t.exportKind="type";const e=this.startNode();return this.next(),this.match(n.braceL)?(t.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(t),null):this.flowParseTypeAlias(e)}if(this.isContextual("opaque")){t.exportKind="type";const e=this.startNode();return this.next(),this.flowParseOpaqueType(e,!1)}if(this.isContextual("interface")){t.exportKind="type";const e=this.startNode();return this.next(),this.flowParseInterface(e)}if(this.shouldParseEnums()&&this.isContextual("enum")){t.exportKind="value";const e=this.startNode();return this.next(),this.flowParseEnumDeclaration(e)}return super.parseExportDeclaration(t)}eatExportStar(t){return!!super.eatExportStar(...arguments)||!(!this.isContextual("type")||this.lookahead().type!==n.star)&&(t.exportKind="type",this.next(),this.next(),!0)}maybeParseExportNamespaceSpecifier(t){const e=this.state.start,s=super.maybeParseExportNamespaceSpecifier(t);return s&&"type"===t.exportKind&&this.unexpected(e),s}parseClassId(t,e,s){super.parseClassId(t,e,s),this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(t,e,s,i){const r=this.state.start;if(this.isContextual("declare")){if(this.parseClassMemberFromModifier(t,e))return;e.declare=!0}super.parseClassMember(t,e,s,i),e.declare&&("ClassProperty"!==e.type&&"ClassPrivateProperty"!==e.type?this.raise(r,j.DeclareClassElement):e.value&&this.raise(e.value.start,j.DeclareClassFieldInitializer))}getTokenFromCode(t){const e=this.input.charCodeAt(this.state.pos+1);return 123===t&&124===e?this.finishOp(n.braceBarL,2):!this.state.inType||62!==t&&60!==t?function(t,e){return 64===t&&64===e}(t,e)?(this.state.isIterator=!0,super.readWord()):super.getTokenFromCode(t):this.finishOp(n.relational,1)}isAssignable(t,e){switch(t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":return!0;case"ObjectExpression":{const e=t.properties.length-1;return t.properties.every((t,s)=>"ObjectMethod"!==t.type&&(s===e||"SpreadElement"===t.type)&&this.isAssignable(t))}case"ObjectProperty":return this.isAssignable(t.value);case"SpreadElement":return this.isAssignable(t.argument);case"ArrayExpression":return t.elements.every(t=>this.isAssignable(t));case"AssignmentExpression":return"="===t.operator;case"ParenthesizedExpression":case"TypeCastExpression":return this.isAssignable(t.expression);case"MemberExpression":case"OptionalMemberExpression":return!e;default:return!1}}toAssignable(t){return"TypeCastExpression"===t.type?super.toAssignable(this.typeCastToParameter(t)):super.toAssignable(t)}toAssignableList(t,e){for(let e=0;e<t.length;e++){const s=t[e];s&&"TypeCastExpression"===s.type&&(t[e]=this.typeCastToParameter(s))}return super.toAssignableList(t,e)}toReferencedList(t,e){for(let s=0;s<t.length;s++){const i=t[s];!i||"TypeCastExpression"!==i.type||i.extra&&i.extra.parenthesized||!(t.length>1)&&e||this.raise(i.typeAnnotation.start,j.TypeCastInPattern)}return t}checkLVal(t,e=64,s,i){if("TypeCastExpression"!==t.type)return super.checkLVal(t,e,s,i)}parseClassProperty(t){return this.match(n.colon)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassProperty(t)}parseClassPrivateProperty(t){return this.match(n.colon)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassPrivateProperty(t)}isClassMethod(){return this.isRelational("<")||super.isClassMethod()}isClassProperty(){return this.match(n.colon)||super.isClassProperty()}isNonstaticConstructor(t){return!this.match(n.colon)&&super.isNonstaticConstructor(t)}pushClassMethod(t,e,s,i,r,a){e.variance&&this.unexpected(e.variance.start),delete e.variance,this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(t,e,s,i,r,a)}pushClassPrivateMethod(t,e,s,i){e.variance&&this.unexpected(e.variance.start),delete e.variance,this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(t,e,s,i)}parseClassSuper(t){if(super.parseClassSuper(t),t.superClass&&this.isRelational("<")&&(t.superTypeParameters=this.flowParseTypeParameterInstantiation()),this.isContextual("implements")){this.next();const e=t.implements=[];do{const t=this.startNode();t.id=this.flowParseRestrictedIdentifier(!0),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterInstantiation():t.typeParameters=null,e.push(this.finishNode(t,"ClassImplements"))}while(this.eat(n.comma))}}parsePropertyName(t,e){const s=this.flowParseVariance(),i=super.parsePropertyName(t,e);return t.variance=s,i}parseObjPropValue(t,e,s,i,r,a,o,h){let p;t.variance&&this.unexpected(t.variance.start),delete t.variance,this.isRelational("<")&&(p=this.flowParseTypeParameterDeclaration(),this.match(n.parenL)||this.unexpected()),super.parseObjPropValue(t,e,s,i,r,a,o,h),p&&((t.value||t).typeParameters=p)}parseAssignableListItemTypes(t){return this.eat(n.question)&&("Identifier"!==t.type&&this.raise(t.start,j.OptionalBindingPattern),t.optional=!0),this.match(n.colon)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),this.resetEndLocation(t),t}parseMaybeDefault(t,e,s){const i=super.parseMaybeDefault(t,e,s);return"AssignmentPattern"===i.type&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(i.typeAnnotation.start,j.TypeBeforeInitializer),i}shouldParseDefaultImport(t){return U(t)?q(this.state):super.shouldParseDefaultImport(t)}parseImportSpecifierLocal(t,e,s,i){e.local=U(t)?this.flowParseRestrictedIdentifier(!0,!0):this.parseIdentifier(),this.checkLVal(e.local,9,void 0,i),t.specifiers.push(this.finishNode(e,s))}maybeParseDefaultImportSpecifier(t){t.importKind="value";let e=null;if(this.match(n._typeof)?e="typeof":this.isContextual("type")&&(e="type"),e){const s=this.lookahead();"type"===e&&s.type===n.star&&this.unexpected(s.start),(q(s)||s.type===n.braceL||s.type===n.star)&&(this.next(),t.importKind=e)}return super.maybeParseDefaultImportSpecifier(t)}parseImportSpecifier(t){const e=this.startNode(),s=this.state.start,i=this.parseIdentifier(!0);let r=null;"type"===i.name?r="type":"typeof"===i.name&&(r="typeof");let a=!1;if(this.isContextual("as")&&!this.isLookaheadContextual("as")){const t=this.parseIdentifier(!0);null===r||this.match(n.name)||this.state.type.keyword?(e.imported=i,e.importKind=null,e.local=this.parseIdentifier()):(e.imported=t,e.importKind=r,e.local=t.__clone())}else null!==r&&(this.match(n.name)||this.state.type.keyword)?(e.imported=this.parseIdentifier(!0),e.importKind=r,this.eatContextual("as")?e.local=this.parseIdentifier():(a=!0,e.local=e.imported.__clone())):(a=!0,e.imported=i,e.importKind=null,e.local=e.imported.__clone());const o=U(t),h=U(e);o&&h&&this.raise(s,j.ImportTypeShorthandOnlyInPureImport),(o||h)&&this.checkReservedType(e.local.name,e.local.start,!0),!a||o||h||this.checkReservedWord(e.local.name,e.start,!0,!0),this.checkLVal(e.local,9,void 0,"import specifier"),t.specifiers.push(this.finishNode(e,"ImportSpecifier"))}parseFunctionParams(t,e){const s=t.kind;"get"!==s&&"set"!==s&&this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration()),super.parseFunctionParams(t,e)}parseVarId(t,e){super.parseVarId(t,e),this.match(n.colon)&&(t.id.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(t.id))}parseAsyncArrowFromCallExpression(t,e){if(this.match(n.colon)){const e=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,t.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=e}return super.parseAsyncArrowFromCallExpression(t,e)}shouldParseAsyncArrow(){return this.match(n.colon)||super.shouldParseAsyncArrow()}parseMaybeAssign(t,e,s,i){let r,a=null;if(this.hasPlugin("jsx")&&(this.match(n.jsxTagStart)||this.isRelational("<"))){if(a=this.state.clone(),r=this.tryParse(()=>super.parseMaybeAssign(t,e,s,i),a),!r.error)return r.node;const{context:n}=this.state;n[n.length-1]===x.j_oTag?n.length-=2:n[n.length-1]===x.j_expr&&(n.length-=1)}if(r&&r.error||this.isRelational("<")){let n;a=a||this.state.clone();const o=this.tryParse(()=>{n=this.flowParseTypeParameterDeclaration();const r=this.forwardNoArrowParamsConversionAt(n,()=>super.parseMaybeAssign(t,e,s,i));return r.typeParameters=n,this.resetStartLocationFromNode(r,n),r},a),h=o.node&&"ArrowFunctionExpression"===o.node.type?o.node:null;if(!o.error&&h)return h;if(r&&r.node)return this.state=r.failState,r.node;if(h)return this.state=o.failState,h;if(r&&r.thrown)throw r.error;if(o.thrown)throw o.error;throw this.raise(n.start,j.UnexpectedTokenAfterTypeParameter)}return super.parseMaybeAssign(t,e,s,i)}parseArrow(t){if(this.match(n.colon)){const e=this.tryParse(()=>{const e=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;const s=this.startNode();return[s.typeAnnotation,t.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=e,this.canInsertSemicolon()&&this.unexpected(),this.match(n.arrow)||this.unexpected(),s});if(e.thrown)return null;e.error&&(this.state=e.failState),t.returnType=e.node.typeAnnotation?this.finishNode(e.node,"TypeAnnotation"):null}return super.parseArrow(t)}shouldParseArrow(){return this.match(n.colon)||super.shouldParseArrow()}setArrowFunctionParameters(t,e){-1!==this.state.noArrowParamsConversionAt.indexOf(t.start)?t.params=e:super.setArrowFunctionParameters(t,e)}checkParams(t,e,s){if(!s||-1===this.state.noArrowParamsConversionAt.indexOf(t.start))return super.checkParams(...arguments)}parseParenAndDistinguishExpression(t){return super.parseParenAndDistinguishExpression(t&&-1===this.state.noArrowAt.indexOf(this.state.start))}parseSubscripts(t,e,s,i){if("Identifier"===t.type&&"async"===t.name&&-1!==this.state.noArrowAt.indexOf(e)){this.next();const i=this.startNodeAt(e,s);i.callee=t,i.arguments=this.parseCallExpressionArguments(n.parenR,!1),t=this.finishNode(i,"CallExpression")}else if("Identifier"===t.type&&"async"===t.name&&this.isRelational("<")){const r=this.state.clone(),a=this.tryParse(t=>this.parseAsyncArrowWithTypeParameters(e,s)||t(),r);if(!a.error&&!a.aborted)return a.node;const n=this.tryParse(()=>super.parseSubscripts(t,e,s,i),r);if(n.node&&!n.error)return n.node;if(a.node)return this.state=a.failState,a.node;if(n.node)return this.state=n.failState,n.node;throw a.error||n.error}return super.parseSubscripts(t,e,s,i)}parseSubscript(t,e,s,i,r){if(this.match(n.questionDot)&&this.isLookaheadRelational("<")){if(r.optionalChainMember=!0,i)return r.stop=!0,t;this.next();const a=this.startNodeAt(e,s);return a.callee=t,a.typeArguments=this.flowParseTypeParameterInstantiation(),this.expect(n.parenL),a.arguments=this.parseCallExpressionArguments(n.parenR,!1),a.optional=!0,this.finishCallExpression(a,!0)}if(!i&&this.shouldParseTypes()&&this.isRelational("<")){const i=this.startNodeAt(e,s);i.callee=t;const a=this.tryParse(()=>(i.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(n.parenL),i.arguments=this.parseCallExpressionArguments(n.parenR,!1),r.optionalChainMember&&(i.optional=!1),this.finishCallExpression(i,r.optionalChainMember)));if(a.node)return a.error&&(this.state=a.failState),a.node}return super.parseSubscript(t,e,s,i,r)}parseNewArguments(t){let e=null;this.shouldParseTypes()&&this.isRelational("<")&&(e=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),t.typeArguments=e,super.parseNewArguments(t)}parseAsyncArrowWithTypeParameters(t,e){const s=this.startNodeAt(t,e);if(this.parseFunctionParams(s),this.parseArrow(s))return this.parseArrowExpression(s,void 0,!0)}readToken_mult_modulo(t){const e=this.input.charCodeAt(this.state.pos+1);if(42===t&&47===e&&this.state.hasFlowComment)return this.state.hasFlowComment=!1,this.state.pos+=2,void this.nextToken();super.readToken_mult_modulo(t)}readToken_pipe_amp(t){const e=this.input.charCodeAt(this.state.pos+1);124!==t||125!==e?super.readToken_pipe_amp(t):this.finishOp(n.braceBarR,2)}parseTopLevel(t,e){const s=super.parseTopLevel(t,e);return this.state.hasFlowComment&&this.raise(this.state.pos,j.UnterminatedFlowComment),s}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment())return this.state.hasFlowComment&&this.unexpected(null,j.NestedFlowComment),this.hasFlowCommentCompletion(),this.state.pos+=this.skipFlowComment(),void(this.state.hasFlowComment=!0);if(this.state.hasFlowComment){const t=this.input.indexOf("*-/",this.state.pos+=2);if(-1===t)throw this.raise(this.state.pos-2,f.UnterminatedComment);this.state.pos=t+3}else super.skipBlockComment()}skipFlowComment(){const{pos:t}=this.state;let e=2;for(;[32,9].includes(this.input.charCodeAt(t+e));)e++;const s=this.input.charCodeAt(e+t),i=this.input.charCodeAt(e+t+1);return 58===s&&58===i?e+2:"flow-include"===this.input.slice(e+t,e+t+12)?e+12:58===s&&58!==i&&e}hasFlowCommentCompletion(){if(-1===this.input.indexOf("*/",this.state.pos))throw this.raise(this.state.pos,f.UnterminatedComment)}flowEnumErrorBooleanMemberNotInitialized(t,{enumName:e,memberName:s}){this.raise(t,j.EnumBooleanMemberNotInitialized,s,e)}flowEnumErrorInvalidMemberName(t,{enumName:e,memberName:s}){const i=s[0].toUpperCase()+s.slice(1);this.raise(t,j.EnumInvalidMemberName,s,i,e)}flowEnumErrorDuplicateMemberName(t,{enumName:e,memberName:s}){this.raise(t,j.EnumDuplicateMemberName,s,e)}flowEnumErrorInconsistentMemberValues(t,{enumName:e}){this.raise(t,j.EnumInconsistentMemberValues,e)}flowEnumErrorInvalidExplicitType(t,{enumName:e,suppliedType:s}){return this.raise(t,null===s?j.EnumInvalidExplicitTypeUnknownSupplied:j.EnumInvalidExplicitType,e,s)}flowEnumErrorInvalidMemberInitializer(t,{enumName:e,explicitType:s,memberName:i}){let r=null;switch(s){case"boolean":case"number":case"string":r=j.EnumInvalidMemberInitializerPrimaryType;break;case"symbol":r=j.EnumInvalidMemberInitializerSymbolType;break;default:r=j.EnumInvalidMemberInitializerUnknownType}return this.raise(t,r,e,i,s)}flowEnumErrorNumberMemberNotInitialized(t,{enumName:e,memberName:s}){this.raise(t,j.EnumNumberMemberNotInitialized,e,s)}flowEnumErrorStringMemberInconsistentlyInitailized(t,{enumName:e}){this.raise(t,j.EnumStringMemberInconsistentlyInitailized,e)}flowEnumMemberInit(){const t=this.state.start,e=()=>this.match(n.comma)||this.match(n.braceR);switch(this.state.type){case n.num:{const s=this.parseLiteral(this.state.value,"NumericLiteral");return e()?{type:"number",pos:s.start,value:s}:{type:"invalid",pos:t}}case n.string:{const s=this.parseLiteral(this.state.value,"StringLiteral");return e()?{type:"string",pos:s.start,value:s}:{type:"invalid",pos:t}}case n._true:case n._false:{const s=this.parseBooleanLiteral();return e()?{type:"boolean",pos:s.start,value:s}:{type:"invalid",pos:t}}default:return{type:"invalid",pos:t}}}flowEnumMemberRaw(){const t=this.state.start;return{id:this.parseIdentifier(!0),init:this.eat(n.eq)?this.flowEnumMemberInit():{type:"none",pos:t}}}flowEnumCheckExplicitTypeMismatch(t,e,s){const{explicitType:i}=e;null!==i&&i!==s&&this.flowEnumErrorInvalidMemberInitializer(t,e)}flowEnumMembers({enumName:t,explicitType:e}){const s=new Set,i={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]};for(;!this.match(n.braceR);){const r=this.startNode(),{id:a,init:o}=this.flowEnumMemberRaw(),h=a.name;if(""===h)continue;/^[a-z]/.test(h)&&this.flowEnumErrorInvalidMemberName(a.start,{enumName:t,memberName:h}),s.has(h)&&this.flowEnumErrorDuplicateMemberName(a.start,{enumName:t,memberName:h}),s.add(h);const p={enumName:t,explicitType:e,memberName:h};switch(r.id=a,o.type){case"boolean":this.flowEnumCheckExplicitTypeMismatch(o.pos,p,"boolean"),r.init=o.value,i.booleanMembers.push(this.finishNode(r,"EnumBooleanMember"));break;case"number":this.flowEnumCheckExplicitTypeMismatch(o.pos,p,"number"),r.init=o.value,i.numberMembers.push(this.finishNode(r,"EnumNumberMember"));break;case"string":this.flowEnumCheckExplicitTypeMismatch(o.pos,p,"string"),r.init=o.value,i.stringMembers.push(this.finishNode(r,"EnumStringMember"));break;case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(o.pos,p);case"none":switch(e){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(o.pos,p);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(o.pos,p);break;default:i.defaultedMembers.push(this.finishNode(r,"EnumDefaultedMember"))}}this.match(n.braceR)||this.expect(n.comma)}return i}flowEnumStringMembers(t,e,{enumName:s}){if(0===t.length)return e;if(0===e.length)return t;if(e.length>t.length){for(let e=0;e<t.length;e++){const i=t[e];this.flowEnumErrorStringMemberInconsistentlyInitailized(i.start,{enumName:s})}return e}for(let t=0;t<e.length;t++){const i=e[t];this.flowEnumErrorStringMemberInconsistentlyInitailized(i.start,{enumName:s})}return t}flowEnumParseExplicitType({enumName:t}){if(this.eatContextual("of")){if(!this.match(n.name))throw this.flowEnumErrorInvalidExplicitType(this.state.start,{enumName:t,suppliedType:null});const{value:e}=this.state;return this.next(),"boolean"!==e&&"number"!==e&&"string"!==e&&"symbol"!==e&&this.flowEnumErrorInvalidExplicitType(this.state.start,{enumName:t,suppliedType:e}),e}return null}flowEnumBody(t,{enumName:e,nameLoc:s}){const i=this.flowEnumParseExplicitType({enumName:e});this.expect(n.braceL);const r=this.flowEnumMembers({enumName:e,explicitType:i});switch(i){case"boolean":return t.explicitType=!0,t.members=r.booleanMembers,this.expect(n.braceR),this.finishNode(t,"EnumBooleanBody");case"number":return t.explicitType=!0,t.members=r.numberMembers,this.expect(n.braceR),this.finishNode(t,"EnumNumberBody");case"string":return t.explicitType=!0,t.members=this.flowEnumStringMembers(r.stringMembers,r.defaultedMembers,{enumName:e}),this.expect(n.braceR),this.finishNode(t,"EnumStringBody");case"symbol":return t.members=r.defaultedMembers,this.expect(n.braceR),this.finishNode(t,"EnumSymbolBody");default:{const i=()=>(t.members=[],this.expect(n.braceR),this.finishNode(t,"EnumStringBody"));t.explicitType=!1;const a=r.booleanMembers.length,o=r.numberMembers.length,h=r.stringMembers.length,p=r.defaultedMembers.length;if(a||o||h||p){if(a||o){if(!o&&!h&&a>=p){for(let t=0,s=r.defaultedMembers;t<s.length;t++){const i=s[t];this.flowEnumErrorBooleanMemberNotInitialized(i.start,{enumName:e,memberName:i.id.name})}return t.members=r.booleanMembers,this.expect(n.braceR),this.finishNode(t,"EnumBooleanBody")}if(!a&&!h&&o>=p){for(let t=0,s=r.defaultedMembers;t<s.length;t++){const i=s[t];this.flowEnumErrorNumberMemberNotInitialized(i.start,{enumName:e,memberName:i.id.name})}return t.members=r.numberMembers,this.expect(n.braceR),this.finishNode(t,"EnumNumberBody")}return this.flowEnumErrorInconsistentMemberValues(s,{enumName:e}),i()}return t.members=this.flowEnumStringMembers(r.stringMembers,r.defaultedMembers,{enumName:e}),this.expect(n.braceR),this.finishNode(t,"EnumStringBody")}return i()}}}flowParseEnumDeclaration(t){const e=this.parseIdentifier();return t.id=e,t.body=this.flowEnumBody(this.startNode(),{enumName:e.name,nameLoc:e.start}),this.finishNode(t,"EnumDeclaration")}},typescript:t=>class extends t{getScopeHandler(){return Z}tsIsIdentifier(){return this.match(n.name)}tsNextTokenCanFollowModifier(){return this.next(),!(this.hasPrecedingLineBreak()||this.match(n.parenL)||this.match(n.parenR)||this.match(n.colon)||this.match(n.eq)||this.match(n.question)||this.match(n.bang))}tsParseModifier(t){if(!this.match(n.name))return;const e=this.state.value;return-1!==t.indexOf(e)&&this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))?e:void 0}tsParseModifiers(t,e){for(;;){const s=this.state.start,i=this.tsParseModifier(e);if(!i)break;Object.hasOwnProperty.call(t,i)&&this.raise(s,rt.DuplicateModifier,i),t[i]=!0}}tsIsListTerminator(t){switch(t){case"EnumMembers":case"TypeMembers":return this.match(n.braceR);case"HeritageClauseElement":return this.match(n.braceL);case"TupleElementTypes":return this.match(n.bracketR);case"TypeParametersOrArguments":return this.isRelational(">")}throw new Error("Unreachable")}tsParseList(t,e){const s=[];for(;!this.tsIsListTerminator(t);)s.push(e());return s}tsParseDelimitedList(t,e){return st(this.tsParseDelimitedListWorker(t,e,!0))}tsParseDelimitedListWorker(t,e,s){const i=[];for(;!this.tsIsListTerminator(t);){const r=e();if(null==r)return;if(i.push(r),!this.eat(n.comma)){if(this.tsIsListTerminator(t))break;return void(s&&this.expect(n.comma))}}return i}tsParseBracketedList(t,e,s,i){i||(s?this.expect(n.bracketL):this.expectRelational("<"));const r=this.tsParseDelimitedList(t,e);return s?this.expect(n.bracketR):this.expectRelational(">"),r}tsParseImportType(){const t=this.startNode();return this.expect(n._import),this.expect(n.parenL),this.match(n.string)||this.raise(this.state.start,rt.UnsupportedImportTypeArgument),t.argument=this.parseExprAtom(),this.expect(n.parenR),this.eat(n.dot)&&(t.qualifier=this.tsParseEntityName(!0)),this.isRelational("<")&&(t.typeParameters=this.tsParseTypeArguments()),this.finishNode(t,"TSImportType")}tsParseEntityName(t){let e=this.parseIdentifier();for(;this.eat(n.dot);){const s=this.startNodeAtNode(e);s.left=e,s.right=this.parseIdentifier(t),e=this.finishNode(s,"TSQualifiedName")}return e}tsParseTypeReference(){const t=this.startNode();return t.typeName=this.tsParseEntityName(!1),!this.hasPrecedingLineBreak()&&this.isRelational("<")&&(t.typeParameters=this.tsParseTypeArguments()),this.finishNode(t,"TSTypeReference")}tsParseThisTypePredicate(t){this.next();const e=this.startNodeAtNode(t);return e.parameterName=t,e.typeAnnotation=this.tsParseTypeAnnotation(!1),this.finishNode(e,"TSTypePredicate")}tsParseThisTypeNode(){const t=this.startNode();return this.next(),this.finishNode(t,"TSThisType")}tsParseTypeQuery(){const t=this.startNode();return this.expect(n._typeof),this.match(n._import)?t.exprName=this.tsParseImportType():t.exprName=this.tsParseEntityName(!0),this.finishNode(t,"TSTypeQuery")}tsParseTypeParameter(){const t=this.startNode();return t.name=this.parseIdentifierName(t.start),t.constraint=this.tsEatThenParseType(n._extends),t.default=this.tsEatThenParseType(n.eq),this.finishNode(t,"TSTypeParameter")}tsTryParseTypeParameters(){if(this.isRelational("<"))return this.tsParseTypeParameters()}tsParseTypeParameters(){const t=this.startNode();return this.isRelational("<")||this.match(n.jsxTagStart)?this.next():this.unexpected(),t.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this),!1,!0),this.finishNode(t,"TSTypeParameterDeclaration")}tsTryNextParseConstantContext(){return this.lookahead().type===n._const?(this.next(),this.tsParseTypeReference()):null}tsFillSignature(t,e){const s=t===n.arrow;e.typeParameters=this.tsTryParseTypeParameters(),this.expect(n.parenL),e.parameters=this.tsParseBindingListForSignature(),s?e.typeAnnotation=this.tsParseTypeOrTypePredicateAnnotation(t):this.match(t)&&(e.typeAnnotation=this.tsParseTypeOrTypePredicateAnnotation(t))}tsParseBindingListForSignature(){return this.parseBindingList(n.parenR,41).map(t=>("Identifier"!==t.type&&"RestElement"!==t.type&&"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&this.raise(t.start,rt.UnsupportedSignatureParameterKind,t.type),t))}tsParseTypeMemberSemicolon(){this.eat(n.comma)||this.semicolon()}tsParseSignatureMember(t,e){return this.tsFillSignature(n.colon,e),this.tsParseTypeMemberSemicolon(),this.finishNode(e,t)}tsIsUnambiguouslyIndexSignature(){return this.next(),this.eat(n.name)&&this.match(n.colon)}tsTryParseIndexSignature(t){if(!this.match(n.bracketL)||!this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))return;this.expect(n.bracketL);const e=this.parseIdentifier();e.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(e),this.expect(n.bracketR),t.parameters=[e];const s=this.tsTryParseTypeAnnotation();return s&&(t.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(t,"TSIndexSignature")}tsParsePropertyOrMethodSignature(t,e){this.eat(n.question)&&(t.optional=!0);const s=t;if(e||!this.match(n.parenL)&&!this.isRelational("<")){const t=s;e&&(t.readonly=!0);const i=this.tsTryParseTypeAnnotation();return i&&(t.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(t,"TSPropertySignature")}{const t=s;return this.tsFillSignature(n.colon,t),this.tsParseTypeMemberSemicolon(),this.finishNode(t,"TSMethodSignature")}}tsParseTypeMember(){const t=this.startNode();if(this.match(n.parenL)||this.isRelational("<"))return this.tsParseSignatureMember("TSCallSignatureDeclaration",t);if(this.match(n._new)){const e=this.startNode();return this.next(),this.match(n.parenL)||this.isRelational("<")?this.tsParseSignatureMember("TSConstructSignatureDeclaration",t):(t.key=this.createIdentifier(e,"new"),this.tsParsePropertyOrMethodSignature(t,!1))}const e=!!this.tsParseModifier(["readonly"]),s=this.tsTryParseIndexSignature(t);return s?(e&&(t.readonly=!0),s):(this.parsePropertyName(t,!1),this.tsParsePropertyOrMethodSignature(t,e))}tsParseTypeLiteral(){const t=this.startNode();return t.members=this.tsParseObjectTypeMembers(),this.finishNode(t,"TSTypeLiteral")}tsParseObjectTypeMembers(){this.expect(n.braceL);const t=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(n.braceR),t}tsIsStartOfMappedType(){return this.next(),this.eat(n.plusMin)?this.isContextual("readonly"):(this.isContextual("readonly")&&this.next(),!!this.match(n.bracketL)&&(this.next(),!!this.tsIsIdentifier()&&(this.next(),this.match(n._in))))}tsParseMappedTypeParameter(){const t=this.startNode();return t.name=this.parseIdentifierName(t.start),t.constraint=this.tsExpectThenParseType(n._in),this.finishNode(t,"TSTypeParameter")}tsParseMappedType(){const t=this.startNode();return this.expect(n.braceL),this.match(n.plusMin)?(t.readonly=this.state.value,this.next(),this.expectContextual("readonly")):this.eatContextual("readonly")&&(t.readonly=!0),this.expect(n.bracketL),t.typeParameter=this.tsParseMappedTypeParameter(),this.expect(n.bracketR),this.match(n.plusMin)?(t.optional=this.state.value,this.next(),this.expect(n.question)):this.eat(n.question)&&(t.optional=!0),t.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(n.braceR),this.finishNode(t,"TSMappedType")}tsParseTupleType(){const t=this.startNode();t.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);let e=!1;return t.elementTypes.forEach(t=>{"TSOptionalType"===t.type?e=!0:e&&"TSRestType"!==t.type&&this.raise(t.start,rt.OptionalTypeBeforeRequired)}),this.finishNode(t,"TSTupleType")}tsParseTupleElementType(){if(this.match(n.ellipsis)){const t=this.startNode();return this.next(),t.typeAnnotation=this.tsParseType(),this.match(n.comma)&&93!==this.lookaheadCharCode()&&this.raiseRestNotLast(this.state.start),this.finishNode(t,"TSRestType")}const t=this.tsParseType();if(this.eat(n.question)){const e=this.startNodeAtNode(t);return e.typeAnnotation=t,this.finishNode(e,"TSOptionalType")}return t}tsParseParenthesizedType(){const t=this.startNode();return this.expect(n.parenL),t.typeAnnotation=this.tsParseType(),this.expect(n.parenR),this.finishNode(t,"TSParenthesizedType")}tsParseFunctionOrConstructorType(t){const e=this.startNode();return"TSConstructorType"===t&&this.expect(n._new),this.tsFillSignature(n.arrow,e),this.finishNode(e,t)}tsParseLiteralTypeNode(){const t=this.startNode();return t.literal=(()=>{switch(this.state.type){case n.num:case n.string:case n._true:case n._false:return this.parseExprAtom();default:throw this.unexpected()}})(),this.finishNode(t,"TSLiteralType")}tsParseTemplateLiteralType(){const t=this.startNode(),e=this.parseTemplate(!1);return e.expressions.length>0&&this.raise(e.expressions[0].start,rt.TemplateTypeHasSubstitution),t.literal=e,this.finishNode(t,"TSLiteralType")}tsParseThisTypeOrThisTypePredicate(){const t=this.tsParseThisTypeNode();return this.isContextual("is")&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(t):t}tsParseNonArrayType(){switch(this.state.type){case n.name:case n._void:case n._null:{const t=this.match(n._void)?"TSVoidKeyword":this.match(n._null)?"TSNullKeyword":function(t){switch(t){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"bigint":return"TSBigIntKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";case"unknown":return"TSUnknownKeyword";default:return}}(this.state.value);if(void 0!==t&&46!==this.lookaheadCharCode()){const e=this.startNode();return this.next(),this.finishNode(e,t)}return this.tsParseTypeReference()}case n.string:case n.num:case n._true:case n._false:return this.tsParseLiteralTypeNode();case n.plusMin:if("-"===this.state.value){const t=this.startNode();if(this.lookahead().type!==n.num)throw this.unexpected();return t.literal=this.parseMaybeUnary(),this.finishNode(t,"TSLiteralType")}break;case n._this:return this.tsParseThisTypeOrThisTypePredicate();case n._typeof:return this.tsParseTypeQuery();case n._import:return this.tsParseImportType();case n.braceL:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case n.bracketL:return this.tsParseTupleType();case n.parenL:return this.tsParseParenthesizedType();case n.backQuote:return this.tsParseTemplateLiteralType()}throw this.unexpected()}tsParseArrayTypeOrHigher(){let t=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(n.bracketL);)if(this.match(n.bracketR)){const e=this.startNodeAtNode(t);e.elementType=t,this.expect(n.bracketR),t=this.finishNode(e,"TSArrayType")}else{const e=this.startNodeAtNode(t);e.objectType=t,e.indexType=this.tsParseType(),this.expect(n.bracketR),t=this.finishNode(e,"TSIndexedAccessType")}return t}tsParseTypeOperator(t){const e=this.startNode();return this.expectContextual(t),e.operator=t,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),"readonly"===t&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(t){switch(t.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(t.start,rt.UnexpectedReadonly)}}tsParseInferType(){const t=this.startNode();this.expectContextual("infer");const e=this.startNode();return e.name=this.parseIdentifierName(e.start),t.typeParameter=this.finishNode(e,"TSTypeParameter"),this.finishNode(t,"TSInferType")}tsParseTypeOperatorOrHigher(){const t=["keyof","unique","readonly"].find(t=>this.isContextual(t));return t?this.tsParseTypeOperator(t):this.isContextual("infer")?this.tsParseInferType():this.tsParseArrayTypeOrHigher()}tsParseUnionOrIntersectionType(t,e,s){this.eat(s);let i=e();if(this.match(s)){const r=[i];for(;this.eat(s);)r.push(e());const a=this.startNodeAtNode(i);a.types=r,i=this.finishNode(a,t)}return i}tsParseIntersectionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),n.bitwiseAND)}tsParseUnionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),n.bitwiseOR)}tsIsStartOfFunctionType(){return!!this.isRelational("<")||this.match(n.parenL)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))}tsSkipParameterStart(){if(this.match(n.name)||this.match(n._this))return this.next(),!0;if(this.match(n.braceL)){let t=1;for(this.next();t>0;)this.match(n.braceL)?++t:this.match(n.braceR)&&--t,this.next();return!0}if(this.match(n.bracketL)){let t=1;for(this.next();t>0;)this.match(n.bracketL)?++t:this.match(n.bracketR)&&--t,this.next();return!0}return!1}tsIsUnambiguouslyStartOfFunctionType(){if(this.next(),this.match(n.parenR)||this.match(n.ellipsis))return!0;if(this.tsSkipParameterStart()){if(this.match(n.colon)||this.match(n.comma)||this.match(n.question)||this.match(n.eq))return!0;if(this.match(n.parenR)&&(this.next(),this.match(n.arrow)))return!0}return!1}tsParseTypeOrTypePredicateAnnotation(t){return this.tsInType(()=>{const e=this.startNode();this.expect(t);const s=this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(s&&this.match(n._this)){let t=this.tsParseThisTypeOrThisTypePredicate();if("TSThisType"===t.type){const s=this.startNodeAtNode(e);s.parameterName=t,s.asserts=!0,t=this.finishNode(s,"TSTypePredicate")}else t.asserts=!0;return e.typeAnnotation=t,this.finishNode(e,"TSTypeAnnotation")}const i=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!i){if(!s)return this.tsParseTypeAnnotation(!1,e);const t=this.startNodeAtNode(e);return t.parameterName=this.parseIdentifier(),t.asserts=s,e.typeAnnotation=this.finishNode(t,"TSTypePredicate"),this.finishNode(e,"TSTypeAnnotation")}const r=this.tsParseTypeAnnotation(!1),a=this.startNodeAtNode(e);return a.parameterName=i,a.typeAnnotation=r,a.asserts=s,e.typeAnnotation=this.finishNode(a,"TSTypePredicate"),this.finishNode(e,"TSTypeAnnotation")})}tsTryParseTypeOrTypePredicateAnnotation(){return this.match(n.colon)?this.tsParseTypeOrTypePredicateAnnotation(n.colon):void 0}tsTryParseTypeAnnotation(){return this.match(n.colon)?this.tsParseTypeAnnotation():void 0}tsTryParseType(){return this.tsEatThenParseType(n.colon)}tsParseTypePredicatePrefix(){const t=this.parseIdentifier();if(this.isContextual("is")&&!this.hasPrecedingLineBreak())return this.next(),t}tsParseTypePredicateAsserts(){if(!this.match(n.name)||"asserts"!==this.state.value||this.hasPrecedingLineBreak())return!1;const t=this.state.containsEsc;return this.next(),!(!this.match(n.name)&&!this.match(n._this))&&(t&&this.raise(this.state.lastTokStart,f.InvalidEscapedReservedWord,"asserts"),!0)}tsParseTypeAnnotation(t=!0,e=this.startNode()){return this.tsInType(()=>{t&&this.expect(n.colon),e.typeAnnotation=this.tsParseType()}),this.finishNode(e,"TSTypeAnnotation")}tsParseType(){it(this.state.inType);const t=this.tsParseNonConditionalType();if(this.hasPrecedingLineBreak()||!this.eat(n._extends))return t;const e=this.startNodeAtNode(t);return e.checkType=t,e.extendsType=this.tsParseNonConditionalType(),this.expect(n.question),e.trueType=this.tsParseType(),this.expect(n.colon),e.falseType=this.tsParseType(),this.finishNode(e,"TSConditionalType")}tsParseNonConditionalType(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(n._new)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.tsParseUnionTypeOrHigher()}tsParseTypeAssertion(){const t=this.startNode(),e=this.tsTryNextParseConstantContext();return t.typeAnnotation=e||this.tsNextThenParseType(),this.expectRelational(">"),t.expression=this.parseMaybeUnary(),this.finishNode(t,"TSTypeAssertion")}tsParseHeritageClause(t){const e=this.state.start,s=this.tsParseDelimitedList("HeritageClauseElement",this.tsParseExpressionWithTypeArguments.bind(this));return s.length||this.raise(e,rt.EmptyHeritageClauseType,t),s}tsParseExpressionWithTypeArguments(){const t=this.startNode();return t.expression=this.tsParseEntityName(!1),this.isRelational("<")&&(t.typeParameters=this.tsParseTypeArguments()),this.finishNode(t,"TSExpressionWithTypeArguments")}tsParseInterfaceDeclaration(t){t.id=this.parseIdentifier(),this.checkLVal(t.id,130,void 0,"typescript interface declaration"),t.typeParameters=this.tsTryParseTypeParameters(),this.eat(n._extends)&&(t.extends=this.tsParseHeritageClause("extends"));const e=this.startNode();return e.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),t.body=this.finishNode(e,"TSInterfaceBody"),this.finishNode(t,"TSInterfaceDeclaration")}tsParseTypeAliasDeclaration(t){return t.id=this.parseIdentifier(),this.checkLVal(t.id,2,void 0,"typescript type alias"),t.typeParameters=this.tsTryParseTypeParameters(),t.typeAnnotation=this.tsExpectThenParseType(n.eq),this.semicolon(),this.finishNode(t,"TSTypeAliasDeclaration")}tsInNoContext(t){const e=this.state.context;this.state.context=[e[0]];try{return t()}finally{this.state.context=e}}tsInType(t){const e=this.state.inType;this.state.inType=!0;try{return t()}finally{this.state.inType=e}}tsEatThenParseType(t){return this.match(t)?this.tsNextThenParseType():void 0}tsExpectThenParseType(t){return this.tsDoThenParseType(()=>this.expect(t))}tsNextThenParseType(){return this.tsDoThenParseType(()=>this.next())}tsDoThenParseType(t){return this.tsInType(()=>(t(),this.tsParseType()))}tsParseEnumMember(){const t=this.startNode();return t.id=this.match(n.string)?this.parseExprAtom():this.parseIdentifier(!0),this.eat(n.eq)&&(t.initializer=this.parseMaybeAssign()),this.finishNode(t,"TSEnumMember")}tsParseEnumDeclaration(t,e){return e&&(t.const=!0),t.id=this.parseIdentifier(),this.checkLVal(t.id,e?779:267,void 0,"typescript enum declaration"),this.expect(n.braceL),t.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(n.braceR),this.finishNode(t,"TSEnumDeclaration")}tsParseModuleBlock(){const t=this.startNode();return this.scope.enter(0),this.expect(n.braceL),this.parseBlockOrModuleBlockBody(t.body=[],void 0,!0,n.braceR),this.scope.exit(),this.finishNode(t,"TSModuleBlock")}tsParseModuleOrNamespaceDeclaration(t,e=!1){if(t.id=this.parseIdentifier(),e||this.checkLVal(t.id,1024,null,"module or namespace declaration"),this.eat(n.dot)){const e=this.startNode();this.tsParseModuleOrNamespaceDeclaration(e,!0),t.body=e}else this.scope.enter(128),this.prodParam.enter(0),t.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(t,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(t){return this.isContextual("global")?(t.global=!0,t.id=this.parseIdentifier()):this.match(n.string)?t.id=this.parseExprAtom():this.unexpected(),this.match(n.braceL)?(this.scope.enter(128),this.prodParam.enter(0),t.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(t,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(t,e){return t.isExport=e||!1,t.id=this.parseIdentifier(),this.checkLVal(t.id,9,void 0,"import equals declaration"),this.expect(n.eq),t.moduleReference=this.tsParseModuleReference(),this.semicolon(),this.finishNode(t,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual("require")&&40===this.lookaheadCharCode()}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(!1)}tsParseExternalModuleReference(){const t=this.startNode();if(this.expectContextual("require"),this.expect(n.parenL),!this.match(n.string))throw this.unexpected();return t.expression=this.parseExprAtom(),this.expect(n.parenR),this.finishNode(t,"TSExternalModuleReference")}tsLookAhead(t){const e=this.state.clone(),s=t();return this.state=e,s}tsTryParseAndCatch(t){const e=this.tryParse(e=>t()||e());if(!e.aborted&&e.node)return e.error&&(this.state=e.failState),e.node}tsTryParse(t){const e=this.state.clone(),s=t();return void 0!==s&&!1!==s?s:void(this.state=e)}tsTryParseDeclare(t){if(this.isLineTerminator())return;let e,s=this.state.type;switch(this.isContextual("let")&&(s=n._var,e="let"),s){case n._function:return this.parseFunctionStatement(t,!1,!0);case n._class:return t.declare=!0,this.parseClass(t,!0,!1);case n._const:if(this.match(n._const)&&this.isLookaheadContextual("enum"))return this.expect(n._const),this.expectContextual("enum"),this.tsParseEnumDeclaration(t,!0);case n._var:return e=e||this.state.value,this.parseVarStatement(t,e);case n.name:{const e=this.state.value;return"global"===e?this.tsParseAmbientExternalModuleDeclaration(t):this.tsParseDeclaration(t,e,!0)}}}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.value,!0)}tsParseExpressionStatement(t,e){switch(e.name){case"declare":{const e=this.tsTryParseDeclare(t);if(e)return e.declare=!0,e;break}case"global":if(this.match(n.braceL)){this.scope.enter(128),this.prodParam.enter(0);const s=t;return s.global=!0,s.id=e,s.body=this.tsParseModuleBlock(),this.scope.exit(),this.prodParam.exit(),this.finishNode(s,"TSModuleDeclaration")}break;default:return this.tsParseDeclaration(t,e.name,!1)}}tsParseDeclaration(t,e,s){switch(e){case"abstract":if(this.tsCheckLineTerminatorAndMatch(n._class,s)){const e=t;return e.abstract=!0,s&&(this.next(),this.match(n._class)||this.unexpected(null,n._class)),this.parseClass(e,!0,!1)}break;case"enum":if(s||this.match(n.name))return s&&this.next(),this.tsParseEnumDeclaration(t,!1);break;case"interface":if(this.tsCheckLineTerminatorAndMatch(n.name,s))return s&&this.next(),this.tsParseInterfaceDeclaration(t);break;case"module":if(s&&this.next(),this.match(n.string))return this.tsParseAmbientExternalModuleDeclaration(t);if(this.tsCheckLineTerminatorAndMatch(n.name,s))return this.tsParseModuleOrNamespaceDeclaration(t);break;case"namespace":if(this.tsCheckLineTerminatorAndMatch(n.name,s))return s&&this.next(),this.tsParseModuleOrNamespaceDeclaration(t);break;case"type":if(this.tsCheckLineTerminatorAndMatch(n.name,s))return s&&this.next(),this.tsParseTypeAliasDeclaration(t)}}tsCheckLineTerminatorAndMatch(t,e){return(e||this.match(t))&&!this.isLineTerminator()}tsTryParseGenericAsyncArrowFunction(t,e){if(!this.isRelational("<"))return;const s=this.state.maybeInArrowParameters,i=this.state.yieldPos,r=this.state.awaitPos;this.state.maybeInArrowParameters=!0,this.state.yieldPos=-1,this.state.awaitPos=-1;const a=this.tsTryParseAndCatch(()=>{const s=this.startNodeAt(t,e);return s.typeParameters=this.tsParseTypeParameters(),super.parseFunctionParams(s),s.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(n.arrow),s});return this.state.maybeInArrowParameters=s,this.state.yieldPos=i,this.state.awaitPos=r,a?this.parseArrowExpression(a,null,!0):void 0}tsParseTypeArguments(){const t=this.startNode();return t.params=this.tsInType(()=>this.tsInNoContext(()=>(this.expectRelational("<"),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))),this.state.exprAllowed=!1,this.expectRelational(">"),this.finishNode(t,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){if(this.match(n.name))switch(this.state.value){case"abstract":case"declare":case"enum":case"interface":case"module":case"namespace":case"type":return!0}return!1}isExportDefaultSpecifier(){return!this.tsIsDeclarationStart()&&super.isExportDefaultSpecifier()}parseAssignableListItem(t,e){const s=this.state.start,i=this.state.startLoc;let r,a=!1;t&&(r=this.parseAccessModifier(),a=!!this.tsParseModifier(["readonly"]));const n=this.parseMaybeDefault();this.parseAssignableListItemTypes(n);const o=this.parseMaybeDefault(n.start,n.loc.start,n);if(r||a){const t=this.startNodeAt(s,i);return e.length&&(t.decorators=e),r&&(t.accessibility=r),a&&(t.readonly=a),"Identifier"!==o.type&&"AssignmentPattern"!==o.type&&this.raise(t.start,rt.UnsupportedParameterPropertyKind),t.parameter=o,this.finishNode(t,"TSParameterProperty")}return e.length&&(n.decorators=e),o}parseFunctionBodyAndFinish(t,e,s=!1){this.match(n.colon)&&(t.returnType=this.tsParseTypeOrTypePredicateAnnotation(n.colon));const i="FunctionDeclaration"===e?"TSDeclareFunction":"ClassMethod"===e?"TSDeclareMethod":void 0;i&&!this.match(n.braceL)&&this.isLineTerminator()?this.finishNode(t,i):super.parseFunctionBodyAndFinish(t,e,s)}registerFunctionStatementId(t){!t.body&&t.id?this.checkLVal(t.id,1024,null,"function name"):super.registerFunctionStatementId(...arguments)}parseSubscript(t,e,s,i,r){if(!this.hasPrecedingLineBreak()&&this.match(n.bang)){this.state.exprAllowed=!1,this.next();const i=this.startNodeAt(e,s);return i.expression=t,this.finishNode(i,"TSNonNullExpression")}if(this.isRelational("<")){const a=this.tsTryParseAndCatch(()=>{if(!i&&this.atPossibleAsyncArrow(t)){const t=this.tsTryParseGenericAsyncArrowFunction(e,s);if(t)return t}const a=this.startNodeAt(e,s);a.callee=t;const o=this.tsParseTypeArguments();if(o){if(!i&&this.eat(n.parenL))return a.arguments=this.parseCallExpressionArguments(n.parenR,!1),a.typeParameters=o,this.finishCallExpression(a,r.optionalChainMember);if(this.match(n.backQuote))return this.parseTaggedTemplateExpression(e,s,t,r,o)}this.unexpected()});if(a)return a}return super.parseSubscript(t,e,s,i,r)}parseNewArguments(t){if(this.isRelational("<")){const e=this.tsTryParseAndCatch(()=>{const t=this.tsParseTypeArguments();return this.match(n.parenL)||this.unexpected(),t});e&&(t.typeParameters=e)}super.parseNewArguments(t)}parseExprOp(t,e,s,i,r){if(st(n._in.binop)>i&&!this.hasPrecedingLineBreak()&&this.isContextual("as")){const a=this.startNodeAt(e,s);a.expression=t;const n=this.tsTryNextParseConstantContext();return a.typeAnnotation=n||this.tsNextThenParseType(),this.finishNode(a,"TSAsExpression"),this.parseExprOp(a,e,s,i,r)}return super.parseExprOp(t,e,s,i,r)}checkReservedWord(t,e,s,i){}checkDuplicateExports(){}parseImport(t){if(this.match(n.name)||this.match(n.star)||this.match(n.braceL)){const e=this.lookahead();if(this.match(n.name)&&e.type===n.eq)return this.tsParseImportEqualsDeclaration(t);!this.isContextual("type")||e.type===n.comma||e.type===n.name&&"from"===e.value?t.importKind="value":(t.importKind="type",this.next())}const e=super.parseImport(t);return"type"===e.importKind&&e.specifiers.length>1&&"ImportDefaultSpecifier"===e.specifiers[0].type&&this.raise(e.start,"A type-only import can specify a default import or named bindings, but not both."),e}parseExport(t){if(this.match(n._import))return this.expect(n._import),this.tsParseImportEqualsDeclaration(t,!0);if(this.eat(n.eq)){const e=t;return e.expression=this.parseExpression(),this.semicolon(),this.finishNode(e,"TSExportAssignment")}if(this.eatContextual("as")){const e=t;return this.expectContextual("namespace"),e.id=this.parseIdentifier(),this.semicolon(),this.finishNode(e,"TSNamespaceExportDeclaration")}return this.isContextual("type")&&this.lookahead().type===n.braceL?(this.next(),t.exportKind="type"):t.exportKind="value",super.parseExport(t)}isAbstractClass(){return this.isContextual("abstract")&&this.lookahead().type===n._class}parseExportDefaultExpression(){if(this.isAbstractClass()){const t=this.startNode();return this.next(),this.parseClass(t,!0,!0),t.abstract=!0,t}if("interface"===this.state.value){const t=this.tsParseDeclaration(this.startNode(),this.state.value,!0);if(t)return t}return super.parseExportDefaultExpression()}parseStatementContent(t,e){if(this.state.type===n._const){const t=this.lookahead();if(t.type===n.name&&"enum"===t.value){const t=this.startNode();return this.expect(n._const),this.expectContextual("enum"),this.tsParseEnumDeclaration(t,!0)}}return super.parseStatementContent(t,e)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}parseClassMember(t,e,s,i){this.tsParseModifiers(e,["declare"]);const r=this.parseAccessModifier();r&&(e.accessibility=r),this.tsParseModifiers(e,["declare"]),super.parseClassMember(t,e,s,i)}parseClassMemberWithIsStatic(t,e,s,i,r){this.tsParseModifiers(e,["abstract","readonly","declare"]);const a=this.tsTryParseIndexSignature(e);if(a)return t.body.push(a),e.abstract&&this.raise(e.start,rt.IndexSignatureHasAbstract),i&&this.raise(e.start,rt.IndexSignatureHasStatic),void(e.accessibility&&this.raise(e.start,rt.IndexSignatureHasAccessibility,e.accessibility));super.parseClassMemberWithIsStatic(t,e,s,i,r)}parsePostMemberNameModifiers(t){this.eat(n.question)&&(t.optional=!0),t.readonly&&this.match(n.parenL)&&this.raise(t.start,rt.ClassMethodHasReadonly),t.declare&&this.match(n.parenL)&&this.raise(t.start,rt.ClassMethodHasDeclare)}parseExpressionStatement(t,e){return("Identifier"===e.type?this.tsParseExpressionStatement(t,e):void 0)||super.parseExpressionStatement(t,e)}shouldParseExportDeclaration(){return!!this.tsIsDeclarationStart()||super.shouldParseExportDeclaration()}parseConditional(t,e,s,i,r){if(!r||!this.match(n.question))return super.parseConditional(t,e,s,i,r);const a=this.tryParse(()=>super.parseConditional(t,e,s,i));return a.node?(a.error&&(this.state=a.failState),a.node):(r.start=a.error.pos||this.state.start,t)}parseParenItem(t,e,s){if(t=super.parseParenItem(t,e,s),this.eat(n.question)&&(t.optional=!0,this.resetEndLocation(t)),this.match(n.colon)){const i=this.startNodeAt(e,s);return i.expression=t,i.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(i,"TSTypeCastExpression")}return t}parseExportDeclaration(t){const e=this.state.start,s=this.state.startLoc,i=this.eatContextual("declare");let r;return this.match(n.name)&&(r=this.tsTryParseExportDeclaration()),r||(r=super.parseExportDeclaration(t)),r&&("TSInterfaceDeclaration"===r.type||"TSTypeAliasDeclaration"===r.type||i)&&(t.exportKind="type"),r&&i&&(this.resetStartLocation(r,e,s),r.declare=!0),r}parseClassId(t,e,s){if((!e||s)&&this.isContextual("implements"))return;super.parseClassId(t,e,s,t.declare?1024:139);const i=this.tsTryParseTypeParameters();i&&(t.typeParameters=i)}parseClassPropertyAnnotation(t){!t.optional&&this.eat(n.bang)&&(t.definite=!0);const e=this.tsTryParseTypeAnnotation();e&&(t.typeAnnotation=e)}parseClassProperty(t){return this.parseClassPropertyAnnotation(t),t.declare&&this.match(n.equal)&&this.raise(this.state.start,rt.DeclareClassFieldHasInitializer),super.parseClassProperty(t)}parseClassPrivateProperty(t){return t.abstract&&this.raise(t.start,rt.PrivateElementHasAbstract),t.accessibility&&this.raise(t.start,rt.PrivateElementHasAccessibility,t.accessibility),this.parseClassPropertyAnnotation(t),super.parseClassPrivateProperty(t)}pushClassMethod(t,e,s,i,r,a){const n=this.tsTryParseTypeParameters();n&&(e.typeParameters=n),super.pushClassMethod(t,e,s,i,r,a)}pushClassPrivateMethod(t,e,s,i){const r=this.tsTryParseTypeParameters();r&&(e.typeParameters=r),super.pushClassPrivateMethod(t,e,s,i)}parseClassSuper(t){super.parseClassSuper(t),t.superClass&&this.isRelational("<")&&(t.superTypeParameters=this.tsParseTypeArguments()),this.eatContextual("implements")&&(t.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(t,...e){const s=this.tsTryParseTypeParameters();s&&(t.typeParameters=s),super.parseObjPropValue(t,...e)}parseFunctionParams(t,e){const s=this.tsTryParseTypeParameters();s&&(t.typeParameters=s),super.parseFunctionParams(t,e)}parseVarId(t,e){super.parseVarId(t,e),"Identifier"===t.id.type&&this.eat(n.bang)&&(t.definite=!0);const s=this.tsTryParseTypeAnnotation();s&&(t.id.typeAnnotation=s,this.resetEndLocation(t.id))}parseAsyncArrowFromCallExpression(t,e){return this.match(n.colon)&&(t.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(t,e)}parseMaybeAssign(...t){let e,s,i,r;if(this.match(n.jsxTagStart)){if(e=this.state.clone(),s=this.tryParse(()=>super.parseMaybeAssign(...t),e),!s.error)return s.node;const{context:i}=this.state;i[i.length-1]===x.j_oTag?i.length-=2:i[i.length-1]===x.j_expr&&(i.length-=1)}if(!(s&&s.error||this.isRelational("<")))return super.parseMaybeAssign(...t);e=e||this.state.clone();const a=this.tryParse(e=>{r=this.tsParseTypeParameters();const s=super.parseMaybeAssign(...t);return("ArrowFunctionExpression"!==s.type||s.extra&&s.extra.parenthesized)&&e(),r&&0!==r.params.length&&this.resetStartLocationFromNode(s,r),s.typeParameters=r,s},e);if(!a.error&&!a.aborted)return a.node;if(!s&&(it(!this.hasPlugin("jsx")),i=this.tryParse(()=>super.parseMaybeAssign(...t),e),!i.error))return i.node;if(s&&s.node)return this.state=s.failState,s.node;if(a.node)return this.state=a.failState,a.node;if(i&&i.node)return this.state=i.failState,i.node;if(s&&s.thrown)throw s.error;if(a.thrown)throw a.error;if(i&&i.thrown)throw i.error;throw s&&s.error||a.error||i&&i.error}parseMaybeUnary(t){return!this.hasPlugin("jsx")&&this.isRelational("<")?this.tsParseTypeAssertion():super.parseMaybeUnary(t)}parseArrow(t){if(this.match(n.colon)){const e=this.tryParse(t=>{const e=this.tsParseTypeOrTypePredicateAnnotation(n.colon);return!this.canInsertSemicolon()&&this.match(n.arrow)||t(),e});if(e.aborted)return;e.thrown||(e.error&&(this.state=e.failState),t.returnType=e.node)}return super.parseArrow(t)}parseAssignableListItemTypes(t){this.eat(n.question)&&("Identifier"!==t.type&&this.raise(t.start,rt.PatternIsOptional),t.optional=!0);const e=this.tsTryParseTypeAnnotation();return e&&(t.typeAnnotation=e),this.resetEndLocation(t),t}toAssignable(t){switch(t.type){case"TSTypeCastExpression":return super.toAssignable(this.typeCastToParameter(t));case"TSParameterProperty":return super.toAssignable(t);case"TSAsExpression":case"TSNonNullExpression":case"TSTypeAssertion":return t.expression=this.toAssignable(t.expression),t;default:return super.toAssignable(t)}}checkLVal(t,e=64,s,i){switch(t.type){case"TSTypeCastExpression":return;case"TSParameterProperty":return void this.checkLVal(t.parameter,e,s,"parameter property");case"TSAsExpression":case"TSNonNullExpression":case"TSTypeAssertion":return void this.checkLVal(t.expression,e,s,i);default:return void super.checkLVal(t,e,s,i)}}parseBindingAtom(){switch(this.state.type){case n._this:return this.parseIdentifier(!0);default:return super.parseBindingAtom()}}parseMaybeDecoratorArguments(t){if(this.isRelational("<")){const e=this.tsParseTypeArguments();if(this.match(n.parenL)){const s=super.parseMaybeDecoratorArguments(t);return s.typeParameters=e,s}this.unexpected(this.state.start,n.parenL)}return super.parseMaybeDecoratorArguments(t)}isClassMethod(){return this.isRelational("<")||super.isClassMethod()}isClassProperty(){return this.match(n.bang)||this.match(n.colon)||super.isClassProperty()}parseMaybeDefault(...t){const e=super.parseMaybeDefault(...t);return"AssignmentPattern"===e.type&&e.typeAnnotation&&e.right.start<e.typeAnnotation.start&&this.raise(e.typeAnnotation.start,rt.TypeAnnotationAfterAssign),e}getTokenFromCode(t){return!this.state.inType||62!==t&&60!==t?super.getTokenFromCode(t):this.finishOp(n.relational,1)}toAssignableList(t){for(let e=0;e<t.length;e++){const s=t[e];if(s)switch(s.type){case"TSTypeCastExpression":t[e]=this.typeCastToParameter(s);break;case"TSAsExpression":case"TSTypeAssertion":this.state.maybeInArrowParameters?this.raise(s.start,rt.UnexpectedTypeCastInParameter):t[e]=this.typeCastToParameter(s)}}return super.toAssignableList(...arguments)}typeCastToParameter(t){return t.expression.typeAnnotation=t.typeAnnotation,this.resetEndLocation(t.expression,t.typeAnnotation.end,t.typeAnnotation.loc.end),t.expression}toReferencedList(t,e){for(let e=0;e<t.length;e++){const s=t[e];s&&"TSTypeCastExpression"===s.type&&this.raise(s.start,rt.UnexpectedTypeAnnotation)}return t}shouldParseArrow(){return this.match(n.colon)||super.shouldParseArrow()}shouldParseAsyncArrow(){return this.match(n.colon)||super.shouldParseAsyncArrow()}canHaveLeadingDecorator(){return super.canHaveLeadingDecorator()||this.isAbstractClass()}jsxParseOpeningElementAfterName(t){if(this.isRelational("<")){const e=this.tsTryParseAndCatch(()=>this.tsParseTypeArguments());e&&(t.typeParameters=e)}return super.jsxParseOpeningElementAfterName(t)}getGetterSetterExpectedParamCount(t){const e=super.getGetterSetterExpectedParamCount(t),s=t.params[0];return s&&"Identifier"===s.type&&"this"===s.name?e+1:e}},v8intrinsic:t=>class extends t{parseV8Intrinsic(){if(this.match(n.modulo)){const t=this.state.start,e=this.startNode();if(this.eat(n.modulo),this.match(n.name)){const t=this.parseIdentifierName(this.state.start),s=this.createIdentifier(e,t);if(s.type="V8IntrinsicIdentifier",this.match(n.parenL))return s}this.unexpected(t)}}parseExprAtom(){return this.parseV8Intrinsic()||super.parseExprAtom(...arguments)}},placeholders:t=>class extends t{parsePlaceholder(t){if(this.match(n.placeholder)){const e=this.startNode();return this.next(),this.assertNoSpace("Unexpected space in placeholder."),e.name=super.parseIdentifier(!0),this.assertNoSpace("Unexpected space in placeholder."),this.expect(n.placeholder),this.finishPlaceholder(e,t)}}finishPlaceholder(t,e){const s=!(!t.expectedNode||"Placeholder"!==t.type);return t.expectedNode=e,s?t:this.finishNode(t,"Placeholder")}getTokenFromCode(t){return 37===t&&37===this.input.charCodeAt(this.state.pos+1)?this.finishOp(n.placeholder,2):super.getTokenFromCode(...arguments)}parseExprAtom(){return this.parsePlaceholder("Expression")||super.parseExprAtom(...arguments)}parseIdentifier(){return this.parsePlaceholder("Identifier")||super.parseIdentifier(...arguments)}checkReservedWord(t){void 0!==t&&super.checkReservedWord(...arguments)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom(...arguments)}checkLVal(t){"Placeholder"!==t.type&&super.checkLVal(...arguments)}toAssignable(t){return t&&"Placeholder"===t.type&&"Expression"===t.expectedNode?(t.expectedNode="Pattern",t):super.toAssignable(...arguments)}verifyBreakContinue(t){t.label&&"Placeholder"===t.label.type||super.verifyBreakContinue(...arguments)}parseExpressionStatement(t,e){if("Placeholder"!==e.type||e.extra&&e.extra.parenthesized)return super.parseExpressionStatement(...arguments);if(this.match(n.colon)){const s=t;return s.label=this.finishPlaceholder(e,"Identifier"),this.next(),s.body=this.parseStatement("label"),this.finishNode(s,"LabeledStatement")}return this.semicolon(),t.name=e.name,this.finishPlaceholder(t,"Statement")}parseBlock(){return this.parsePlaceholder("BlockStatement")||super.parseBlock(...arguments)}parseFunctionId(){return this.parsePlaceholder("Identifier")||super.parseFunctionId(...arguments)}parseClass(t,e,s){const i=e?"ClassDeclaration":"ClassExpression";this.next(),this.takeDecorators(t);const r=this.parsePlaceholder("Identifier");if(r)if(this.match(n._extends)||this.match(n.placeholder)||this.match(n.braceL))t.id=r;else{if(s||!e)return t.id=null,t.body=this.finishPlaceholder(r,"ClassBody"),this.finishNode(t,i);this.unexpected(null,"A class name is required")}else this.parseClassId(t,e,s);return this.parseClassSuper(t),t.body=this.parsePlaceholder("ClassBody")||this.parseClassBody(!!t.superClass),this.finishNode(t,i)}parseExport(t){const e=this.parsePlaceholder("Identifier");if(!e)return super.parseExport(...arguments);if(!this.isContextual("from")&&!this.match(n.comma))return t.specifiers=[],t.source=null,t.declaration=this.finishPlaceholder(e,"Declaration"),this.finishNode(t,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");const s=this.startNode();return s.exported=e,t.specifiers=[this.finishNode(s,"ExportDefaultSpecifier")],super.parseExport(t)}maybeParseExportDefaultSpecifier(t){return!!(t.specifiers&&t.specifiers.length>0)||super.maybeParseExportDefaultSpecifier(...arguments)}checkExport(t){const{specifiers:e}=t;e&&e.length&&(t.specifiers=e.filter(t=>"Placeholder"===t.exported.type)),super.checkExport(t),t.specifiers=e}parseImport(t){const e=this.parsePlaceholder("Identifier");if(!e)return super.parseImport(...arguments);if(t.specifiers=[],!this.isContextual("from")&&!this.match(n.comma))return t.source=this.finishPlaceholder(e,"StringLiteral"),this.semicolon(),this.finishNode(t,"ImportDeclaration");const s=this.startNodeAtNode(e);if(s.local=e,this.finishNode(s,"ImportDefaultSpecifier"),t.specifiers.push(s),this.eat(n.comma)){this.maybeParseStarImportSpecifier(t)||this.parseNamedImportSpecifiers(t)}return this.expectContextual("from"),t.source=this.parseImportSource(),this.semicolon(),this.finishNode(t,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource(...arguments)}}},ct=Object.keys(pt),ut={sourceType:"script",sourceFilename:void 0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,plugins:[],strictMode:null,ranges:!1,tokens:!1,createParenthesizedExpressions:!1,errorRecovery:!1};class lt{constructor(){this.errors=[],this.potentialArrowAt=-1,this.noArrowAt=[],this.noArrowParamsConversionAt=[],this.inParameters=!1,this.maybeInArrowParameters=!1,this.maybeInAsyncArrowHead=!1,this.inPipeline=!1,this.inType=!1,this.noAnonFunctionType=!1,this.inPropertyName=!1,this.hasFlowComment=!1,this.isIterator=!1,this.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null},this.soloAwait=!1,this.inFSharpPipelineDirectBody=!1,this.labels=[],this.decoratorStack=[[]],this.yieldPos=-1,this.awaitPos=-1,this.comments=[],this.trailingComments=[],this.leadingComments=[],this.commentStack=[],this.commentPreviousNode=null,this.pos=0,this.lineStart=0,this.type=n.eof,this.value=null,this.start=0,this.end=0,this.lastTokEndLoc=null,this.lastTokStartLoc=null,this.lastTokStart=0,this.lastTokEnd=0,this.context=[x.braceStatement],this.exprAllowed=!0,this.containsEsc=!1,this.octalPositions=[],this.exportedIdentifiers=[],this.tokensLength=0}init(t){this.strict=!1!==t.strictMode&&"module"===t.sourceType,this.curLine=t.startLine,this.startLoc=this.endLoc=this.curPosition()}curPosition(){return new l(this.curLine,this.pos-this.lineStart)}clone(t){const e=new lt,s=Object.keys(this);for(let i=0,r=s.length;i<r;i++){const r=s[i];let a=this[r];!t&&Array.isArray(a)&&(a=a.slice()),e[r]=a}return e}}var dt=function(t){return t>=48&&t<=57};const mt=new Set(["g","m","s","i","y","u"]),ft={decBinOct:[46,66,69,79,95,98,101,111],hex:[46,88,95,120]},Dt={bin:[48,49]};Dt.oct=[...Dt.bin,50,51,52,53,54,55],Dt.dec=[...Dt.oct,56,57],Dt.hex=[...Dt.dec,65,66,67,68,69,70,97,98,99,100,101,102];class yt{constructor(t){this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new d(t.startLoc,t.endLoc)}}class xt{constructor(){this.shorthandAssign=-1,this.doubleProto=-1}}class gt{constructor(t,e,s){this.type="",this.start=e,this.end=0,this.loc=new d(s),t&&t.options.ranges&&(this.range=[e,0]),t&&t.filename&&(this.loc.filename=t.filename)}__clone(){const t=new gt,e=Object.keys(this);for(let s=0,i=e.length;s<i;s++){const i=e[s];"leadingComments"!==i&&"trailingComments"!==i&&"innerComments"!==i&&(t[i]=this[i])}return t}}const Pt=t=>"ParenthesizedExpression"===t.type?Pt(t.expression):t;const Et={kind:"loop"},Ct={kind:"switch"};class bt{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}}class Tt{constructor(t){this.stack=[],this.undefinedPrivateNames=new Map,this.raise=t}current(){return this.stack[this.stack.length-1]}enter(){this.stack.push(new bt)}exit(){const t=this.stack.pop(),e=this.current();for(let s=0,i=Array.from(t.undefinedPrivateNames);s<i.length;s++){const[t,r]=i[s];e?e.undefinedPrivateNames.has(t)||e.undefinedPrivateNames.set(t,r):this.raise(r,f.InvalidPrivateFieldResolution,t)}}declarePrivateName(t,e,s){const i=this.current();let r=i.privateNames.has(t);if(3&e){const s=r&&i.loneAccessors.get(t);if(s){const a=4&s,n=4&e;r=(3&s)===(3&e)||a!==n,r||i.loneAccessors.delete(t)}else r||i.loneAccessors.set(t,e)}r&&this.raise(s,f.PrivateNameRedeclaration,t),i.privateNames.add(t),i.undefinedPrivateNames.delete(t)}usePrivateName(t,e){let s;for(let e=0,i=this.stack;e<i.length;e++)if(s=i[e],s.privateNames.has(t))return;s?s.undefinedPrivateNames.set(t,e):this.raise(e,f.InvalidPrivateFieldResolution,t)}}class At extends class extends class extends class extends class extends class extends class extends class extends class extends class{constructor(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1}hasPlugin(t){return this.plugins.has(t)}getPluginOption(t,e){if(this.hasPlugin(t))return this.plugins.get(t)[e]}}{addComment(t){this.filename&&(t.loc.filename=this.filename),this.state.trailingComments.push(t),this.state.leadingComments.push(t)}adjustCommentsAfterTrailingComma(t,e,s){if(0===this.state.leadingComments.length)return;let i=null,r=e.length;for(;null===i&&r>0;)i=e[--r];if(null===i)return;for(let t=0;t<this.state.leadingComments.length;t++)this.state.leadingComments[t].end<this.state.commentPreviousNode.end&&(this.state.leadingComments.splice(t,1),t--);const a=[];for(let e=0;e<this.state.leadingComments.length;e++){const i=this.state.leadingComments[e];i.end<t.end?(a.push(i),s||(this.state.leadingComments.splice(e,1),e--)):(void 0===t.trailingComments&&(t.trailingComments=[]),t.trailingComments.push(i))}s&&(this.state.leadingComments=[]),a.length>0?i.trailingComments=a:void 0!==i.trailingComments&&(i.trailingComments=[])}processComment(t){if("Program"===t.type&&t.body.length>0)return;const e=this.state.commentStack;let s,i,r,a,n;if(this.state.trailingComments.length>0)this.state.trailingComments[0].start>=t.end?(r=this.state.trailingComments,this.state.trailingComments=[]):this.state.trailingComments.length=0;else if(e.length>0){const s=m(e);s.trailingComments&&s.trailingComments[0].start>=t.end&&(r=s.trailingComments,delete s.trailingComments)}for(e.length>0&&m(e).start>=t.start&&(s=e.pop());e.length>0&&m(e).start>=t.start;)i=e.pop();if(!i&&s&&(i=s),s)switch(t.type){case"ObjectExpression":this.adjustCommentsAfterTrailingComma(t,t.properties);break;case"ObjectPattern":this.adjustCommentsAfterTrailingComma(t,t.properties,!0);break;case"CallExpression":this.adjustCommentsAfterTrailingComma(t,t.arguments);break;case"ArrayExpression":this.adjustCommentsAfterTrailingComma(t,t.elements);break;case"ArrayPattern":this.adjustCommentsAfterTrailingComma(t,t.elements,!0)}else this.state.commentPreviousNode&&("ImportSpecifier"===this.state.commentPreviousNode.type&&"ImportSpecifier"!==t.type||"ExportSpecifier"===this.state.commentPreviousNode.type&&"ExportSpecifier"!==t.type)&&this.adjustCommentsAfterTrailingComma(t,[this.state.commentPreviousNode]);if(i){if(i.leadingComments)if(i!==t&&i.leadingComments.length>0&&m(i.leadingComments).end<=t.start)t.leadingComments=i.leadingComments,delete i.leadingComments;else for(a=i.leadingComments.length-2;a>=0;--a)if(i.leadingComments[a].end<=t.start){t.leadingComments=i.leadingComments.splice(0,a+1);break}}else if(this.state.leadingComments.length>0)if(m(this.state.leadingComments).end<=t.start){if(this.state.commentPreviousNode)for(n=0;n<this.state.leadingComments.length;n++)this.state.leadingComments[n].end<this.state.commentPreviousNode.end&&(this.state.leadingComments.splice(n,1),n--);this.state.leadingComments.length>0&&(t.leadingComments=this.state.leadingComments,this.state.leadingComments=[])}else{for(a=0;a<this.state.leadingComments.length&&!(this.state.leadingComments[a].end>t.start);a++);const e=this.state.leadingComments.slice(0,a);e.length&&(t.leadingComments=e),r=this.state.leadingComments.slice(a),0===r.length&&(r=null)}this.state.commentPreviousNode=t,r&&(r.length&&r[0].start>=t.start&&m(r).end<=t.end?t.innerComments=r:t.trailingComments=r),e.push(t)}}{getLocationForPosition(t){let e;return e=t===this.state.start?this.state.startLoc:t===this.state.lastTokStart?this.state.lastTokStartLoc:t===this.state.end?this.state.endLoc:t===this.state.lastTokEnd?this.state.lastTokEndLoc:function(t,e){let s,i=1,r=0;for(h.lastIndex=0;(s=h.exec(t))&&s.index<e;)i++,r=h.lastIndex;return new l(i,e-r)}(this.input,t),e}raise(t,e,...s){return this.raiseWithData(t,void 0,e,...s)}raiseWithData(t,e,s,...i){const r=this.getLocationForPosition(t),a=s.replace(/%(\d+)/g,(t,e)=>i[e])+" (".concat(r.line,":").concat(r.column,")");return this._raise(Object.assign({loc:r,pos:t},e),a)}_raise(t,e){const s=new SyntaxError(e);if(Object.assign(s,t),this.options.errorRecovery)return this.isLookahead||this.state.errors.push(s),s;throw s}}{constructor(t,e){super(),this.tokens=[],this.state=new lt,this.state.init(t),this.input=e,this.length=e.length,this.isLookahead=!1}pushToken(t){this.tokens.length=this.state.tokensLength,this.tokens.push(t),++this.state.tokensLength}next(){this.isLookahead||(this.checkKeywordEscapes(),this.options.tokens&&this.pushToken(new yt(this.state))),this.state.lastTokEnd=this.state.end,this.state.lastTokStart=this.state.start,this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()}eat(t){return!!this.match(t)&&(this.next(),!0)}match(t){return this.state.type===t}lookahead(){const t=this.state;this.state=t.clone(!0),this.isLookahead=!0,this.next(),this.isLookahead=!1;const e=this.state;return this.state=t,e}nextTokenStart(){const t=this.state.pos;return c.lastIndex=t,t+c.exec(this.input)[0].length}lookaheadCharCode(){return this.input.charCodeAt(this.nextTokenStart())}setStrict(t){if(this.state.strict=t,this.match(n.num)||this.match(n.string)){for(this.state.pos=this.state.start;this.state.pos<this.state.lineStart;)this.state.lineStart=this.input.lastIndexOf("\n",this.state.lineStart-2)+1,--this.state.curLine;this.nextToken()}}curContext(){return this.state.context[this.state.context.length-1]}nextToken(){const t=this.curContext();if(t&&t.preserveSpace||this.skipSpace(),this.state.octalPositions=[],this.state.start=this.state.pos,this.state.startLoc=this.state.curPosition(),this.state.pos>=this.length)return void this.finishToken(n.eof);const e=null==t?void 0:t.override;e?e(this):this.getTokenFromCode(this.input.codePointAt(this.state.pos))}pushComment(t,e,s,i,r,a){const n={type:t?"CommentBlock":"CommentLine",value:e,start:s,end:i,loc:new d(r,a)};this.options.tokens&&this.pushToken(n),this.state.comments.push(n),this.addComment(n)}skipBlockComment(){const t=this.state.curPosition(),e=this.state.pos,s=this.input.indexOf("*/",this.state.pos+2);if(-1===s)throw this.raise(e,f.UnterminatedComment);let i;for(this.state.pos=s+2,h.lastIndex=e;(i=h.exec(this.input))&&i.index<this.state.pos;)++this.state.curLine,this.state.lineStart=i.index+i[0].length;this.isLookahead||this.pushComment(!0,this.input.slice(e+2,s),e,this.state.pos,t,this.state.curPosition())}skipLineComment(t){const e=this.state.pos,s=this.state.curPosition();let i=this.input.charCodeAt(this.state.pos+=t);if(this.state.pos<this.length)for(;!p(i)&&++this.state.pos<this.length;)i=this.input.charCodeAt(this.state.pos);this.isLookahead||this.pushComment(!1,this.input.slice(e+t,this.state.pos),e,this.state.pos,s,this.state.curPosition())}skipSpace(){t:for(;this.state.pos<this.length;){const t=this.input.charCodeAt(this.state.pos);switch(t){case 32:case 160:case 9:++this.state.pos;break;case 13:10===this.input.charCodeAt(this.state.pos+1)&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break t}break;default:if(!u(t))break t;++this.state.pos}}}finishToken(t,e){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();const s=this.state.type;this.state.type=t,this.state.value=e,this.isLookahead||this.updateContext(s)}readToken_numberSign(){if(0===this.state.pos&&this.readToken_interpreter())return;const t=this.state.pos+1,e=this.input.charCodeAt(t);if(e>=48&&e<=57)throw this.raise(this.state.pos,f.UnexpectedDigitAfterHash);if(!this.hasPlugin("recordAndTuple")||123!==e&&91!==e){if(!this.hasPlugin("classPrivateProperties")&&!this.hasPlugin("classPrivateMethods")&&"smart"!==this.getPluginOption("pipelineOperator","proposal"))throw this.raise(this.state.pos,f.InvalidOrUnexpectedToken,"#");this.finishOp(n.hash,1)}else{if("hash"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(this.state.pos,123===e?f.RecordExpressionHashIncorrectStartSyntaxType:f.TupleExpressionHashIncorrectStartSyntaxType);123===e?this.finishToken(n.braceHashL):this.finishToken(n.bracketHashL),this.state.pos+=2}}readToken_dot(){const t=this.input.charCodeAt(this.state.pos+1);t>=48&&t<=57?this.readNumber(!0):46===t&&46===this.input.charCodeAt(this.state.pos+2)?(this.state.pos+=3,this.finishToken(n.ellipsis)):(++this.state.pos,this.finishToken(n.dot))}readToken_slash(){if(this.state.exprAllowed&&!this.state.inType)return++this.state.pos,void this.readRegexp();61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(n.assign,2):this.finishOp(n.slash,1)}readToken_interpreter(){if(0!==this.state.pos||this.length<2)return!1;let t=this.input.charCodeAt(this.state.pos+1);if(33!==t)return!1;const e=this.state.pos;for(this.state.pos+=1;!p(t)&&++this.state.pos<this.length;)t=this.input.charCodeAt(this.state.pos);const s=this.input.slice(e+2,this.state.pos);return this.finishToken(n.interpreterDirective,s),!0}readToken_mult_modulo(t){let e=42===t?n.star:n.modulo,s=1,i=this.input.charCodeAt(this.state.pos+1);const r=this.state.exprAllowed;42===t&&42===i&&(s++,i=this.input.charCodeAt(this.state.pos+2),e=n.exponent),61!==i||r||(s++,e=n.assign),this.finishOp(e,s)}readToken_pipe_amp(t){const e=this.input.charCodeAt(this.state.pos+1);if(e!==t){if(124===t){if(62===e)return void this.finishOp(n.pipeline,2);if(this.hasPlugin("recordAndTuple")&&125===e){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(this.state.pos,f.RecordExpressionBarIncorrectEndSyntaxType);return void this.finishOp(n.braceBarR,2)}if(this.hasPlugin("recordAndTuple")&&93===e){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(this.state.pos,f.TupleExpressionBarIncorrectEndSyntaxType);return void this.finishOp(n.bracketBarR,2)}}61!==e?this.finishOp(124===t?n.bitwiseOR:n.bitwiseAND,1):this.finishOp(n.assign,2)}else 61===this.input.charCodeAt(this.state.pos+2)?this.finishOp(n.assign,3):this.finishOp(124===t?n.logicalOR:n.logicalAND,2)}readToken_caret(){61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(n.assign,2):this.finishOp(n.bitwiseXOR,1)}readToken_plus_min(t){const e=this.input.charCodeAt(this.state.pos+1);if(e===t)return 45!==e||this.inModule||62!==this.input.charCodeAt(this.state.pos+2)||0!==this.state.lastTokEnd&&!o.test(this.input.slice(this.state.lastTokEnd,this.state.pos))?void this.finishOp(n.incDec,2):(this.skipLineComment(3),this.skipSpace(),void this.nextToken());61===e?this.finishOp(n.assign,2):this.finishOp(n.plusMin,1)}readToken_lt_gt(t){const e=this.input.charCodeAt(this.state.pos+1);let s=1;return e===t?(s=62===t&&62===this.input.charCodeAt(this.state.pos+2)?3:2,61===this.input.charCodeAt(this.state.pos+s)?void this.finishOp(n.assign,s+1):void this.finishOp(n.bitShift,s)):33!==e||60!==t||this.inModule||45!==this.input.charCodeAt(this.state.pos+2)||45!==this.input.charCodeAt(this.state.pos+3)?(61===e&&(s=2),void this.finishOp(n.relational,s)):(this.skipLineComment(4),this.skipSpace(),void this.nextToken())}readToken_eq_excl(t){const e=this.input.charCodeAt(this.state.pos+1);if(61!==e)return 61===t&&62===e?(this.state.pos+=2,void this.finishToken(n.arrow)):void this.finishOp(61===t?n.eq:n.bang,1);this.finishOp(n.equality,61===this.input.charCodeAt(this.state.pos+2)?3:2)}readToken_question(){const t=this.input.charCodeAt(this.state.pos+1),e=this.input.charCodeAt(this.state.pos+2);63!==t||this.state.inType?46!==t||e>=48&&e<=57?(++this.state.pos,this.finishToken(n.question)):(this.state.pos+=2,this.finishToken(n.questionDot)):61===e?this.finishOp(n.assign,3):this.finishOp(n.nullishCoalescing,2)}getTokenFromCode(t){switch(t){case 46:return void this.readToken_dot();case 40:return++this.state.pos,void this.finishToken(n.parenL);case 41:return++this.state.pos,void this.finishToken(n.parenR);case 59:return++this.state.pos,void this.finishToken(n.semi);case 44:return++this.state.pos,void this.finishToken(n.comma);case 91:if(this.hasPlugin("recordAndTuple")&&124===this.input.charCodeAt(this.state.pos+1)){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(this.state.pos,f.TupleExpressionBarIncorrectStartSyntaxType);this.finishToken(n.bracketBarL),this.state.pos+=2}else++this.state.pos,this.finishToken(n.bracketL);return;case 93:return++this.state.pos,void this.finishToken(n.bracketR);case 123:if(this.hasPlugin("recordAndTuple")&&124===this.input.charCodeAt(this.state.pos+1)){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(this.state.pos,f.RecordExpressionBarIncorrectStartSyntaxType);this.finishToken(n.braceBarL),this.state.pos+=2}else++this.state.pos,this.finishToken(n.braceL);return;case 125:return++this.state.pos,void this.finishToken(n.braceR);case 58:return void(this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(n.doubleColon,2):(++this.state.pos,this.finishToken(n.colon)));case 63:return void this.readToken_question();case 96:return++this.state.pos,void this.finishToken(n.backQuote);case 48:{const t=this.input.charCodeAt(this.state.pos+1);if(120===t||88===t)return void this.readRadixNumber(16);if(111===t||79===t)return void this.readRadixNumber(8);if(98===t||66===t)return void this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return void this.readNumber(!1);case 34:case 39:return void this.readString(t);case 47:return void this.readToken_slash();case 37:case 42:return void this.readToken_mult_modulo(t);case 124:case 38:return void this.readToken_pipe_amp(t);case 94:return void this.readToken_caret();case 43:case 45:return void this.readToken_plus_min(t);case 60:case 62:return void this.readToken_lt_gt(t);case 61:case 33:return void this.readToken_eq_excl(t);case 126:return void this.finishOp(n.tilde,1);case 64:return++this.state.pos,void this.finishToken(n.at);case 35:return void this.readToken_numberSign();case 92:return void this.readWord();default:if(w(t))return void this.readWord()}throw this.raise(this.state.pos,f.InvalidOrUnexpectedToken,String.fromCodePoint(t))}finishOp(t,e){const s=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(t,s)}readRegexp(){const t=this.state.pos;let e,s;for(;;){if(this.state.pos>=this.length)throw this.raise(t,f.UnterminatedRegExp);const i=this.input.charAt(this.state.pos);if(o.test(i))throw this.raise(t,f.UnterminatedRegExp);if(e)e=!1;else{if("["===i)s=!0;else if("]"===i&&s)s=!1;else if("/"===i&&!s)break;e="\\"===i}++this.state.pos}const i=this.input.slice(t,this.state.pos);++this.state.pos;let r="";for(;this.state.pos<this.length;){const t=this.input[this.state.pos],e=this.input.codePointAt(this.state.pos);if(mt.has(t))r.indexOf(t)>-1&&this.raise(this.state.pos+1,f.DuplicateRegExpFlags);else{if(!S(e)&&92!==e)break;this.raise(this.state.pos+1,f.MalformedRegExpFlags)}++this.state.pos,r+=t}this.finishToken(n.regexp,{pattern:i,flags:r})}readInt(t,e,s,i=!0){const r=this.state.pos,a=16===t?ft.hex:ft.decBinOct,n=16===t?Dt.hex:10===t?Dt.dec:8===t?Dt.oct:Dt.bin;let o=!1,h=0;for(let r=0,p=null==e?1/0:e;r<p;++r){const e=this.input.charCodeAt(this.state.pos);let p;if(this.hasPlugin("numericSeparator")&&95===e){const t=this.input.charCodeAt(this.state.pos-1),e=this.input.charCodeAt(this.state.pos+1);-1===n.indexOf(e)?this.raise(this.state.pos,f.UnexpectedNumericSeparator):(a.indexOf(t)>-1||a.indexOf(e)>-1||Number.isNaN(e))&&this.raise(this.state.pos,f.UnexpectedNumericSeparator),i||this.raise(this.state.pos,f.NumericSeparatorInEscapeSequence),++this.state.pos}else{if(p=e>=97?e-97+10:e>=65?e-65+10:dt(e)?e-48:1/0,p>=t)if(this.options.errorRecovery&&p<=9)p=0,this.raise(this.state.start+r+2,f.InvalidDigit,t);else{if(!s)break;p=0,o=!0}++this.state.pos,h=h*t+p}}return this.state.pos===r||null!=e&&this.state.pos-r!==e||o?null:h}readRadixNumber(t){const e=this.state.pos;let s=!1;this.state.pos+=2;const i=this.readInt(t);if(null==i&&this.raise(this.state.start+2,f.InvalidDigit,t),110===this.input.charCodeAt(this.state.pos)&&(++this.state.pos,s=!0),w(this.input.codePointAt(this.state.pos)))throw this.raise(this.state.pos,f.NumberIdentifier);if(s){const t=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");this.finishToken(n.bigint,t)}else this.finishToken(n.num,i)}readNumber(t){const e=this.state.pos;let s=!1,i=!1,r=!1;t||null!==this.readInt(10)||this.raise(e,f.InvalidNumber);let a=this.state.pos-e>=2&&48===this.input.charCodeAt(e);a&&(this.state.strict&&this.raise(e,f.StrictOctalLiteral),/[89]/.test(this.input.slice(e,this.state.pos))&&(a=!1,r=!0));let o=this.input.charCodeAt(this.state.pos);if(46!==o||a||(++this.state.pos,this.readInt(10),s=!0,o=this.input.charCodeAt(this.state.pos)),69!==o&&101!==o||a||(o=this.input.charCodeAt(++this.state.pos),43!==o&&45!==o||++this.state.pos,null===this.readInt(10)&&this.raise(e,"Invalid number"),s=!0,o=this.input.charCodeAt(this.state.pos)),this.hasPlugin("numericSeparator")&&(a||r)){const t=this.input.slice(e,this.state.pos).indexOf("_");t>0&&this.raise(t+e,f.ZeroDigitNumericSeparator)}if(110===o&&((s||a||r)&&this.raise(e,"Invalid BigIntLiteral"),++this.state.pos,i=!0),w(this.input.codePointAt(this.state.pos)))throw this.raise(this.state.pos,f.NumberIdentifier);const h=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");if(i)return void this.finishToken(n.bigint,h);const p=a?parseInt(h,8):parseFloat(h);this.finishToken(n.num,p)}readCodePoint(t){let e;if(123===this.input.charCodeAt(this.state.pos)){const s=++this.state.pos;if(e=this.readHexChar(this.input.indexOf("}",this.state.pos)-this.state.pos,!0,t),++this.state.pos,null!==e&&e>1114111){if(!t)return null;this.raise(s,f.InvalidCodePoint)}}else e=this.readHexChar(4,!1,t);return e}readString(t){let e="",s=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(this.state.start,f.UnterminatedString);const i=this.input.charCodeAt(this.state.pos);if(i===t)break;if(92===i)e+=this.input.slice(s,this.state.pos),e+=this.readEscapedChar(!1),s=this.state.pos;else if(8232===i||8233===i)++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;else{if(p(i))throw this.raise(this.state.start,f.UnterminatedString);++this.state.pos}}e+=this.input.slice(s,this.state.pos++),this.finishToken(n.string,e)}readTmplToken(){let t="",e=this.state.pos,s=!1;for(;;){if(this.state.pos>=this.length)throw this.raise(this.state.start,f.UnterminatedTemplate);const i=this.input.charCodeAt(this.state.pos);if(96===i||36===i&&123===this.input.charCodeAt(this.state.pos+1))return this.state.pos===this.state.start&&this.match(n.template)?36===i?(this.state.pos+=2,void this.finishToken(n.dollarBraceL)):(++this.state.pos,void this.finishToken(n.backQuote)):(t+=this.input.slice(e,this.state.pos),void this.finishToken(n.template,s?null:t));if(92===i){t+=this.input.slice(e,this.state.pos);const i=this.readEscapedChar(!0);null===i?s=!0:t+=i,e=this.state.pos}else if(p(i)){switch(t+=this.input.slice(e,this.state.pos),++this.state.pos,i){case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:t+="\n";break;default:t+=String.fromCharCode(i)}++this.state.curLine,this.state.lineStart=this.state.pos,e=this.state.pos}else++this.state.pos}}readEscapedChar(t){const e=!t,s=this.input.charCodeAt(++this.state.pos);switch(++this.state.pos,s){case 110:return"\n";case 114:return"\r";case 120:{const t=this.readHexChar(2,!1,e);return null===t?null:String.fromCharCode(t)}case 117:{const t=this.readCodePoint(e);return null===t?null:String.fromCodePoint(t)}case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:this.state.lineStart=this.state.pos,++this.state.curLine;case 8232:case 8233:return"";case 56:case 57:if(t)return null;default:if(s>=48&&s<=55){const e=this.state.pos-1;let s=this.input.substr(this.state.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(s,8);i>255&&(s=s.slice(0,-1),i=parseInt(s,8)),this.state.pos+=s.length-1;const r=this.input.charCodeAt(this.state.pos);if("0"!==s||56===r||57===r){if(t)return null;this.state.strict?this.raise(e,f.StrictOctalLiteral):this.state.octalPositions.push(e)}return String.fromCharCode(i)}return String.fromCharCode(s)}}readHexChar(t,e,s){const i=this.state.pos,r=this.readInt(16,t,e,!1);return null===r&&(s?this.raise(i,f.InvalidEscapeSequence):this.state.pos=i-1),r}readWord1(){let t="";this.state.containsEsc=!1;const e=this.state.pos;let s=this.state.pos;for(;this.state.pos<this.length;){const i=this.input.codePointAt(this.state.pos);if(S(i))this.state.pos+=i<=65535?1:2;else if(this.state.isIterator&&64===i)++this.state.pos;else{if(92!==i)break;{this.state.containsEsc=!0,t+=this.input.slice(s,this.state.pos);const i=this.state.pos,r=this.state.pos===e?w:S;if(117!==this.input.charCodeAt(++this.state.pos)){this.raise(this.state.pos,f.MissingUnicodeEscape);continue}++this.state.pos;const a=this.readCodePoint(!0);null!==a&&(r(a)||this.raise(i,f.EscapedCharNotAnIdentifier),t+=String.fromCodePoint(a)),s=this.state.pos}}}return t+this.input.slice(s,this.state.pos)}isIterator(t){return"@@iterator"===t||"@@asyncIterator"===t}readWord(){const t=this.readWord1(),e=i.get(t)||n.name;!this.state.isIterator||this.isIterator(t)&&this.state.inType||this.raise(this.state.pos,f.InvalidIdentifier,t),this.finishToken(e,t)}checkKeywordEscapes(){const t=this.state.type.keyword;t&&this.state.containsEsc&&this.raise(this.state.start,f.InvalidEscapedReservedWord,t)}braceIsBlock(t){const e=this.curContext();return e===x.functionExpression||e===x.functionStatement||(t!==n.colon||e!==x.braceStatement&&e!==x.braceExpression?t===n._return||t===n.name&&this.state.exprAllowed?o.test(this.input.slice(this.state.lastTokEnd,this.state.start)):t===n._else||t===n.semi||t===n.eof||t===n.parenR||t===n.arrow||(t===n.braceL?e===x.braceStatement:t!==n._var&&t!==n._const&&t!==n.name&&(t===n.relational||!this.state.exprAllowed)):!e.isExpr)}updateContext(t){const e=this.state.type;let s;!e.keyword||t!==n.dot&&t!==n.questionDot?(s=e.updateContext)?s.call(this,t):this.state.exprAllowed=e.beforeExpr:this.state.exprAllowed=!1}}{addExtra(t,e,s){if(!t)return;(t.extra=t.extra||{})[e]=s}isRelational(t){return this.match(n.relational)&&this.state.value===t}isLookaheadRelational(t){const e=this.nextTokenStart();if(this.input.charAt(e)===t){if(e+1===this.input.length)return!0;const s=this.input.charCodeAt(e+1);return s!==t.charCodeAt(0)&&61!==s}return!1}expectRelational(t){this.isRelational(t)?this.next():this.unexpected(null,n.relational)}isContextual(t){return this.match(n.name)&&this.state.value===t&&!this.state.containsEsc}isUnparsedContextual(t,e){const s=t+e.length;return this.input.slice(t,s)===e&&(s===this.input.length||!S(this.input.charCodeAt(s)))}isLookaheadContextual(t){const e=this.nextTokenStart();return this.isUnparsedContextual(e,t)}eatContextual(t){return this.isContextual(t)&&this.eat(n.name)}expectContextual(t,e){this.eatContextual(t)||this.unexpected(null,e)}canInsertSemicolon(){return this.match(n.eof)||this.match(n.braceR)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return o.test(this.input.slice(this.state.lastTokEnd,this.state.start))}isLineTerminator(){return this.eat(n.semi)||this.canInsertSemicolon()}semicolon(){this.isLineTerminator()||this.unexpected(null,n.semi)}expect(t,e){this.eat(t)||this.unexpected(e,t)}assertNoSpace(t="Unexpected space."){this.state.start>this.state.lastTokEnd&&this.raise(this.state.lastTokEnd,t)}unexpected(t,e="Unexpected token"){throw"string"!=typeof e&&(e='Unexpected token, expected "'.concat(e.label,'"')),this.raise(null!=t?t:this.state.start,e)}expectPlugin(t,e){if(!this.hasPlugin(t))throw this.raiseWithData(null!=e?e:this.state.start,{missingPlugin:[t]},"This experimental syntax requires enabling the parser plugin: '".concat(t,"'"));return!0}expectOnePlugin(t,e){if(!t.some(t=>this.hasPlugin(t)))throw this.raiseWithData(null!=e?e:this.state.start,{missingPlugin:t},"This experimental syntax requires enabling one of the following parser plugin(s): '".concat(t.join(", "),"'"))}checkYieldAwaitInDefaultParams(){-1!==this.state.yieldPos&&(-1===this.state.awaitPos||this.state.yieldPos<this.state.awaitPos)&&this.raise(this.state.yieldPos,"Yield cannot be used as name inside a generator function"),-1!==this.state.awaitPos&&this.raise(this.state.awaitPos,"Await cannot be used as name inside an async function")}tryParse(t,e=this.state.clone()){const s={node:null};try{const i=t((t=null)=>{throw s.node=t,s});if(this.state.errors.length>e.errors.length){const t=this.state;return this.state=e,{node:i,error:t.errors[e.errors.length],thrown:!1,aborted:!1,failState:t}}return{node:i,error:null,thrown:!1,aborted:!1,failState:null}}catch(t){const i=this.state;if(this.state=e,t instanceof SyntaxError)return{node:null,error:t,thrown:!0,aborted:!1,failState:i};if(t===s)return{node:s.node,error:null,thrown:!1,aborted:!0,failState:i};throw t}}checkExpressionErrors(t,e){if(!t)return!1;const{shorthandAssign:s,doubleProto:i}=t;if(!e)return s>=0||i>=0;s>=0&&this.unexpected(s),i>=0&&this.raise(i,f.DuplicateProto)}}{startNode(){return new gt(this,this.state.start,this.state.startLoc)}startNodeAt(t,e){return new gt(this,t,e)}startNodeAtNode(t){return this.startNodeAt(t.start,t.loc.start)}finishNode(t,e){return this.finishNodeAt(t,e,this.state.lastTokEnd,this.state.lastTokEndLoc)}finishNodeAt(t,e,s,i){return t.type=e,t.end=s,t.loc.end=i,this.options.ranges&&(t.range[1]=s),this.processComment(t),t}resetStartLocation(t,e,s){t.start=e,t.loc.start=s,this.options.ranges&&(t.range[0]=e)}resetEndLocation(t,e=this.state.lastTokEnd,s=this.state.lastTokEndLoc){t.end=e,t.loc.end=s,this.options.ranges&&(t.range[1]=e)}resetStartLocationFromNode(t,e){this.resetStartLocation(t,e.start,e.loc.start)}}{toAssignable(t){var e,s;let i=void 0;switch(("ParenthesizedExpression"===t.type||(null==(e=t.extra)?void 0:e.parenthesized))&&(i=Pt(t),"Identifier"!==i.type&&"MemberExpression"!==i.type&&this.raise(t.start,f.InvalidParenthesizedAssignment)),t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":t.type="ObjectPattern";for(let e=0,s=t.properties.length,i=s-1;e<s;e++){var r;const s=t.properties[e],a=e===i;this.toAssignableObjectExpressionProp(s,a),a&&"RestElement"===s.type&&(null==(r=t.extra)?void 0:r.trailingComma)&&this.raiseRestNotLast(t.extra.trailingComma)}break;case"ObjectProperty":this.toAssignable(t.value);break;case"SpreadElement":{this.checkToRestConversion(t),t.type="RestElement";const e=t.argument;this.toAssignable(e);break}case"ArrayExpression":t.type="ArrayPattern",this.toAssignableList(t.elements,null==(s=t.extra)?void 0:s.trailingComma);break;case"AssignmentExpression":"="!==t.operator&&this.raise(t.left.end,f.MissingEqInAssignment),t.type="AssignmentPattern",delete t.operator,this.toAssignable(t.left);break;case"ParenthesizedExpression":this.toAssignable(i)}return t}toAssignableObjectExpressionProp(t,e){if("ObjectMethod"===t.type){const e="get"===t.kind||"set"===t.kind?f.PatternHasAccessor:f.PatternHasMethod;this.raise(t.key.start,e)}else"SpreadElement"!==t.type||e?this.toAssignable(t):this.raiseRestNotLast(t.start)}toAssignableList(t,e){let s=t.length;if(s){const i=t[s-1];if(i&&"RestElement"===i.type)--s;else if(i&&"SpreadElement"===i.type){i.type="RestElement";const t=i.argument;this.toAssignable(t),"Identifier"!==t.type&&"MemberExpression"!==t.type&&"ArrayPattern"!==t.type&&"ObjectPattern"!==t.type&&this.unexpected(t.start),e&&this.raiseTrailingCommaAfterRest(e),--s}}for(let e=0;e<s;e++){const s=t[e];s&&(this.toAssignable(s),"RestElement"===s.type&&this.raiseRestNotLast(s.start))}return t}toReferencedList(t,e){return t}toReferencedListDeep(t,e){this.toReferencedList(t,e);for(let e=0;e<t.length;e++){const s=t[e];s&&"ArrayExpression"===s.type&&this.toReferencedListDeep(s.elements)}}parseSpread(t,e){const s=this.startNode();return this.next(),s.argument=this.parseMaybeAssign(!1,t,void 0,e),this.finishNode(s,"SpreadElement")}parseRestBinding(){const t=this.startNode();return this.next(),t.argument=this.parseBindingAtom(),this.finishNode(t,"RestElement")}parseBindingAtom(){switch(this.state.type){case n.bracketL:{const t=this.startNode();return this.next(),t.elements=this.parseBindingList(n.bracketR,93,!0),this.finishNode(t,"ArrayPattern")}case n.braceL:return this.parseObj(n.braceR,!0)}return this.parseIdentifier()}parseBindingList(t,e,s,i){const r=[];let a=!0;for(;!this.eat(t);)if(a?a=!1:this.expect(n.comma),s&&this.match(n.comma))r.push(null);else{if(this.eat(t))break;if(this.match(n.ellipsis)){r.push(this.parseAssignableListItemTypes(this.parseRestBinding())),this.checkCommaAfterRest(e),this.expect(t);break}{const t=[];for(this.match(n.at)&&this.hasPlugin("decorators")&&this.raise(this.state.start,f.UnsupportedParameterDecorator);this.match(n.at);)t.push(this.parseDecorator());r.push(this.parseAssignableListItem(i,t))}}return r}parseAssignableListItem(t,e){const s=this.parseMaybeDefault();this.parseAssignableListItemTypes(s);const i=this.parseMaybeDefault(s.start,s.loc.start,s);return e.length&&(s.decorators=e),i}parseAssignableListItemTypes(t){return t}parseMaybeDefault(t,e,s){if(e=e||this.state.startLoc,t=t||this.state.start,s=s||this.parseBindingAtom(),!this.eat(n.eq))return s;const i=this.startNodeAt(t,e);return i.left=s,i.right=this.parseMaybeAssign(),this.finishNode(i,"AssignmentPattern")}checkLVal(t,e=64,s,i,r,a=!1){switch(t.type){case"Identifier":if(this.state.strict&&(a?O(t.name,this.inModule):M(t.name))&&this.raise(t.start,64===e?f.StrictEvalArguments:f.StrictEvalArgumentsBinding,t.name),s){const e="_".concat(t.name);s[e]?this.raise(t.start,f.ParamDupe):s[e]=!0}r&&"let"===t.name&&this.raise(t.start,f.LetInLexicalBinding),64&e||this.scope.declareName(t.name,e,t.start);break;case"MemberExpression":64!==e&&this.raise(t.start,f.InvalidPropertyBindingPattern);break;case"ObjectPattern":for(let i=0,a=t.properties;i<a.length;i++){let t=a[i];if("ObjectProperty"===t.type)t=t.value;else if("ObjectMethod"===t.type)continue;this.checkLVal(t,e,s,"object destructuring pattern",r)}break;case"ArrayPattern":for(let i=0,a=t.elements;i<a.length;i++){const t=a[i];t&&this.checkLVal(t,e,s,"array destructuring pattern",r)}break;case"AssignmentPattern":this.checkLVal(t.left,e,s,"assignment pattern");break;case"RestElement":this.checkLVal(t.argument,e,s,"rest element");break;case"ParenthesizedExpression":this.checkLVal(t.expression,e,s,"parenthesized expression");break;default:this.raise(t.start,64===e?f.InvalidLhs:f.InvalidLhsBinding,i)}}checkToRestConversion(t){"Identifier"!==t.argument.type&&"MemberExpression"!==t.argument.type&&this.raise(t.argument.start,f.InvalidRestAssignmentPattern)}checkCommaAfterRest(t){this.match(n.comma)&&(this.lookaheadCharCode()===t?this.raiseTrailingCommaAfterRest(this.state.start):this.raiseRestNotLast(this.state.start))}raiseRestNotLast(t){throw this.raise(t,f.ElementAfterRest)}raiseTrailingCommaAfterRest(t){this.raise(t,f.RestTrailingComma)}}{checkDuplicatedProto(t,e,s){if("SpreadElement"===t.type||t.computed||t.kind||t.shorthand)return;const i=t.key;"__proto__"===("Identifier"===i.type?i.name:String(i.value))&&(e.used&&(s?-1===s.doubleProto&&(s.doubleProto=i.start):this.raise(i.start,f.DuplicateProto)),e.used=!0)}getExpression(){let t=0;this.hasPlugin("topLevelAwait")&&this.inModule&&(t|=2),this.scope.enter(1),this.prodParam.enter(t),this.nextToken();const e=this.parseExpression();return this.match(n.eof)||this.unexpected(),e.comments=this.state.comments,e.errors=this.state.errors,e}parseExpression(t,e){const s=this.state.start,i=this.state.startLoc,r=this.parseMaybeAssign(t,e);if(this.match(n.comma)){const a=this.startNodeAt(s,i);for(a.expressions=[r];this.eat(n.comma);)a.expressions.push(this.parseMaybeAssign(t,e));return this.toReferencedList(a.expressions),this.finishNode(a,"SequenceExpression")}return r}parseMaybeAssign(t,e,s,i){const r=this.state.start,a=this.state.startLoc;if(this.isContextual("yield")){if(this.prodParam.hasYield){let e=this.parseYield(t);return s&&(e=s.call(this,e,r,a)),e}this.state.exprAllowed=!1}let o;e?o=!1:(e=new xt,o=!0),(this.match(n.parenL)||this.match(n.name))&&(this.state.potentialArrowAt=this.state.start);let h=this.parseMaybeConditional(t,e,i);if(s&&(h=s.call(this,h,r,a)),this.state.type.isAssign){const s=this.startNodeAt(r,a),i=this.state.value;return s.operator=i,"??="===i&&this.expectPlugin("logicalAssignment"),"||="!==i&&"&&="!==i||this.expectPlugin("logicalAssignment"),this.match(n.eq)?(s.left=this.toAssignable(h),e.doubleProto=-1):s.left=h,e.shorthandAssign>=s.left.start&&(e.shorthandAssign=-1),this.checkLVal(h,void 0,void 0,"assignment expression"),this.next(),s.right=this.parseMaybeAssign(t),this.finishNode(s,"AssignmentExpression")}return o&&this.checkExpressionErrors(e,!0),h}parseMaybeConditional(t,e,s){const i=this.state.start,r=this.state.startLoc,a=this.state.potentialArrowAt,n=this.parseExprOps(t,e);return"ArrowFunctionExpression"===n.type&&n.start===a?n:this.checkExpressionErrors(e,!1)?n:this.parseConditional(n,t,i,r,s)}parseConditional(t,e,s,i,r){if(this.eat(n.question)){const r=this.startNodeAt(s,i);return r.test=t,r.consequent=this.parseMaybeAssign(),this.expect(n.colon),r.alternate=this.parseMaybeAssign(e),this.finishNode(r,"ConditionalExpression")}return t}parseExprOps(t,e){const s=this.state.start,i=this.state.startLoc,r=this.state.potentialArrowAt,a=this.parseMaybeUnary(e);return"ArrowFunctionExpression"===a.type&&a.start===r?a:this.checkExpressionErrors(e,!1)?a:this.parseExprOp(a,s,i,-1,t)}parseExprOp(t,e,s,i,r){let a=this.state.type.binop;if(!(null==a||r&&this.match(n._in))&&a>i){const o=this.state.value;if("|>"===o&&this.state.inFSharpPipelineDirectBody)return t;const h=this.startNodeAt(e,s);h.left=t,h.operator=o,"**"!==o||"UnaryExpression"!==t.type||!this.options.createParenthesizedExpressions&&t.extra&&t.extra.parenthesized||this.raise(t.argument.start,f.UnexpectedTokenUnaryExponentiation);const p=this.state.type,c=p===n.logicalOR||p===n.logicalAND,u=p===n.nullishCoalescing;if(p===n.pipeline?(this.expectPlugin("pipelineOperator"),this.state.inPipeline=!0,this.checkPipelineAtInfixOperator(t,e)):u&&(a=n.logicalAND.binop),this.next(),p===n.pipeline&&"minimal"===this.getPluginOption("pipelineOperator","proposal")&&this.match(n.name)&&"await"===this.state.value&&this.prodParam.hasAwait)throw this.raise(this.state.start,f.UnexpectedAwaitAfterPipelineBody);h.right=this.parseExprOpRightExpr(p,a,r),this.finishNode(h,c||u?"LogicalExpression":"BinaryExpression");const l=this.state.type;if(u&&(l===n.logicalOR||l===n.logicalAND)||c&&l===n.nullishCoalescing)throw this.raise(this.state.start,f.MixingCoalesceWithLogical);return this.parseExprOp(h,e,s,i,r)}return t}parseExprOpRightExpr(t,e,s){const i=this.state.start,r=this.state.startLoc;switch(t){case n.pipeline:switch(this.getPluginOption("pipelineOperator","proposal")){case"smart":return this.withTopicPermittingContext(()=>this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(t,e,s),i,r));case"fsharp":return this.withSoloAwaitPermittingContext(()=>this.parseFSharpPipelineBody(e,s))}default:return this.parseExprOpBaseRightExpr(t,e,s)}}parseExprOpBaseRightExpr(t,e,s){const i=this.state.start,r=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnary(),i,r,t.rightAssociative?e-1:e,s)}parseMaybeUnary(t){if(this.isContextual("await")&&this.isAwaitAllowed())return this.parseAwait();if(this.state.type.prefix){const e=this.startNode(),s=this.match(n.incDec);if(e.operator=this.state.value,e.prefix=!0,"throw"===e.operator&&this.expectPlugin("throwExpressions"),this.next(),e.argument=this.parseMaybeUnary(),this.checkExpressionErrors(t,!0),s)this.checkLVal(e.argument,void 0,void 0,"prefix operation");else if(this.state.strict&&"delete"===e.operator){const t=e.argument;"Identifier"===t.type?this.raise(e.start,f.StrictDelete):"MemberExpression"===t.type&&"PrivateName"===t.property.type&&this.raise(e.start,f.DeletePrivateField)}return this.finishNode(e,s?"UpdateExpression":"UnaryExpression")}const e=this.state.start,s=this.state.startLoc;let i=this.parseExprSubscripts(t);if(this.checkExpressionErrors(t,!1))return i;for(;this.state.type.postfix&&!this.canInsertSemicolon();){const t=this.startNodeAt(e,s);t.operator=this.state.value,t.prefix=!1,t.argument=i,this.checkLVal(i,void 0,void 0,"postfix operation"),this.next(),i=this.finishNode(t,"UpdateExpression")}return i}parseExprSubscripts(t){const e=this.state.start,s=this.state.startLoc,i=this.state.potentialArrowAt,r=this.parseExprAtom(t);return"ArrowFunctionExpression"===r.type&&r.start===i?r:this.parseSubscripts(r,e,s)}parseSubscripts(t,e,s,i){const r={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(t),stop:!1};do{const a=this.state.maybeInAsyncArrowHead;r.maybeAsyncArrow&&(this.state.maybeInAsyncArrowHead=!0),t=this.parseSubscript(t,e,s,i,r),r.maybeAsyncArrow=!1,this.state.maybeInAsyncArrowHead=a}while(!r.stop);return t}parseSubscript(t,e,s,i,r){if(!i&&this.eat(n.doubleColon)){const a=this.startNodeAt(e,s);return a.object=t,a.callee=this.parseNoCallExpr(),r.stop=!0,this.parseSubscripts(this.finishNode(a,"BindExpression"),e,s,i)}let a=!1;if(this.match(n.questionDot)){if(r.optionalChainMember=a=!0,i&&40===this.lookaheadCharCode())return r.stop=!0,t;this.next()}const o=this.eat(n.bracketL);if(a&&!this.match(n.parenL)&&!this.match(n.backQuote)||o||this.eat(n.dot)){const i=this.startNodeAt(e,s);return i.object=t,i.property=o?this.parseExpression():a?this.parseIdentifier(!0):this.parseMaybePrivateName(!0),i.computed=o,"PrivateName"===i.property.type&&("Super"===i.object.type&&this.raise(e,f.SuperPrivateField),this.classScope.usePrivateName(i.property.id.name,i.property.start)),o&&this.expect(n.bracketR),r.optionalChainMember?(i.optional=a,this.finishNode(i,"OptionalMemberExpression")):this.finishNode(i,"MemberExpression")}if(!i&&this.match(n.parenL)){const i=this.state.maybeInArrowParameters,o=this.state.yieldPos,h=this.state.awaitPos;this.state.maybeInArrowParameters=!0,this.state.yieldPos=-1,this.state.awaitPos=-1,this.next();let p=this.startNodeAt(e,s);return p.callee=t,a?(p.optional=!0,p.arguments=this.parseCallExpressionArguments(n.parenR,!1)):p.arguments=this.parseCallExpressionArguments(n.parenR,r.maybeAsyncArrow,"Import"===t.type,"Super"!==t.type,p),this.finishCallExpression(p,r.optionalChainMember),r.maybeAsyncArrow&&this.shouldParseAsyncArrow()&&!a?(r.stop=!0,p=this.parseAsyncArrowFromCallExpression(this.startNodeAt(e,s),p),this.checkYieldAwaitInDefaultParams(),this.state.yieldPos=o,this.state.awaitPos=h):(this.toReferencedListDeep(p.arguments),-1!==o&&(this.state.yieldPos=o),(this.isAwaitAllowed()||i)&&-1===h||(this.state.awaitPos=h)),this.state.maybeInArrowParameters=i,p}return this.match(n.backQuote)?this.parseTaggedTemplateExpression(e,s,t,r):(r.stop=!0,t)}parseTaggedTemplateExpression(t,e,s,i,r){const a=this.startNodeAt(t,e);return a.tag=s,a.quasi=this.parseTemplate(!0),r&&(a.typeParameters=r),i.optionalChainMember&&this.raise(t,f.OptionalChainingNoTemplate),this.finishNode(a,"TaggedTemplateExpression")}atPossibleAsyncArrow(t){return"Identifier"===t.type&&"async"===t.name&&this.state.lastTokEnd===t.end&&!this.canInsertSemicolon()&&t.end-t.start==5&&t.start===this.state.potentialArrowAt}finishCallExpression(t,e){if("Import"===t.callee.type)if(1!==t.arguments.length)this.raise(t.start,f.ImportCallArity);else{const e=t.arguments[0];e&&"SpreadElement"===e.type&&this.raise(e.start,f.ImportCallSpreadArgument)}return this.finishNode(t,e?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(t,e,s,i,r){const a=[];let o,h=!0;const p=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(t);){if(h)h=!1;else if(this.expect(n.comma),this.match(t)){s&&this.raise(this.state.lastTokStart,f.ImportCallArgumentTrailingComma),r&&this.addExtra(r,"trailingComma",this.state.lastTokStart),this.next();break}this.match(n.parenL)&&!o&&(o=this.state.start),a.push(this.parseExprListItem(!1,e?new xt:void 0,e?{start:0}:void 0,i))}return e&&o&&this.shouldParseAsyncArrow()&&this.unexpected(),this.state.inFSharpPipelineDirectBody=p,a}shouldParseAsyncArrow(){return this.match(n.arrow)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(t,e){var s;return this.expect(n.arrow),this.parseArrowExpression(t,e.arguments,!0,null==(s=e.extra)?void 0:s.trailingComma),t}parseNoCallExpr(){const t=this.state.start,e=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,e,!0)}parseExprAtom(t){this.state.type===n.slash&&this.readRegexp();const e=this.state.potentialArrowAt===this.state.start;let s;switch(this.state.type){case n._super:return s=this.startNode(),this.next(),!this.match(n.parenL)||this.scope.allowDirectSuper||this.options.allowSuperOutsideMethod?this.scope.allowSuper||this.options.allowSuperOutsideMethod||this.raise(s.start,f.UnexpectedSuper):this.raise(s.start,f.SuperNotAllowed),this.match(n.parenL)||this.match(n.bracketL)||this.match(n.dot)||this.raise(s.start,f.UnsupportedSuper),this.finishNode(s,"Super");case n._import:return s=this.startNode(),this.next(),this.match(n.dot)?this.parseImportMetaProperty(s):(this.match(n.parenL)||this.raise(this.state.lastTokStart,f.UnsupportedImport),this.finishNode(s,"Import"));case n._this:return s=this.startNode(),this.next(),this.finishNode(s,"ThisExpression");case n.name:{s=this.startNode();const t=this.state.containsEsc,i=this.parseIdentifier();if(!t&&"async"===i.name&&this.match(n._function)&&!this.canInsertSemicolon()){const t=this.state.context.length-1;if(this.state.context[t]!==x.functionStatement)throw new Error("Internal error");return this.state.context[t]=x.functionExpression,this.next(),this.parseFunction(s,void 0,!0)}if(e&&!t&&"async"===i.name&&this.match(n.name)&&!this.canInsertSemicolon()){const t=this.state.maybeInArrowParameters,e=this.state.maybeInAsyncArrowHead,i=this.state.yieldPos,r=this.state.awaitPos;this.state.maybeInArrowParameters=!0,this.state.maybeInAsyncArrowHead=!0,this.state.yieldPos=-1,this.state.awaitPos=-1;const a=[this.parseIdentifier()];return this.expect(n.arrow),this.checkYieldAwaitInDefaultParams(),this.state.maybeInArrowParameters=t,this.state.maybeInAsyncArrowHead=e,this.state.yieldPos=i,this.state.awaitPos=r,this.parseArrowExpression(s,a,!0),s}return e&&this.match(n.arrow)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(s,[i],!1),s):i}case n._do:{this.expectPlugin("doExpressions");const t=this.startNode();this.next();const e=this.state.labels;return this.state.labels=[],t.body=this.parseBlock(),this.state.labels=e,this.finishNode(t,"DoExpression")}case n.regexp:{const t=this.state.value;return s=this.parseLiteral(t.value,"RegExpLiteral"),s.pattern=t.pattern,s.flags=t.flags,s}case n.num:return this.parseLiteral(this.state.value,"NumericLiteral");case n.bigint:return this.parseLiteral(this.state.value,"BigIntLiteral");case n.string:return this.parseLiteral(this.state.value,"StringLiteral");case n._null:return s=this.startNode(),this.next(),this.finishNode(s,"NullLiteral");case n._true:case n._false:return this.parseBooleanLiteral();case n.parenL:return this.parseParenAndDistinguishExpression(e);case n.bracketBarL:case n.bracketHashL:{this.expectPlugin("recordAndTuple");const e=this.state.inFSharpPipelineDirectBody,i=this.state.type===n.bracketBarL?n.bracketBarR:n.bracketR;return this.state.inFSharpPipelineDirectBody=!1,s=this.startNode(),this.next(),s.elements=this.parseExprList(i,!0,t,s),this.state.inFSharpPipelineDirectBody=e,this.finishNode(s,"TupleExpression")}case n.bracketL:{const e=this.state.inFSharpPipelineDirectBody;return this.state.inFSharpPipelineDirectBody=!1,s=this.startNode(),this.next(),s.elements=this.parseExprList(n.bracketR,!0,t,s),this.state.maybeInArrowParameters||this.toReferencedList(s.elements),this.state.inFSharpPipelineDirectBody=e,this.finishNode(s,"ArrayExpression")}case n.braceBarL:case n.braceHashL:{this.expectPlugin("recordAndTuple");const e=this.state.inFSharpPipelineDirectBody,s=this.state.type===n.braceBarL?n.braceBarR:n.braceR;this.state.inFSharpPipelineDirectBody=!1;const i=this.parseObj(s,!1,!0,t);return this.state.inFSharpPipelineDirectBody=e,i}case n.braceL:{const e=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;const s=this.parseObj(n.braceR,!1,!1,t);return this.state.inFSharpPipelineDirectBody=e,s}case n._function:return this.parseFunctionExpression();case n.at:this.parseDecorators();case n._class:return s=this.startNode(),this.takeDecorators(s),this.parseClass(s,!1);case n._new:return this.parseNew();case n.backQuote:return this.parseTemplate(!1);case n.doubleColon:{s=this.startNode(),this.next(),s.object=null;const t=s.callee=this.parseNoCallExpr();if("MemberExpression"===t.type)return this.finishNode(s,"BindExpression");throw this.raise(t.start,f.UnsupportedBind)}case n.hash:if(this.state.inPipeline)return s=this.startNode(),"smart"!==this.getPluginOption("pipelineOperator","proposal")&&this.raise(s.start,f.PrimaryTopicRequiresSmartPipeline),this.next(),this.primaryTopicReferenceIsAllowedInCurrentTopicContext()||this.raise(s.start,f.PrimaryTopicNotAllowed),this.registerTopicReference(),this.finishNode(s,"PipelinePrimaryTopicReference");default:throw this.unexpected()}}parseBooleanLiteral(){const t=this.startNode();return t.value=this.match(n._true),this.next(),this.finishNode(t,"BooleanLiteral")}parseMaybePrivateName(t){if(this.match(n.hash)){this.expectOnePlugin(["classPrivateProperties","classPrivateMethods"]),t||this.raise(this.state.pos,f.UnexpectedPrivateField);const e=this.startNode();return this.next(),this.assertNoSpace("Unexpected space between # and identifier"),e.id=this.parseIdentifier(!0),this.finishNode(e,"PrivateName")}return this.parseIdentifier(!0)}parseFunctionExpression(){const t=this.startNode();let e=this.startNode();return this.next(),e=this.createIdentifier(e,"function"),this.prodParam.hasYield&&this.eat(n.dot)?this.parseMetaProperty(t,e,"sent"):this.parseFunction(t)}parseMetaProperty(t,e,s){t.meta=e,"function"===e.name&&"sent"===s&&(this.isContextual(s)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected());const i=this.state.containsEsc;return t.property=this.parseIdentifier(!0),(t.property.name!==s||i)&&this.raise(t.property.start,f.UnsupportedMetaProperty,e.name,s),this.finishNode(t,"MetaProperty")}parseImportMetaProperty(t){const e=this.createIdentifier(this.startNodeAtNode(t),"import");return this.expect(n.dot),this.isContextual("meta")?(this.expectPlugin("importMeta"),this.inModule||this.raiseWithData(e.start,{code:"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"},f.ImportMetaOutsideModule),this.sawUnambiguousESM=!0):this.hasPlugin("importMeta")||this.raise(e.start,f.ImportCallArityLtOne),this.parseMetaProperty(t,e,"meta")}parseLiteral(t,e,s,i){s=s||this.state.start,i=i||this.state.startLoc;const r=this.startNodeAt(s,i);return this.addExtra(r,"rawValue",t),this.addExtra(r,"raw",this.input.slice(s,this.state.end)),r.value=t,this.next(),this.finishNode(r,e)}parseParenAndDistinguishExpression(t){const e=this.state.start,s=this.state.startLoc;let i;this.expect(n.parenL);const r=this.state.maybeInArrowParameters,a=this.state.yieldPos,o=this.state.awaitPos,h=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.yieldPos=-1,this.state.awaitPos=-1,this.state.inFSharpPipelineDirectBody=!1;const p=this.state.start,c=this.state.startLoc,u=[],l=new xt,d={start:0};let m,f,D=!0;for(;!this.match(n.parenR);){if(D)D=!1;else if(this.expect(n.comma,d.start||null),this.match(n.parenR)){f=this.state.start;break}if(this.match(n.ellipsis)){const t=this.state.start,e=this.state.startLoc;m=this.state.start,u.push(this.parseParenItem(this.parseRestBinding(),t,e)),this.checkCommaAfterRest(41);break}u.push(this.parseMaybeAssign(!1,l,this.parseParenItem,d))}const y=this.state.start,x=this.state.startLoc;this.expect(n.parenR),this.state.maybeInArrowParameters=r,this.state.inFSharpPipelineDirectBody=h;let g=this.startNodeAt(e,s);if(t&&this.shouldParseArrow()&&(g=this.parseArrow(g))){this.isAwaitAllowed()||this.state.maybeInAsyncArrowHead||(this.state.awaitPos=o),this.checkYieldAwaitInDefaultParams(),this.state.yieldPos=a,this.state.awaitPos=o;for(let t=0;t<u.length;t++){const e=u[t];e.extra&&e.extra.parenthesized&&this.unexpected(e.extra.parenStart)}return this.parseArrowExpression(g,u,!1),g}if(-1!==a&&(this.state.yieldPos=a),-1!==o&&(this.state.awaitPos=o),u.length||this.unexpected(this.state.lastTokStart),f&&this.unexpected(f),m&&this.unexpected(m),this.checkExpressionErrors(l,!0),d.start&&this.unexpected(d.start),this.toReferencedListDeep(u,!0),u.length>1?(i=this.startNodeAt(p,c),i.expressions=u,this.finishNodeAt(i,"SequenceExpression",y,x)):i=u[0],!this.options.createParenthesizedExpressions)return this.addExtra(i,"parenthesized",!0),this.addExtra(i,"parenStart",e),i;const P=this.startNodeAt(e,s);return P.expression=i,this.finishNode(P,"ParenthesizedExpression"),P}shouldParseArrow(){return!this.canInsertSemicolon()}parseArrow(t){if(this.eat(n.arrow))return t}parseParenItem(t,e,s){return t}parseNew(){const t=this.startNode();let e=this.startNode();if(this.next(),e=this.createIdentifier(e,"new"),this.eat(n.dot)){const s=this.parseMetaProperty(t,e,"target");if(!this.scope.inNonArrowFunction&&!this.scope.inClass){let t=f.UnexpectedNewTarget;this.hasPlugin("classProperties")&&(t+=" or class properties"),this.raise(s.start,t)}return s}return t.callee=this.parseNoCallExpr(),"Import"===t.callee.type?this.raise(t.callee.start,f.ImportCallNotNewExpression):"OptionalMemberExpression"===t.callee.type||"OptionalCallExpression"===t.callee.type?this.raise(this.state.lastTokEnd,f.OptionalChainingNoNew):this.eat(n.questionDot)&&this.raise(this.state.start,f.OptionalChainingNoNew),this.parseNewArguments(t),this.finishNode(t,"NewExpression")}parseNewArguments(t){if(this.eat(n.parenL)){const e=this.parseExprList(n.parenR);this.toReferencedList(e),t.arguments=e}else t.arguments=[]}parseTemplateElement(t){const e=this.startNode();return null===this.state.value&&(t||this.raise(this.state.start+1,f.InvalidEscapeSequenceTemplate)),e.value={raw:this.input.slice(this.state.start,this.state.end).replace(/\r\n?/g,"\n"),cooked:this.state.value},this.next(),e.tail=this.match(n.backQuote),this.finishNode(e,"TemplateElement")}parseTemplate(t){const e=this.startNode();this.next(),e.expressions=[];let s=this.parseTemplateElement(t);for(e.quasis=[s];!s.tail;)this.expect(n.dollarBraceL),e.expressions.push(this.parseExpression()),this.expect(n.braceR),e.quasis.push(s=this.parseTemplateElement(t));return this.next(),this.finishNode(e,"TemplateLiteral")}parseObj(t,e,s,i){const r=Object.create(null);let a=!0;const o=this.startNode();for(o.properties=[],this.next();!this.eat(t);){if(a)a=!1;else if(this.expect(n.comma),this.match(t)){this.addExtra(o,"trailingComma",this.state.lastTokStart),this.next();break}const s=this.parseObjectMember(e,i);e||this.checkDuplicatedProto(s,r,i),s.shorthand&&this.addExtra(s,"shorthand",!0),o.properties.push(s)}let h="ObjectExpression";return e?h="ObjectPattern":s&&(h="RecordExpression"),this.finishNode(o,h)}isAsyncProp(t){return!t.computed&&"Identifier"===t.key.type&&"async"===t.key.name&&(this.match(n.name)||this.match(n.num)||this.match(n.string)||this.match(n.bracketL)||this.state.type.keyword||this.match(n.star))&&!this.hasPrecedingLineBreak()}parseObjectMember(t,e){let s=[];if(this.match(n.at))for(this.hasPlugin("decorators")&&this.raise(this.state.start,f.UnsupportedPropertyDecorator);this.match(n.at);)s.push(this.parseDecorator());const i=this.startNode();let r,a,o=!1,h=!1;if(this.match(n.ellipsis))return s.length&&this.unexpected(),t?(this.next(),i.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(i,"RestElement")):this.parseSpread();s.length&&(i.decorators=s,s=[]),i.method=!1,(t||e)&&(r=this.state.start,a=this.state.startLoc),t||(o=this.eat(n.star));const p=this.state.containsEsc;return this.parsePropertyName(i,!1),t||p||o||!this.isAsyncProp(i)?h=!1:(h=!0,o=this.eat(n.star),this.parsePropertyName(i,!1)),this.parseObjPropValue(i,r,a,o,h,t,e,p),i}isGetterOrSetterMethod(t,e){return!e&&!t.computed&&"Identifier"===t.key.type&&("get"===t.key.name||"set"===t.key.name)&&(this.match(n.string)||this.match(n.num)||this.match(n.bracketL)||this.match(n.name)||!!this.state.type.keyword)}getGetterSetterExpectedParamCount(t){return"get"===t.kind?0:1}checkGetterSetterParams(t){const e=this.getGetterSetterExpectedParamCount(t),s=t.start;t.params.length!==e&&("get"===t.kind?this.raise(s,f.BadGetterArity):this.raise(s,f.BadSetterArity)),"set"===t.kind&&"RestElement"===t.params[t.params.length-1].type&&this.raise(s,f.BadSetterRestParameter)}parseObjectMethod(t,e,s,i,r){return s||e||this.match(n.parenL)?(i&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,e,s,!1,!1,"ObjectMethod")):!r&&this.isGetterOrSetterMethod(t,i)?((e||s)&&this.unexpected(),t.kind=t.key.name,this.parsePropertyName(t,!1),this.parseMethod(t,!1,!1,!1,!1,"ObjectMethod"),this.checkGetterSetterParams(t),t):void 0}parseObjectProperty(t,e,s,i,r){return t.shorthand=!1,this.eat(n.colon)?(t.value=i?this.parseMaybeDefault(this.state.start,this.state.startLoc):this.parseMaybeAssign(!1,r),this.finishNode(t,"ObjectProperty")):t.computed||"Identifier"!==t.key.type?void 0:(this.checkReservedWord(t.key.name,t.key.start,!0,!0),i?t.value=this.parseMaybeDefault(e,s,t.key.__clone()):this.match(n.eq)&&r?(-1===r.shorthandAssign&&(r.shorthandAssign=this.state.start),t.value=this.parseMaybeDefault(e,s,t.key.__clone())):t.value=t.key.__clone(),t.shorthand=!0,this.finishNode(t,"ObjectProperty"))}parseObjPropValue(t,e,s,i,r,a,n,o){const h=this.parseObjectMethod(t,i,r,a,o)||this.parseObjectProperty(t,e,s,a,n);return h||this.unexpected(),h}parsePropertyName(t,e){if(this.eat(n.bracketL))t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(n.bracketR);else{const s=this.state.inPropertyName;this.state.inPropertyName=!0,t.key=this.match(n.num)||this.match(n.string)||this.match(n.bigint)?this.parseExprAtom():this.parseMaybePrivateName(e),"PrivateName"!==t.key.type&&(t.computed=!1),this.state.inPropertyName=s}return t.key}initFunction(t,e){t.id=null,t.generator=!1,t.async=!!e}parseMethod(t,e,s,i,r,a,n=!1){const o=this.state.yieldPos,h=this.state.awaitPos;this.state.yieldPos=-1,this.state.awaitPos=-1,this.initFunction(t,s),t.generator=!!e;const p=i;return this.scope.enter(18|(n?64:0)|(r?32:0)),this.prodParam.enter(et(s,t.generator)),this.parseFunctionParams(t,p),this.parseFunctionBodyAndFinish(t,a,!0),this.prodParam.exit(),this.scope.exit(),this.state.yieldPos=o,this.state.awaitPos=h,t}parseArrowExpression(t,e,s,i){this.scope.enter(6),this.prodParam.enter(et(s,!1)),this.initFunction(t,s);const r=this.state.maybeInArrowParameters,a=this.state.yieldPos,n=this.state.awaitPos;return e&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(t,e,i)),this.state.maybeInArrowParameters=!1,this.state.yieldPos=-1,this.state.awaitPos=-1,this.parseFunctionBody(t,!0),this.prodParam.exit(),this.scope.exit(),this.state.maybeInArrowParameters=r,this.state.yieldPos=a,this.state.awaitPos=n,this.finishNode(t,"ArrowFunctionExpression")}setArrowFunctionParameters(t,e,s){t.params=this.toAssignableList(e,s)}parseFunctionBodyAndFinish(t,e,s=!1){this.parseFunctionBody(t,!1,s),this.finishNode(t,e)}parseFunctionBody(t,e,s=!1){const i=e&&!this.match(n.braceL),r=this.state.inParameters;if(this.state.inParameters=!1,i)t.body=this.parseMaybeAssign(),this.checkParams(t,!1,e,!1);else{const i=this.state.strict,r=this.state.labels;this.state.labels=[],this.prodParam.enter(4|this.prodParam.currentFlags()),t.body=this.parseBlock(!0,!1,r=>{const a=!this.isSimpleParamList(t.params);if(r&&a){const e="method"!==t.kind&&"constructor"!==t.kind||!t.key?t.start:t.key.end;this.raise(e,f.IllegalLanguageModeDirective)}const n=!i&&this.state.strict;this.checkParams(t,!(this.state.strict||e||s||a),e,n),this.state.strict&&t.id&&this.checkLVal(t.id,65,void 0,"function name",void 0,n)}),this.prodParam.exit(),this.state.labels=r}this.state.inParameters=r}isSimpleParamList(t){for(let e=0,s=t.length;e<s;e++)if("Identifier"!==t[e].type)return!1;return!0}checkParams(t,e,s,i=!0){const r=Object.create(null);for(let s=0;s<t.params.length;s++)this.checkLVal(t.params[s],5,e?null:r,"function parameter list",void 0,i)}parseExprList(t,e,s,i){const r=[];let a=!0;for(;!this.eat(t);){if(a)a=!1;else if(this.expect(n.comma),this.match(t)){i&&this.addExtra(i,"trailingComma",this.state.lastTokStart),this.next();break}r.push(this.parseExprListItem(e,s))}return r}parseExprListItem(t,e,s,i){let r;if(t&&this.match(n.comma))r=null;else if(this.match(n.ellipsis)){const t=this.state.start,i=this.state.startLoc;r=this.parseParenItem(this.parseSpread(e,s),t,i)}else if(this.match(n.question)){this.expectPlugin("partialApplication"),i||this.raise(this.state.start,f.UnexpectedArgumentPlaceholder);const t=this.startNode();this.next(),r=this.finishNode(t,"ArgumentPlaceholder")}else r=this.parseMaybeAssign(!1,e,this.parseParenItem,s);return r}parseIdentifier(t){const e=this.startNode(),s=this.parseIdentifierName(e.start,t);return this.createIdentifier(e,s)}createIdentifier(t,e){return t.name=e,t.loc.identifierName=e,this.finishNode(t,"Identifier")}parseIdentifierName(t,e){let s;if(this.match(n.name))s=this.state.value;else{if(!this.state.type.keyword)throw this.unexpected();s=this.state.type.keyword,"class"!==s&&"function"!==s||this.state.lastTokEnd===this.state.lastTokStart+1&&46===this.input.charCodeAt(this.state.lastTokStart)||this.state.context.pop()}return e?this.state.type=n.name:this.checkReservedWord(s,this.state.start,!!this.state.type.keyword,!1),this.next(),s}checkReservedWord(t,e,s,i){if(this.prodParam.hasYield&&"yield"===t)return void this.raise(e,f.YieldBindingIdentifier);if("await"===t){if(this.prodParam.hasAwait)return void this.raise(e,f.AwaitBindingIdentifier);-1===this.state.awaitPos&&(this.state.maybeInAsyncArrowHead||this.isAwaitAllowed())&&(this.state.awaitPos=this.state.start)}if(this.scope.inClass&&!this.scope.inNonArrowFunction&&"arguments"===t)return void this.raise(e,f.ArgumentsDisallowedInInitializer);if(s&&function(t){return k.has(t)}(t))return void this.raise(e,f.UnexpectedKeyword,t);(this.state.strict?i?O:B:L)(t,this.inModule)&&(this.prodParam.hasAwait||"await"!==t?this.raise(e,f.UnexpectedReservedWord,t):this.raise(e,f.AwaitNotInAsyncFunction))}isAwaitAllowed(){return this.scope.inFunction?this.prodParam.hasAwait:!!this.options.allowAwaitOutsideFunction||!!this.hasPlugin("topLevelAwait")&&(this.inModule&&this.prodParam.hasAwait)}parseAwait(){const t=this.startNode();return this.next(),this.state.inParameters?this.raise(t.start,f.AwaitExpressionFormalParameter):-1===this.state.awaitPos&&(this.state.awaitPos=t.start),this.eat(n.star)&&this.raise(t.start,f.ObsoleteAwaitStar),this.scope.inFunction||this.options.allowAwaitOutsideFunction||(this.hasPrecedingLineBreak()||this.match(n.plusMin)||this.match(n.parenL)||this.match(n.bracketL)||this.match(n.backQuote)||this.match(n.regexp)||this.match(n.slash)||this.hasPlugin("v8intrinsic")&&this.match(n.modulo)?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(t.argument=this.parseMaybeUnary()),this.finishNode(t,"AwaitExpression")}parseYield(t){const e=this.startNode();return this.state.inParameters?this.raise(e.start,f.YieldInParameter):-1===this.state.yieldPos&&(this.state.yieldPos=e.start),this.next(),this.match(n.semi)||!this.match(n.star)&&!this.state.type.startsExpr||this.hasPrecedingLineBreak()?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(n.star),e.argument=this.parseMaybeAssign(t)),this.finishNode(e,"YieldExpression")}checkPipelineAtInfixOperator(t,e){"smart"===this.getPluginOption("pipelineOperator","proposal")&&"SequenceExpression"===t.type&&this.raise(e,f.PipelineHeadSequenceExpression)}parseSmartPipelineBody(t,e,s){const i=this.checkSmartPipelineBodyStyle(t);return this.checkSmartPipelineBodyEarlyErrors(t,i,e),this.parseSmartPipelineBodyInStyle(t,i,e,s)}checkSmartPipelineBodyEarlyErrors(t,e,s){if(this.match(n.arrow))throw this.raise(this.state.start,f.PipelineBodyNoArrow);"PipelineTopicExpression"===e&&"SequenceExpression"===t.type&&this.raise(s,f.PipelineBodySequenceExpression)}parseSmartPipelineBodyInStyle(t,e,s,i){const r=this.startNodeAt(s,i);switch(e){case"PipelineBareFunction":r.callee=t;break;case"PipelineBareConstructor":r.callee=t.callee;break;case"PipelineBareAwaitedFunction":r.callee=t.argument;break;case"PipelineTopicExpression":this.topicReferenceWasUsedInCurrentTopicContext()||this.raise(s,f.PipelineTopicUnused),r.expression=t;break;default:throw new Error("Internal @babel/parser error: Unknown pipeline style (".concat(e,")"))}return this.finishNode(r,e)}checkSmartPipelineBodyStyle(t){return t.type,this.isSimpleReference(t)?"PipelineBareFunction":"PipelineTopicExpression"}isSimpleReference(t){switch(t.type){case"MemberExpression":return!t.computed&&this.isSimpleReference(t.object);case"Identifier":return!0;default:return!1}}withTopicPermittingContext(t){const e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return t()}finally{this.state.topicContext=e}}withTopicForbiddingContext(t){const e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return t()}finally{this.state.topicContext=e}}withSoloAwaitPermittingContext(t){const e=this.state.soloAwait;this.state.soloAwait=!0;try{return t()}finally{this.state.soloAwait=e}}registerTopicReference(){this.state.topicContext.maxTopicIndex=0}primaryTopicReferenceIsAllowedInCurrentTopicContext(){return this.state.topicContext.maxNumOfResolvableTopics>=1}topicReferenceWasUsedInCurrentTopicContext(){return null!=this.state.topicContext.maxTopicIndex&&this.state.topicContext.maxTopicIndex>=0}parseFSharpPipelineBody(t,e){const s=this.state.start,i=this.state.startLoc;this.state.potentialArrowAt=this.state.start;const r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;const a=this.parseExprOp(this.parseMaybeUnary(),s,i,t,e);return this.state.inFSharpPipelineDirectBody=r,a}}{parseTopLevel(t,e){if(e.sourceType=this.options.sourceType,e.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(e,!0,!0,n.eof),this.inModule&&!this.options.allowUndeclaredExports&&this.scope.undefinedExports.size>0)for(let t=0,e=Array.from(this.scope.undefinedExports);t<e.length;t++){const[s]=e[t],i=this.scope.undefinedExports.get(s);this.raise(i,f.ModuleExportUndefined,s)}return t.program=this.finishNode(e,"Program"),t.comments=this.state.comments,this.options.tokens&&(t.tokens=this.tokens),this.finishNode(t,"File")}stmtToDirective(t){const e=t.expression,s=this.startNodeAt(e.start,e.loc.start),i=this.startNodeAt(t.start,t.loc.start),r=this.input.slice(e.start,e.end),a=s.value=r.slice(1,-1);return this.addExtra(s,"raw",r),this.addExtra(s,"rawValue",a),i.value=this.finishNodeAt(s,"DirectiveLiteral",e.end,e.loc.end),this.finishNodeAt(i,"Directive",t.end,t.loc.end)}parseInterpreterDirective(){if(!this.match(n.interpreterDirective))return null;const t=this.startNode();return t.value=this.state.value,this.next(),this.finishNode(t,"InterpreterDirective")}isLet(t){if(!this.isContextual("let"))return!1;const e=this.nextTokenStart(),s=this.input.charCodeAt(e);if(91===s)return!0;if(t)return!1;if(123===s)return!0;if(w(s)){let t=e+1;for(;S(this.input.charCodeAt(t));)++t;const s=this.input.slice(e,t);if(!R.test(s))return!0}return!1}parseStatement(t,e){return this.match(n.at)&&this.parseDecorators(!0),this.parseStatementContent(t,e)}parseStatementContent(t,e){let s=this.state.type;const i=this.startNode();let r;switch(this.isLet(t)&&(s=n._var,r="let"),s){case n._break:case n._continue:return this.parseBreakContinueStatement(i,s.keyword);case n._debugger:return this.parseDebuggerStatement(i);case n._do:return this.parseDoStatement(i);case n._for:return this.parseForStatement(i);case n._function:if(46===this.lookaheadCharCode())break;return t&&(this.state.strict?this.raise(this.state.start,f.StrictFunction):"if"!==t&&"label"!==t&&this.raise(this.state.start,f.SloppyFunction)),this.parseFunctionStatement(i,!1,!t);case n._class:return t&&this.unexpected(),this.parseClass(i,!0);case n._if:return this.parseIfStatement(i);case n._return:return this.parseReturnStatement(i);case n._switch:return this.parseSwitchStatement(i);case n._throw:return this.parseThrowStatement(i);case n._try:return this.parseTryStatement(i);case n._const:case n._var:return r=r||this.state.value,t&&"var"!==r&&this.raise(this.state.start,f.UnexpectedLexicalDeclaration),this.parseVarStatement(i,r);case n._while:return this.parseWhileStatement(i);case n._with:return this.parseWithStatement(i);case n.braceL:return this.parseBlock();case n.semi:return this.parseEmptyStatement(i);case n._export:case n._import:{const t=this.lookaheadCharCode();if(40===t||46===t)break;let r;return this.options.allowImportExportEverywhere||e||this.raise(this.state.start,f.UnexpectedImportExport),this.next(),s===n._import?(r=this.parseImport(i),"ImportDeclaration"!==r.type||r.importKind&&"value"!==r.importKind||(this.sawUnambiguousESM=!0)):(r=this.parseExport(i),("ExportNamedDeclaration"!==r.type||r.exportKind&&"value"!==r.exportKind)&&("ExportAllDeclaration"!==r.type||r.exportKind&&"value"!==r.exportKind)&&"ExportDefaultDeclaration"!==r.type||(this.sawUnambiguousESM=!0)),this.assertModuleNodeAllowed(i),r}default:if(this.isAsyncFunction())return t&&this.raise(this.state.start,f.AsyncFunctionInSingleStatementContext),this.next(),this.parseFunctionStatement(i,!0,!t)}const a=this.state.value,o=this.parseExpression();return s===n.name&&"Identifier"===o.type&&this.eat(n.colon)?this.parseLabeledStatement(i,a,o,t):this.parseExpressionStatement(i,o)}assertModuleNodeAllowed(t){this.options.allowImportExportEverywhere||this.inModule||this.raiseWithData(t.start,{code:"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"},f.ImportOutsideModule)}takeDecorators(t){const e=this.state.decoratorStack[this.state.decoratorStack.length-1];e.length&&(t.decorators=e,this.resetStartLocationFromNode(t,e[0]),this.state.decoratorStack[this.state.decoratorStack.length-1]=[])}canHaveLeadingDecorator(){return this.match(n._class)}parseDecorators(t){const e=this.state.decoratorStack[this.state.decoratorStack.length-1];for(;this.match(n.at);){const t=this.parseDecorator();e.push(t)}if(this.match(n._export))t||this.unexpected(),this.hasPlugin("decorators")&&!this.getPluginOption("decorators","decoratorsBeforeExport")&&this.raise(this.state.start,f.DecoratorExportClass);else if(!this.canHaveLeadingDecorator())throw this.raise(this.state.start,f.UnexpectedLeadingDecorator)}parseDecorator(){this.expectOnePlugin(["decorators-legacy","decorators"]);const t=this.startNode();if(this.next(),this.hasPlugin("decorators")){this.state.decoratorStack.push([]);const e=this.state.start,s=this.state.startLoc;let i;if(this.eat(n.parenL))i=this.parseExpression(),this.expect(n.parenR);else for(i=this.parseIdentifier(!1);this.eat(n.dot);){const t=this.startNodeAt(e,s);t.object=i,t.property=this.parseIdentifier(!0),t.computed=!1,i=this.finishNode(t,"MemberExpression")}t.expression=this.parseMaybeDecoratorArguments(i),this.state.decoratorStack.pop()}else t.expression=this.parseExprSubscripts();return this.finishNode(t,"Decorator")}parseMaybeDecoratorArguments(t){if(this.eat(n.parenL)){const e=this.startNodeAtNode(t);return e.callee=t,e.arguments=this.parseCallExpressionArguments(n.parenR,!1),this.toReferencedList(e.arguments),this.finishNode(e,"CallExpression")}return t}parseBreakContinueStatement(t,e){const s="break"===e;return this.next(),this.isLineTerminator()?t.label=null:(t.label=this.parseIdentifier(),this.semicolon()),this.verifyBreakContinue(t,e),this.finishNode(t,s?"BreakStatement":"ContinueStatement")}verifyBreakContinue(t,e){const s="break"===e;let i;for(i=0;i<this.state.labels.length;++i){const e=this.state.labels[i];if(null==t.label||e.name===t.label.name){if(null!=e.kind&&(s||"loop"===e.kind))break;if(t.label&&s)break}}i===this.state.labels.length&&this.raise(t.start,f.IllegalBreakContinue,e)}parseDebuggerStatement(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")}parseHeaderExpression(){this.expect(n.parenL);const t=this.parseExpression();return this.expect(n.parenR),t}parseDoStatement(t){return this.next(),this.state.labels.push(Et),t.body=this.withTopicForbiddingContext(()=>this.parseStatement("do")),this.state.labels.pop(),this.expect(n._while),t.test=this.parseHeaderExpression(),this.eat(n.semi),this.finishNode(t,"DoWhileStatement")}parseForStatement(t){this.next(),this.state.labels.push(Et);let e=-1;if(this.isAwaitAllowed()&&this.eatContextual("await")&&(e=this.state.lastTokStart),this.scope.enter(0),this.expect(n.parenL),this.match(n.semi))return e>-1&&this.unexpected(e),this.parseFor(t,null);const s=this.isLet();if(this.match(n._var)||this.match(n._const)||s){const i=this.startNode(),r=s?"let":this.state.value;return this.next(),this.parseVar(i,!0,r),this.finishNode(i,"VariableDeclaration"),(this.match(n._in)||this.isContextual("of"))&&1===i.declarations.length?this.parseForIn(t,i,e):(e>-1&&this.unexpected(e),this.parseFor(t,i))}const i=new xt,r=this.parseExpression(!0,i);if(this.match(n._in)||this.isContextual("of")){this.toAssignable(r);const s=this.isContextual("of")?"for-of statement":"for-in statement";return this.checkLVal(r,void 0,void 0,s),this.parseForIn(t,r,e)}return this.checkExpressionErrors(i,!0),e>-1&&this.unexpected(e),this.parseFor(t,r)}parseFunctionStatement(t,e,s){return this.next(),this.parseFunction(t,1|(s?0:2),e)}parseIfStatement(t){return this.next(),t.test=this.parseHeaderExpression(),t.consequent=this.parseStatement("if"),t.alternate=this.eat(n._else)?this.parseStatement("if"):null,this.finishNode(t,"IfStatement")}parseReturnStatement(t){return this.prodParam.hasReturn||this.options.allowReturnOutsideFunction||this.raise(this.state.start,f.IllegalReturn),this.next(),this.isLineTerminator()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")}parseSwitchStatement(t){this.next(),t.discriminant=this.parseHeaderExpression();const e=t.cases=[];let s,i;for(this.expect(n.braceL),this.state.labels.push(Ct),this.scope.enter(0);!this.match(n.braceR);)if(this.match(n._case)||this.match(n._default)){const t=this.match(n._case);s&&this.finishNode(s,"SwitchCase"),e.push(s=this.startNode()),s.consequent=[],this.next(),t?s.test=this.parseExpression():(i&&this.raise(this.state.lastTokStart,f.MultipleDefaultsInSwitch),i=!0,s.test=null),this.expect(n.colon)}else s?s.consequent.push(this.parseStatement(null)):this.unexpected();return this.scope.exit(),s&&this.finishNode(s,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(t,"SwitchStatement")}parseThrowStatement(t){return this.next(),o.test(this.input.slice(this.state.lastTokEnd,this.state.start))&&this.raise(this.state.lastTokEnd,f.NewlineAfterThrow),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")}parseTryStatement(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.match(n._catch)){const e=this.startNode();if(this.next(),this.match(n.parenL)){this.expect(n.parenL),e.param=this.parseBindingAtom();const t="Identifier"===e.param.type;this.scope.enter(t?8:0),this.checkLVal(e.param,9,null,"catch clause"),this.expect(n.parenR)}else e.param=null,this.scope.enter(0);e.body=this.withTopicForbiddingContext(()=>this.parseBlock(!1,!1)),this.scope.exit(),t.handler=this.finishNode(e,"CatchClause")}return t.finalizer=this.eat(n._finally)?this.parseBlock():null,t.handler||t.finalizer||this.raise(t.start,f.NoCatchOrFinally),this.finishNode(t,"TryStatement")}parseVarStatement(t,e){return this.next(),this.parseVar(t,!1,e),this.semicolon(),this.finishNode(t,"VariableDeclaration")}parseWhileStatement(t){return this.next(),t.test=this.parseHeaderExpression(),this.state.labels.push(Et),t.body=this.withTopicForbiddingContext(()=>this.parseStatement("while")),this.state.labels.pop(),this.finishNode(t,"WhileStatement")}parseWithStatement(t){return this.state.strict&&this.raise(this.state.start,f.StrictWith),this.next(),t.object=this.parseHeaderExpression(),t.body=this.withTopicForbiddingContext(()=>this.parseStatement("with")),this.finishNode(t,"WithStatement")}parseEmptyStatement(t){return this.next(),this.finishNode(t,"EmptyStatement")}parseLabeledStatement(t,e,s,i){for(let t=0,i=this.state.labels;t<i.length;t++){i[t].name===e&&this.raise(s.start,f.LabelRedeclaration,e)}const r=this.state.type.isLoop?"loop":this.match(n._switch)?"switch":null;for(let e=this.state.labels.length-1;e>=0;e--){const s=this.state.labels[e];if(s.statementStart!==t.start)break;s.statementStart=this.state.start,s.kind=r}return this.state.labels.push({name:e,kind:r,statementStart:this.state.start}),t.body=this.parseStatement(i?-1===i.indexOf("label")?i+"label":i:"label"),this.state.labels.pop(),t.label=s,this.finishNode(t,"LabeledStatement")}parseExpressionStatement(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")}parseBlock(t=!1,e=!0,s){const i=this.startNode();return this.expect(n.braceL),e&&this.scope.enter(0),this.parseBlockBody(i,t,!1,n.braceR,s),e&&this.scope.exit(),this.finishNode(i,"BlockStatement")}isValidDirective(t){return"ExpressionStatement"===t.type&&"StringLiteral"===t.expression.type&&!t.expression.extra.parenthesized}parseBlockBody(t,e,s,i,r){const a=t.body=[],n=t.directives=[];this.parseBlockOrModuleBlockBody(a,e?n:void 0,s,i,r)}parseBlockOrModuleBlockBody(t,e,s,i,r){const a=[],n=this.state.strict;let o=!1,h=!1;for(;!this.match(i);){!h&&this.state.octalPositions.length&&a.push(...this.state.octalPositions);const i=this.parseStatement(null,s);if(e&&!h&&this.isValidDirective(i)){const t=this.stmtToDirective(i);e.push(t),o||"use strict"!==t.value.value||(o=!0,this.setStrict(!0))}else h=!0,t.push(i)}if(this.state.strict&&a.length)for(let t=0;t<a.length;t++){const e=a[t];this.raise(e,f.StrictOctalLiteral)}r&&r.call(this,o),n||this.setStrict(!1),this.next()}parseFor(t,e){return t.init=e,this.expect(n.semi),t.test=this.match(n.semi)?null:this.parseExpression(),this.expect(n.semi),t.update=this.match(n.parenR)?null:this.parseExpression(),this.expect(n.parenR),t.body=this.withTopicForbiddingContext(()=>this.parseStatement("for")),this.scope.exit(),this.state.labels.pop(),this.finishNode(t,"ForStatement")}parseForIn(t,e,s){const i=this.match(n._in);return this.next(),i?s>-1&&this.unexpected(s):t.await=s>-1,"VariableDeclaration"!==e.type||null==e.declarations[0].init||i&&!this.state.strict&&"var"===e.kind&&"Identifier"===e.declarations[0].id.type?"AssignmentPattern"===e.type&&this.raise(e.start,f.InvalidLhs,"for-loop"):this.raise(e.start,f.ForInOfLoopInitializer,i?"for-in":"for-of"),t.left=e,t.right=i?this.parseExpression():this.parseMaybeAssign(),this.expect(n.parenR),t.body=this.withTopicForbiddingContext(()=>this.parseStatement("for")),this.scope.exit(),this.state.labels.pop(),this.finishNode(t,i?"ForInStatement":"ForOfStatement")}parseVar(t,e,s){const i=t.declarations=[],r=this.hasPlugin("typescript");for(t.kind=s;;){const t=this.startNode();if(this.parseVarId(t,s),this.eat(n.eq)?t.init=this.parseMaybeAssign(e):("const"!==s||this.match(n._in)||this.isContextual("of")?"Identifier"===t.id.type||e&&(this.match(n._in)||this.isContextual("of"))||this.raise(this.state.lastTokEnd,f.DeclarationMissingInitializer,"Complex binding patterns"):r||this.unexpected(),t.init=null),i.push(this.finishNode(t,"VariableDeclarator")),!this.eat(n.comma))break}return t}parseVarId(t,e){t.id=this.parseBindingAtom(),this.checkLVal(t.id,"var"===e?5:9,void 0,"variable declaration","var"!==e)}parseFunction(t,e=0,s=!1){const i=1&e,r=2&e,a=!(!i||4&e);this.initFunction(t,s),this.match(n.star)&&r&&this.raise(this.state.start,f.GeneratorInSingleStatementContext),t.generator=this.eat(n.star),i&&(t.id=this.parseFunctionId(a));const o=this.state.maybeInArrowParameters,h=this.state.yieldPos,p=this.state.awaitPos;return this.state.maybeInArrowParameters=!1,this.state.yieldPos=-1,this.state.awaitPos=-1,this.scope.enter(2),this.prodParam.enter(et(s,t.generator)),i||(t.id=this.parseFunctionId()),this.parseFunctionParams(t),this.withTopicForbiddingContext(()=>{this.parseFunctionBodyAndFinish(t,i?"FunctionDeclaration":"FunctionExpression")}),this.prodParam.exit(),this.scope.exit(),i&&!r&&this.registerFunctionStatementId(t),this.state.maybeInArrowParameters=o,this.state.yieldPos=h,this.state.awaitPos=p,t}parseFunctionId(t){return t||this.match(n.name)?this.parseIdentifier():null}parseFunctionParams(t,e){const s=this.state.inParameters;this.state.inParameters=!0,this.expect(n.parenL),t.params=this.parseBindingList(n.parenR,41,!1,e),this.state.inParameters=s,this.checkYieldAwaitInDefaultParams()}registerFunctionStatementId(t){t.id&&this.scope.declareName(t.id.name,this.state.strict||t.generator||t.async?this.scope.treatFunctionsAsVar?5:9:17,t.id.start)}parseClass(t,e,s){this.next(),this.takeDecorators(t);const i=this.state.strict;return this.state.strict=!0,this.parseClassId(t,e,s),this.parseClassSuper(t),t.body=this.parseClassBody(!!t.superClass,i),this.state.strict=i,this.finishNode(t,e?"ClassDeclaration":"ClassExpression")}isClassProperty(){return this.match(n.eq)||this.match(n.semi)||this.match(n.braceR)}isClassMethod(){return this.match(n.parenL)}isNonstaticConstructor(t){return!(t.computed||t.static||"constructor"!==t.key.name&&"constructor"!==t.key.value)}parseClassBody(t,e){this.classScope.enter();const s={hadConstructor:!1};let i=[];const r=this.startNode();if(r.body=[],this.expect(n.braceL),this.withTopicForbiddingContext(()=>{for(;!this.match(n.braceR);){if(this.eat(n.semi)){if(i.length>0)throw this.raise(this.state.lastTokEnd,f.DecoratorSemicolon);continue}if(this.match(n.at)){i.push(this.parseDecorator());continue}const e=this.startNode();i.length&&(e.decorators=i,this.resetStartLocationFromNode(e,i[0]),i=[]),this.parseClassMember(r,e,s,t),"constructor"===e.kind&&e.decorators&&e.decorators.length>0&&this.raise(e.start,f.DecoratorConstructor)}}),e||(this.state.strict=!1),this.next(),i.length)throw this.raise(this.state.start,f.TrailingDecorator);return this.classScope.exit(),this.finishNode(r,"ClassBody")}parseClassMemberFromModifier(t,e){const s=this.state.containsEsc,i=this.parseIdentifier(!0);if(this.isClassMethod()){const s=e;return s.kind="method",s.computed=!1,s.key=i,s.static=!1,this.pushClassMethod(t,s,!1,!1,!1,!1),!0}if(this.isClassProperty()){const s=e;return s.computed=!1,s.key=i,s.static=!1,t.body.push(this.parseClassProperty(s)),!0}if(s)throw this.unexpected();return!1}parseClassMember(t,e,s,i){const r=this.isContextual("static");r&&this.parseClassMemberFromModifier(t,e)||this.parseClassMemberWithIsStatic(t,e,s,r,i)}parseClassMemberWithIsStatic(t,e,s,i,r){const a=e,o=e,h=e,p=e,c=a,u=a;if(e.static=i,this.eat(n.star))return c.kind="method",this.parseClassPropertyName(c),"PrivateName"===c.key.type?void this.pushClassPrivateMethod(t,o,!0,!1):(this.isNonstaticConstructor(a)&&this.raise(a.key.start,f.ConstructorIsGenerator),void this.pushClassMethod(t,a,!0,!1,!1,!1));const l=this.state.containsEsc,d=this.parseClassPropertyName(e),m="PrivateName"===d.type,D="Identifier"===d.type,y=this.state.start;if(this.parsePostMemberNameModifiers(u),this.isClassMethod()){if(c.kind="method",m)return void this.pushClassPrivateMethod(t,o,!1,!1);const e=this.isNonstaticConstructor(a);let i=!1;e&&(a.kind="constructor",s.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(d.start,f.DuplicateConstructor),s.hadConstructor=!0,i=r),this.pushClassMethod(t,a,!1,!1,e,i)}else if(this.isClassProperty())m?this.pushClassPrivateProperty(t,p):this.pushClassProperty(t,h);else if(!D||"async"!==d.name||l||this.isLineTerminator())!D||"get"!==d.name&&"set"!==d.name||l||this.match(n.star)&&this.isLineTerminator()?this.isLineTerminator()?m?this.pushClassPrivateProperty(t,p):this.pushClassProperty(t,h):this.unexpected():(c.kind=d.name,this.parseClassPropertyName(a),"PrivateName"===c.key.type?this.pushClassPrivateMethod(t,o,!1,!1):(this.isNonstaticConstructor(a)&&this.raise(a.key.start,f.ConstructorIsAccessor),this.pushClassMethod(t,a,!1,!1,!1,!1)),this.checkGetterSetterParams(a));else{const e=this.eat(n.star);u.optional&&this.unexpected(y),c.kind="method",this.parseClassPropertyName(c),this.parsePostMemberNameModifiers(u),"PrivateName"===c.key.type?this.pushClassPrivateMethod(t,o,e,!0):(this.isNonstaticConstructor(a)&&this.raise(a.key.start,f.ConstructorIsAsync),this.pushClassMethod(t,a,e,!0,!1,!1))}}parseClassPropertyName(t){const e=this.parsePropertyName(t,!0);return t.computed||!t.static||"prototype"!==e.name&&"prototype"!==e.value||this.raise(e.start,f.StaticPrototype),"PrivateName"===e.type&&"constructor"===e.id.name&&this.raise(e.start,f.ConstructorClassPrivateField),e}pushClassProperty(t,e){e.computed||"constructor"!==e.key.name&&"constructor"!==e.key.value||this.raise(e.key.start,f.ConstructorClassField),t.body.push(this.parseClassProperty(e))}pushClassPrivateProperty(t,e){this.expectPlugin("classPrivateProperties",e.key.start);const s=this.parseClassPrivateProperty(e);t.body.push(s),this.classScope.declarePrivateName(s.key.id.name,0,s.key.start)}pushClassMethod(t,e,s,i,r,a){t.body.push(this.parseMethod(e,s,i,r,a,"ClassMethod",!0))}pushClassPrivateMethod(t,e,s,i){this.expectPlugin("classPrivateMethods",e.key.start);const r=this.parseMethod(e,s,i,!1,!1,"ClassPrivateMethod",!0);t.body.push(r);const a="get"===r.kind?r.static?6:2:"set"===r.kind?r.static?5:1:0;this.classScope.declarePrivateName(r.key.id.name,a,r.key.start)}parsePostMemberNameModifiers(t){}parseAccessModifier(){}parseClassPrivateProperty(t){return this.scope.enter(80),this.prodParam.enter(0),t.value=this.eat(n.eq)?this.parseMaybeAssign():null,this.semicolon(),this.prodParam.exit(),this.scope.exit(),this.finishNode(t,"ClassPrivateProperty")}parseClassProperty(t){return t.typeAnnotation||this.expectPlugin("classProperties"),this.scope.enter(80),this.prodParam.enter(0),this.match(n.eq)?(this.expectPlugin("classProperties"),this.next(),t.value=this.parseMaybeAssign()):t.value=null,this.semicolon(),this.prodParam.exit(),this.scope.exit(),this.finishNode(t,"ClassProperty")}parseClassId(t,e,s,i=139){this.match(n.name)?(t.id=this.parseIdentifier(),e&&this.checkLVal(t.id,i,void 0,"class name")):s||!e?t.id=null:this.unexpected(null,f.MissingClassName)}parseClassSuper(t){t.superClass=this.eat(n._extends)?this.parseExprSubscripts():null}parseExport(t){const e=this.maybeParseExportDefaultSpecifier(t),s=!e||this.eat(n.comma),i=s&&this.eatExportStar(t),r=i&&this.maybeParseExportNamespaceSpecifier(t),a=s&&(!r||this.eat(n.comma)),o=e||i;if(i&&!r)return e&&this.unexpected(),this.parseExportFrom(t,!0),this.finishNode(t,"ExportAllDeclaration");const h=this.maybeParseExportNamedSpecifiers(t);if(e&&s&&!i&&!h||r&&a&&!h)throw this.unexpected(null,n.braceL);let p;if(o||h?(p=!1,this.parseExportFrom(t,o)):p=this.maybeParseExportDeclaration(t),o||h||p)return this.checkExport(t,!0,!1,!!t.source),this.finishNode(t,"ExportNamedDeclaration");if(this.eat(n._default))return t.declaration=this.parseExportDefaultExpression(),this.checkExport(t,!0,!0),this.finishNode(t,"ExportDefaultDeclaration");throw this.unexpected(null,n.braceL)}eatExportStar(t){return this.eat(n.star)}maybeParseExportDefaultSpecifier(t){if(this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom");const e=this.startNode();return e.exported=this.parseIdentifier(!0),t.specifiers=[this.finishNode(e,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(t){if(this.isContextual("as")){t.specifiers||(t.specifiers=[]);const e=this.startNodeAt(this.state.lastTokStart,this.state.lastTokStartLoc);return this.next(),e.exported=this.parseIdentifier(!0),t.specifiers.push(this.finishNode(e,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(t){return!!this.match(n.braceL)&&(t.specifiers||(t.specifiers=[]),t.specifiers.push(...this.parseExportSpecifiers()),t.source=null,t.declaration=null,!0)}maybeParseExportDeclaration(t){if(this.shouldParseExportDeclaration()){if(this.isContextual("async")){const t=this.nextTokenStart();this.isUnparsedContextual(t,"function")||this.unexpected(t,n._function)}return t.specifiers=[],t.source=null,t.declaration=this.parseExportDeclaration(t),!0}return!1}isAsyncFunction(){if(!this.isContextual("async"))return!1;const t=this.nextTokenStart();return!o.test(this.input.slice(this.state.pos,t))&&this.isUnparsedContextual(t,"function")}parseExportDefaultExpression(){const t=this.startNode(),e=this.isAsyncFunction();if(this.match(n._function)||e)return this.next(),e&&this.next(),this.parseFunction(t,5,e);if(this.match(n._class))return this.parseClass(t,!0,!0);if(this.match(n.at))return this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")&&this.raise(this.state.start,f.DecoratorBeforeExport),this.parseDecorators(!1),this.parseClass(t,!0,!0);if(this.match(n._const)||this.match(n._var)||this.isLet())throw this.raise(this.state.start,f.UnsupportedDefaultExport);{const t=this.parseMaybeAssign();return this.semicolon(),t}}parseExportDeclaration(t){return this.parseStatement(null)}isExportDefaultSpecifier(){if(this.match(n.name))return"async"!==this.state.value&&"let"!==this.state.value;if(!this.match(n._default))return!1;const t=this.nextTokenStart();return 44===this.input.charCodeAt(t)||this.isUnparsedContextual(t,"from")}parseExportFrom(t,e){this.eatContextual("from")?(t.source=this.parseImportSource(),this.checkExport(t)):e?this.unexpected():t.source=null,this.semicolon()}shouldParseExportDeclaration(){if(this.match(n.at)&&(this.expectOnePlugin(["decorators","decorators-legacy"]),this.hasPlugin("decorators"))){if(!this.getPluginOption("decorators","decoratorsBeforeExport"))return!0;this.unexpected(this.state.start,f.DecoratorBeforeExport)}return"var"===this.state.type.keyword||"const"===this.state.type.keyword||"function"===this.state.type.keyword||"class"===this.state.type.keyword||this.isLet()||this.isAsyncFunction()}checkExport(t,e,s,i){if(e)if(s)this.checkDuplicateExports(t,"default");else if(t.specifiers&&t.specifiers.length)for(let e=0,s=t.specifiers;e<s.length;e++){const t=s[e];this.checkDuplicateExports(t,t.exported.name),!i&&t.local&&(this.checkReservedWord(t.local.name,t.local.start,!0,!1),this.scope.checkLocalExport(t.local))}else if(t.declaration)if("FunctionDeclaration"===t.declaration.type||"ClassDeclaration"===t.declaration.type){const e=t.declaration.id;if(!e)throw new Error("Assertion failure");this.checkDuplicateExports(t,e.name)}else if("VariableDeclaration"===t.declaration.type)for(let e=0,s=t.declaration.declarations;e<s.length;e++){const t=s[e];this.checkDeclaration(t.id)}if(this.state.decoratorStack[this.state.decoratorStack.length-1].length){const e=t.declaration&&("ClassDeclaration"===t.declaration.type||"ClassExpression"===t.declaration.type);if(!t.declaration||!e)throw this.raise(t.start,f.UnsupportedDecoratorExport);this.takeDecorators(t.declaration)}}checkDeclaration(t){if("Identifier"===t.type)this.checkDuplicateExports(t,t.name);else if("ObjectPattern"===t.type)for(let e=0,s=t.properties;e<s.length;e++){const t=s[e];this.checkDeclaration(t)}else if("ArrayPattern"===t.type)for(let e=0,s=t.elements;e<s.length;e++){const t=s[e];t&&this.checkDeclaration(t)}else"ObjectProperty"===t.type?this.checkDeclaration(t.value):"RestElement"===t.type?this.checkDeclaration(t.argument):"AssignmentPattern"===t.type&&this.checkDeclaration(t.left)}checkDuplicateExports(t,e){this.state.exportedIdentifiers.indexOf(e)>-1&&this.raise(t.start,"default"===e?f.DuplicateDefaultExport:f.DuplicateExport,e),this.state.exportedIdentifiers.push(e)}parseExportSpecifiers(){const t=[];let e=!0;for(this.expect(n.braceL);!this.eat(n.braceR);){if(e)e=!1;else if(this.expect(n.comma),this.eat(n.braceR))break;const s=this.startNode();s.local=this.parseIdentifier(!0),s.exported=this.eatContextual("as")?this.parseIdentifier(!0):s.local.__clone(),t.push(this.finishNode(s,"ExportSpecifier"))}return t}parseImport(t){if(t.specifiers=[],!this.match(n.string)){const e=!this.maybeParseDefaultImportSpecifier(t)||this.eat(n.comma),s=e&&this.maybeParseStarImportSpecifier(t);e&&!s&&this.parseNamedImportSpecifiers(t),this.expectContextual("from")}return t.source=this.parseImportSource(),this.semicolon(),this.finishNode(t,"ImportDeclaration")}parseImportSource(){return this.match(n.string)||this.unexpected(),this.parseExprAtom()}shouldParseDefaultImport(t){return this.match(n.name)}parseImportSpecifierLocal(t,e,s,i){e.local=this.parseIdentifier(),this.checkLVal(e.local,9,void 0,i),t.specifiers.push(this.finishNode(e,s))}maybeParseDefaultImportSpecifier(t){return!!this.shouldParseDefaultImport(t)&&(this.parseImportSpecifierLocal(t,this.startNode(),"ImportDefaultSpecifier","default import specifier"),!0)}maybeParseStarImportSpecifier(t){if(this.match(n.star)){const e=this.startNode();return this.next(),this.expectContextual("as"),this.parseImportSpecifierLocal(t,e,"ImportNamespaceSpecifier","import namespace specifier"),!0}return!1}parseNamedImportSpecifiers(t){let e=!0;for(this.expect(n.braceL);!this.eat(n.braceR);){if(e)e=!1;else{if(this.eat(n.colon))throw this.raise(this.state.start,f.DestructureNamedImport);if(this.expect(n.comma),this.eat(n.braceR))break}this.parseImportSpecifier(t)}}parseImportSpecifier(t){const e=this.startNode();e.imported=this.parseIdentifier(!0),this.eatContextual("as")?e.local=this.parseIdentifier():(this.checkReservedWord(e.imported.name,e.start,!0,!0),e.local=e.imported.__clone()),this.checkLVal(e.local,9,void 0,"import specifier"),t.specifiers.push(this.finishNode(e,"ImportSpecifier"))}}{constructor(t,e){super(t=function(t){const e={};for(let s=0,i=Object.keys(ut);s<i.length;s++){const r=i[s];e[r]=t&&null!=t[r]?t[r]:ut[r]}return e}(t),e);const s=this.getScopeHandler();this.options=t,this.inModule="module"===this.options.sourceType,this.scope=new s(this.raise.bind(this),this.inModule),this.prodParam=new tt,this.classScope=new Tt(this.raise.bind(this)),this.plugins=function(t){const e=new Map;for(let s=0;s<t.length;s++){const i=t[s],[r,a]=Array.isArray(i)?i:[i,{}];e.has(r)||e.set(r,a||{})}return e}(this.options.plugins),this.filename=t.sourceFilename}getScopeHandler(){return Y}parse(){let t=0;this.hasPlugin("topLevelAwait")&&this.inModule&&(t|=2),this.scope.enter(1),this.prodParam.enter(t);const e=this.startNode(),s=this.startNode();return this.nextToken(),e.errors=null,this.parseTopLevel(e,s),e.errors=this.state.errors,e}}function wt(t,e){let s=At;return t&&t.plugins&&(!function(t){if(at(t,"decorators")){if(at(t,"decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");const e=nt(t,"decorators","decoratorsBeforeExport");if(null==e)throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option, whose value must be a boolean. If you are migrating from Babylon/Babel 6 or want to use the old decorators proposal, you should use the 'decorators-legacy' plugin instead of 'decorators'.");if("boolean"!=typeof e)throw new Error("'decoratorsBeforeExport' must be a boolean.")}if(at(t,"flow")&&at(t,"typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(at(t,"placeholders")&&at(t,"v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(at(t,"pipelineOperator")&&!ot.includes(nt(t,"pipelineOperator","proposal")))throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: "+ot.map(t=>"'".concat(t,"'")).join(", "));if(at(t,"recordAndTuple")&&!ht.includes(nt(t,"recordAndTuple","syntaxType")))throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: "+ht.map(t=>"'".concat(t,"'")).join(", "))}(t.plugins),s=function(t){const e=ct.filter(e=>at(t,e)),s=e.join("/");let i=St[s];if(!i){i=At;for(let t=0;t<e.length;t++){const s=e[t];i=pt[s](i)}St[s]=i}return i}(t.plugins)),new s(t,e)}const St={};e.parse=function(t,e){if(!e||"unambiguous"!==e.sourceType)return wt(e,t).parse();e=Object.assign({},e);try{e.sourceType="module";const s=wt(e,t),i=s.parse();if(s.sawUnambiguousESM)return i;if(s.ambiguousScriptDifferentAst)try{return e.sourceType="script",wt(e,t).parse()}catch(t){}else i.program.sourceType="script";return i}catch(s){try{return e.sourceType="script",wt(e,t).parse()}catch(t){}throw s}},e.parseExpression=function(t,e){const s=wt(e,t);return s.options.strictMode&&(s.state.strict=!0),s.getExpression()},e.tokTypes=n}));s(Kt);Kt.parse,Kt.parseExpression,Kt.tokTypes;const{hasPragma:Jt}=c;function Xt(t=[]){return{sourceType:"module",allowAwaitOutsideFunction:!0,allowImportExportEverywhere:!0,allowReturnOutsideFunction:!0,allowSuperOutsideMethod:!0,allowUndeclaredExports:!0,errorRecovery:!0,createParenthesizedExpressions:!0,plugins:["doExpressions","objectRestSpread","classProperties","exportDefaultFrom","exportNamespaceFrom","asyncGenerators","functionBind","functionSent","dynamicImport","numericSeparator","importMeta","optionalCatchBinding","optionalChaining","classPrivateProperties",["pipelineOperator",{proposal:"minimal"}],"nullishCoalescingOperator","bigInt","throwExpressions","logicalAssignment","classPrivateMethods","v8intrinsic","partialApplication",["decorators",{decoratorsBeforeExport:!1}],...t]}}function Gt(t,...s){return(i,r,a)=>{const n=Kt;let o;try{o=function(t,e){let s;for(let i=0;i<e.length;i++)try{return t(e[i])}catch(t){s||(s=t)}throw s}(e=>n[t](i,e),s.map(Xt))}catch(t){throw e(t.message.replace(/ \(.*\)/,""),{start:{line:t.loc.line,column:t.loc.column+1}})}return delete o.tokens,Wt(o,Object.assign({},a,{originalText:i}))}}const Qt=Gt("parse",["jsx","flow"]),Yt=Gt("parse",["jsx",["flow",{all:!0,enums:!0}]]),$t=Gt("parse",["jsx","typescript"],["typescript"]),Zt=Gt("parseExpression",["jsx"]);function te(t,s){switch(t.type){case"ArrayExpression":return t.elements.forEach(i);case"ObjectExpression":return t.properties.forEach(i);case"ObjectProperty":if(t.computed)throw r("computed");if(t.shorthand)throw r("shorthand");return[t.key,t.value].forEach(i);case"UnaryExpression":switch(t.operator){case"+":case"-":return i(t.argument);default:throw r("operator")}case"Identifier":if(s&&"ObjectProperty"===s.type&&s.key===t)return;throw r();case"NullLiteral":case"BooleanLiteral":case"NumericLiteral":case"StringLiteral":return;default:throw r()}function i(e){return te(e,t)}function r(s){const i=s?"".concat(t.type," with ").concat(s,"=").concat(JSON.stringify(t[s])):t.type;return e("".concat(i," is not allowed in JSON."),{start:{line:t.loc.start.line,column:t.loc.start.column+1}})}}const ee=Object.assign({parse:Qt,astFormat:"estree",hasPragma:Jt},m),se=Object.assign({},ee,{parse:Yt}),ie=Object.assign({},ee,{parse:$t}),re=Object.assign({},ee,{parse:Zt});var ae={parsers:{babel:ee,"babel-flow":se,"babel-ts":ie,json:Object.assign({},re,{hasPragma:()=>!0}),json5:re,"json-stringify":Object.assign({parse:function(t,e,s){const i=Zt(t,e,s);return i.comments.forEach(te),te(i),i},astFormat:"estree-json"},m),__js_expression:re,__vue_expression:re,__vue_event_binding:ee}},ne=ae.parsers;t.default=ae,t.parsers=ne,Object.defineProperty(t,"__esModule",{value:!0})})); diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/parser-babylon.js.xml b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/parser-babel.js.xml similarity index 86% rename from bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/parser-babylon.js.xml rename to bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/parser-babel.js.xml index db27efa6eb..6e17694119 100644 --- a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/parser-babylon.js.xml +++ b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/parser-babel.js.xml @@ -12,7 +12,7 @@ </item> <item> <key> <string>__name__</string> </key> - <value> <string>parser-babylon.js</string> </value> + <value> <string>parser-babel.js</string> </value> </item> <item> <key> <string>content_type</string> </key> @@ -24,7 +24,7 @@ </item> <item> <key> <string>title</string> </key> - <value> <string>parser-babylon.js</string> </value> + <value> <string>parser-babel.js</string> </value> </item> </dictionary> </pickle> diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/standalone.js.js b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/standalone.js.js new file mode 100644 index 0000000000..a94c2e2ed1 --- /dev/null +++ b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/standalone.js.js @@ -0,0 +1,32923 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.prettier = factory()); +}(this, (function () { 'use strict'; + + var name = "prettier"; + var version = "2.0.5"; + var description = "Prettier is an opinionated code formatter"; + var bin = "./bin/prettier.js"; + var repository = "prettier/prettier"; + var homepage = "https://prettier.io"; + var author = "James Long"; + var license = "MIT"; + var main = "./index.js"; + var engines = { + node: ">=10.13.0" + }; + var dependencies = { + "@angular/compiler": "9.0.5", + "@babel/code-frame": "7.8.0", + "@babel/parser": "7.9.4", + "@glimmer/syntax": "0.50.0", + "@iarna/toml": "2.2.3", + "@typescript-eslint/typescript-estree": "2.26.0", + "angular-estree-parser": "1.3.0", + "angular-html-parser": "1.4.0", + camelcase: "5.3.1", + chalk: "4.0.0", + "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540", + "cjk-regex": "2.0.0", + cosmiconfig: "6.0.0", + dashify: "2.0.0", + dedent: "0.7.0", + diff: "4.0.2", + editorconfig: "0.15.3", + "editorconfig-to-prettier": "0.1.1", + "escape-string-regexp": "2.0.0", + esutils: "2.0.3", + "fast-glob": "3.2.2", + "find-parent-dir": "0.3.0", + "find-project-root": "1.1.1", + "flow-parser": "0.122.0", + "get-stream": "5.1.0", + globby: "11.0.0", + graphql: "15.0.0", + "html-element-attributes": "2.2.1", + "html-styles": "1.0.0", + "html-tag-names": "1.1.5", + ignore: "4.0.6", + "jest-docblock": "25.2.6", + "json-stable-stringify": "1.0.1", + leven: "3.1.0", + "lines-and-columns": "1.1.6", + "linguist-languages": "7.9.0", + lodash: "4.17.15", + mem: "6.0.1", + minimatch: "3.0.4", + minimist: "1.2.5", + "n-readlines": "1.0.0", + "please-upgrade-node": "3.2.0", + "postcss-less": "3.1.4", + "postcss-media-query-parser": "0.2.3", + "postcss-scss": "2.0.0", + "postcss-selector-parser": "2.2.3", + "postcss-values-parser": "2.0.1", + "regexp-util": "1.2.2", + "remark-math": "1.0.6", + "remark-parse": "5.0.0", + resolve: "1.16.1", + semver: "7.1.3", + srcset: "2.0.1", + "string-width": "4.2.0", + typescript: "3.8.3", + "unicode-regex": "3.0.0", + unified: "9.0.0", + vnopts: "1.0.2", + "yaml-unist-parser": "1.1.1" + }; + var devDependencies = { + "@babel/core": "7.9.0", + "@babel/preset-env": "7.9.0", + "@rollup/plugin-alias": "3.0.1", + "@rollup/plugin-commonjs": "11.0.2", + "@rollup/plugin-json": "4.0.2", + "@rollup/plugin-node-resolve": "7.1.1", + "@rollup/plugin-replace": "2.3.1", + "babel-loader": "8.1.0", + benchmark: "2.1.4", + "builtin-modules": "3.1.0", + codecov: "3.6.5", + "cross-env": "7.0.2", + cspell: "4.0.55", + eslint: "6.8.0", + "eslint-config-prettier": "6.10.1", + "eslint-formatter-friendly": "7.0.0", + "eslint-plugin-import": "2.20.2", + "eslint-plugin-prettier": "3.1.2", + "eslint-plugin-react": "7.19.0", + "eslint-plugin-unicorn": "18.0.1", + execa: "4.0.0", + jest: "25.2.7", + "jest-snapshot-serializer-ansi": "1.0.0", + "jest-snapshot-serializer-raw": "1.1.0", + "jest-watch-typeahead": "0.5.0", + prettier: "2.0.4", + rimraf: "3.0.2", + rollup: "2.3.2", + "rollup-plugin-babel": "4.4.0", + "rollup-plugin-node-globals": "1.4.0", + "rollup-plugin-terser": "5.3.0", + shelljs: "0.8.3", + "snapshot-diff": "0.7.0", + "strip-ansi": "6.0.0", + "synchronous-promise": "2.0.10", + tempy: "0.5.0", + "terser-webpack-plugin": "2.3.5", + webpack: "4.42.1" + }; + var scripts = { + prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1", + "prepare-release": "yarn && yarn build && yarn test:dist", + test: "jest", + "test:dist": "cross-env NODE_ENV=production jest", + "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest tests/", + "test:integration": "jest tests_integration", + "perf:repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf:repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf:benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "lint:typecheck": "tsc", + "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly", + "lint:changelog": "node ./scripts/lint-changelog.js", + "lint:prettier": "prettier \"**/*.{md,json,yml,html,css}\" --check", + "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"", + "lint:spellcheck": "cspell {bin,scripts,src,website}/**/*.js {docs,website/blog,changelog_unreleased}/**/*.md", + "lint:deps": "node ./scripts/check-deps.js", + build: "node --max-old-space-size=3072 ./scripts/build/build.js", + "build-docs": "node ./scripts/build-docs.js" + }; + var _package = { + name: name, + version: version, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + engines: engines, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts + }; + + var _package$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name, + version: version, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + engines: engines, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts, + 'default': _package + }); + + function Diff() {} + + Diff.prototype = { + diff: function diff(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(''); + }, + join: function join(chars) { + return chars.join(''); + } + }; + + function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; + } + + function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; + } + + var characterDiff = new Diff(); + + function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); + } + + function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; + } // + // Ranges and exceptions: + // Latin-1 Supplement, 0080–00FF + // - U+00D7 × Multiplication sign + // - U+00F7 ÷ Division sign + // Latin Extended-A, 0100–017F + // Latin Extended-B, 0180–024F + // IPA Extensions, 0250–02AF + // Spacing Modifier Letters, 02B0–02FF + // - U+02C7 ˇ ˇ Caron + // - U+02D8 ˘ ˘ Breve + // - U+02D9 Ë™ ˙ Dot Above + // - U+02DA Ëš ˚ Ring Above + // - U+02DB Ë› ˛ Ogonek + // - U+02DC Ëœ ˜ Small Tilde + // - U+02DD Ë ˝ Double Acute Accent + // Latin Extended Additional, 1E00–1EFF + + + var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; + var reWhitespace = /\S/; + var wordDiff = new Diff(); + + wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); + }; + + wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; + }; + + function diffWords(oldStr, newStr, options) { + options = generateOptions(options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); + } + + function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); + } + + var lineDiff = new Diff(); + + lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; + }; + + function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); + } + + function diffTrimmedLines(oldStr, newStr, callback) { + var options = generateOptions(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); + } + + var sentenceDiff = new Diff(); + + sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); + }; + + function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); + } + + var cssDiff = new Diff(); + + cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); + }; + + function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); + } + + function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function _typeof(obj) { + return typeof obj; + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } + } + + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); + } + + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); + } + + var objectPrototypeToString = Object.prototype.toString; + var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a + // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + + jsonDiff.useLongestToken = true; + jsonDiff.tokenize = lineDiff.tokenize; + + jsonDiff.castInput = function (value) { + var _this$options = this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { + return typeof v === 'undefined' ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); + }; + + jsonDiff.equals = function (left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); + }; + + function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); + } // This function handles the presence of circular references by bailing out when encountering an + // object that is already on the "stack" of items being processed. Accepts an optional replacer + + + function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if (_typeof(obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; + } + + var arrayDiff = new Diff(); + + arrayDiff.tokenize = function (value) { + return value.slice(); + }; + + arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; + }; + + function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); + } + + function parsePatch(uniDiff) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + + if (header) { + index.index = header[1]; + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); + + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + var data = fileHeader[2].split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; + } // Iterator that traverses in the range of [min, max], stepping + // by distance from a given start position. I.e. for [0, 4], with + // start of 2, this will iterate 2, 3, 1, 4, 0. + + + function distanceIterator(start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; + } + + function applyPatch(source, uniDiff) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { + return line === patchContent; + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = distanceIterator(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); + } // Wrapper that supports multiple file patches via callbacks. + + + function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); + } + + function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = diffLines(oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + var _loop = function _loop(i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + var _curRange; // If we have previous context, start with that + + + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + var _curRange2; // Overlapping + + + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; // end the range and output + + + var contextSize = Math.min(lines.length, options.context); + + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + _loop(i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; + } + + function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; + } + + function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); + } + + function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); + } + + function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; + } + + function calcLineCount(hunk) { + var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } + } + + function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; + } + + function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return parsePatch(param)[0]; + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return structuredPatch(undefined, undefined, base, param); + } + + return param; + } + + function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; + } + + function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } + } + + function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; + } + + function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; + } + + function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + var _hunk$lines; // Mine inserted + + + (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + var _hunk$lines2; // Theirs inserted + + + (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); + } + + function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + var _hunk$lines3; + + (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); + + return; + } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + var _hunk$lines4; + + (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); + + return; + } + } else if (arrayEqual(myChanges, theirChanges)) { + var _hunk$lines5; + + (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); + } + + function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + var _hunk$lines6; + + (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } + } + + function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); + } + + function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } + } + + function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } + } + + function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; + } + + function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; + } + + function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); + } + + function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; + } + + function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; + } // See: http://code.google.com/p/google-diff-match-patch/wiki/API + + + function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; + } + + function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push('<ins>'); + } else if (change.removed) { + ret.push('<del>'); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push('</ins>'); + } else if (change.removed) { + ret.push('</del>'); + } + } + + return ret.join(''); + } + + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(/</g, '<'); + n = n.replace(/>/g, '>'); + n = n.replace(/"/g, '"'); + return n; + } + + var index_es6 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Diff: Diff, + diffChars: diffChars, + diffWords: diffWords, + diffWordsWithSpace: diffWordsWithSpace, + diffLines: diffLines, + diffTrimmedLines: diffTrimmedLines, + diffSentences: diffSentences, + diffCss: diffCss, + diffJson: diffJson, + diffArrays: diffArrays, + structuredPatch: structuredPatch, + createTwoFilesPatch: createTwoFilesPatch, + createPatch: createPatch, + applyPatch: applyPatch, + applyPatches: applyPatches, + parsePatch: parsePatch, + merge: merge, + convertChangesToDMP: convertChangesToDMP, + convertChangesToXML: convertChangesToXML, + canonicalize: canonicalize + }); + + var _shim_fs = {}; + + var _shim_fs$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _shim_fs + }); + + const sep = /[\\/]/; + function extname(path) { + const filename = basename(path); + const dotIndex = filename.lastIndexOf("."); + if (dotIndex === -1) return ""; + return filename.slice(dotIndex); + } + function basename(path) { + return path.split(sep).pop(); + } + function isAbsolute() { + return true; + } + + var path = /*#__PURE__*/Object.freeze({ + __proto__: null, + extname: extname, + basename: basename, + isAbsolute: isAbsolute + }); + + var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + + function init() { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray(b64) { + if (!inited) { + init(); + } + + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4'); + } // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + + + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data + + arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars + + l = placeHolders > 0 ? len - 4 : len; + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = tmp >> 16 & 0xFF; + arr[L++] = tmp >> 8 & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[L++] = tmp >> 8 & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr; + } + + function tripletToBase64(num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; + } + + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; + output.push(tripletToBase64(tmp)); + } + + return output.join(''); + } + + function fromByteArray(uint8) { + if (!inited) { + init(); + } + + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + // go through the array every three bytes, we'll deal with trailing stuff later + + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } // pad the end with zeros, but make sure to not forget the extra bytes + + + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[tmp << 4 & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + output += lookup[tmp >> 10]; + output += lookup[tmp >> 4 & 0x3F]; + output += lookup[tmp << 2 & 0x3F]; + output += '='; + } + + parts.push(output); + return parts.join(''); + } + + function read(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + } + function write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = e << mLen | m; + eLen += mLen; + + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; + + function kMaxLength() { + return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; + } + + function createBuffer(that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length'); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + + that.length = length; + } + + return that; + } + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + + function Buffer(arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length); + } // Common case. + + + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error('If encoding is specified then the first argument must be a string'); + } + + return allocUnsafe(this, arg); + } + + return from(this, arg, encodingOrOffset, length); + } + Buffer.poolSize = 8192; // not used by this implementation + // TODO: Legacy, not needed anymore. Remove in next major version. + + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr; + }; + + function from(that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length); + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset); + } + + return fromObject(that, value); + } + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + + + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length); + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + } + + function assertSize(size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number'); + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative'); + } + } + + function alloc(that, size, fill, encoding) { + assertSize(size); + + if (size <= 0) { + return createBuffer(that, size); + } + + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill); + } + + return createBuffer(that, size); + } + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + + + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding); + }; + + function allocUnsafe(that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + + return that; + } + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + + + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size); + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + + + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size); + }; + + function fromString(that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that; + } + + function fromArrayLike(that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + + return that; + } + + function fromArrayBuffer(that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds'); + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds'); + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + + return that; + } + + function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that; + } + + obj.copy(that, 0, 0, len); + return that; + } + + if (obj) { + if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0); + } + + return fromArrayLike(that, obj); + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data); + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.'); + } + + function checked(length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes'); + } + + return length | 0; + } + Buffer.isBuffer = isBuffer; + + function internalIsBuffer(b) { + return !!(b != null && b._isBuffer); + } + + Buffer.compare = function compare(a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers'); + } + + if (a === b) return 0; + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + + Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true; + + default: + return false; + } + }; + + Buffer.concat = function concat(list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + + if (list.length === 0) { + return Buffer.alloc(0); + } + + var i; + + if (length === undefined) { + length = 0; + + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + + buf.copy(buffer, pos); + pos += buf.length; + } + + return buffer; + }; + + function byteLength(string, encoding) { + if (internalIsBuffer(string)) { + return string.length; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength; + } + + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0; // Use a for loop to avoid recursion + + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len; + + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length; + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2; + + case 'hex': + return len >>> 1; + + case 'base64': + return base64ToBytes(string).length; + + default: + if (loweredCase) return utf8ToBytes(string).length; // assume utf8 + + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + + Buffer.byteLength = byteLength; + + function slowToString(encoding, start, end) { + var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + + if (start === undefined || start < 0) { + start = 0; + } // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + + + if (start > this.length) { + return ''; + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return ''; + } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + + + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return ''; + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end); + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end); + + case 'ascii': + return asciiSlice(this, start, end); + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end); + + case 'base64': + return base64Slice(this, start, end); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + + + Buffer.prototype._isBuffer = true; + + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16() { + var len = this.length; + + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits'); + } + + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + + return this; + }; + + Buffer.prototype.swap32 = function swap32() { + var len = this.length; + + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits'); + } + + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + + return this; + }; + + Buffer.prototype.swap64 = function swap64() { + var len = this.length; + + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits'); + } + + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + + return this; + }; + + Buffer.prototype.toString = function toString() { + var length = this.length | 0; + if (length === 0) return ''; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + + Buffer.prototype.equals = function equals(b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer'); + if (this === b) return true; + return Buffer.compare(this, b) === 0; + }; + + Buffer.prototype.inspect = function inspect() { + var str = ''; + var max = INSPECT_MAX_BYTES; + + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + + return '<Buffer ' + str + '>'; + }; + + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer'); + } + + if (start === undefined) { + start = 0; + } + + if (end === undefined) { + end = target ? target.length : 0; + } + + if (thisStart === undefined) { + thisStart = 0; + } + + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index'); + } + + if (thisStart >= thisEnd && start >= end) { + return 0; + } + + if (thisStart >= thisEnd) { + return -1; + } + + if (start >= end) { + return 1; + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + + + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1; // Normalize byteOffset + + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + + byteOffset = +byteOffset; // Coerce to Number. + + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } // Normalize byteOffset: negative offsets start from the end of the buffer + + + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + + if (byteOffset >= buffer.length) { + if (dir) return -1;else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0;else return -1; + } // Normalize val + + + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } // Finally, search either indexOf (if dir is true) or lastIndexOf + + + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1; + } + + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + + if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + + throw new TypeError('val must be string, number or Buffer'); + } + + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + + if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1; + } + + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } + + var i; + + if (dir) { + var foundIndex = -1; + + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + + for (i = byteOffset; i >= 0; i--) { + var found = true; + + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + + if (found) return i; + } + } + + return -1; + } + + Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + + Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + + if (!length) { + length = remaining; + } else { + length = Number(length); + + if (length > remaining) { + length = remaining; + } + } // must be an even number of digits + + + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string'); + + if (length > strLen / 2) { + length = strLen / 2; + } + + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i; + buf[offset + i] = parsed; + } + + return i; + } + + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + } + + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } + + function latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length); + } + + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } + + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); + } + + Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } // legacy write(string, encoding, offset, length) - remove in v0.13 + + } else { + throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds'); + } + + if (!encoding) encoding = 'utf8'; + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length); + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length); + + case 'ascii': + return asciiWrite(this, string, offset, length); + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length); + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON() { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf); + } else { + return fromByteArray(buf.slice(start, end)); + } + } + + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + var i = start; + + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + + break; + + case 2: + secondByte = buf[i + 1]; + + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; + + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + + break; + + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; + + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + + break; + + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; + + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res); + } // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + + + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } // Decode in chunks to avoid "call stack size exceeded". + + + var res = ''; + var i = 0; + + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); + } + + return res; + } + + function asciiSlice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + + return ret; + } + + function latin1Slice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + + return ret; + } + + function hexSlice(buf, start, end) { + var len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + var out = ''; + + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + + return out; + } + + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + + return res; + } + + Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + var newBuf; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf; + }; + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + + + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); + } + + Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val; + }; + + Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val; + }; + + Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + + Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + + Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + + Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return this[offset]; + return (0xff - this[offset] + 1) * -1; + }; + + Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | this[offset + 1] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; + }; + + Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | this[offset] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; + }; + + Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + + Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + + Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4); + }; + + Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4); + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8); + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8); + }; + + function checkInt(buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + } + + Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = value & 0xff; + return offset + 1; + }; + + function objectWriteUInt16(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + + return offset + 2; + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + + return offset + 2; + }; + + function objectWriteUInt32(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, true); + } + + return offset + 4; + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + + return offset + 4; + }; + + Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + + return offset + 2; + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + + return offset + 2; + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + } else { + objectWriteUInt32(this, value, offset, true); + } + + return offset + 4; + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + + return offset + 4; + }; + + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + if (offset < 0) throw new RangeError('Index out of range'); + } + + function writeFloat(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + + Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + + function writeDouble(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + + + Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done + + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions + + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds'); + } + + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds'); + if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? + + if (end > this.length) end = this.length; + + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); + } + + return len; + }; // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + + + Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + + if (val.length === 1) { + var code = val.charCodeAt(0); + + if (code < 256) { + val = code; + } + } + + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string'); + } + + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + } else if (typeof val === 'number') { + val = val & 255; + } // Invalid ranges are not set to a default, so can range check early. + + + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index'); + } + + if (end <= start) { + return this; + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + if (!val) val = 0; + var i; + + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this; + }; // HELPER FUNCTIONS + // ================ + + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean(str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' + + if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + + while (str.length % 4 !== 0) { + str = str + '='; + } + + return str; + } + + function stringtrim(str) { + if (str.trim) return str.trim(); + return str.replace(/^\s+|\s+$/g, ''); + } + + function toHex(n) { + if (n < 16) return '0' + n.toString(16); + return n.toString(16); + } + + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); // is surrogate component + + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } // valid lead + + + leadSurrogate = codePoint; + continue; + } // 2 leads in a row + + + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue; + } // valid surrogate pair + + + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; // encode utf8 + + if (codePoint < 0x80) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break; + bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break; + bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break; + bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else { + throw new Error('Invalid code point'); + } + } + + return bytes; + } + + function asciiToBytes(str) { + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + + return byteArray; + } + + function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray; + } + + function base64ToBytes(str) { + return toByteArray(base64clean(str)); + } + + function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + + return i; + } + + function isnan(val) { + return val !== val; // eslint-disable-line no-self-compare + } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + + + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)); + } + + function isFastBuffer(obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj); + } // For Node v0.10 support. Remove this eventually. + + + function isSlowBuffer(obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)); + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } + + var fs = getCjsExportFromNamespace(_shim_fs$1); + + /** + * @class + */ + + + class LineByLine { + constructor(file, options) { + options = options || {}; + if (!options.readChunk) options.readChunk = 1024; + + if (!options.newLineCharacter) { + options.newLineCharacter = 0x0a; //linux line ending + } else { + options.newLineCharacter = options.newLineCharacter.charCodeAt(0); + } + + if (typeof file === 'number') { + this.fd = file; + } else { + this.fd = fs.openSync(file, 'r'); + } + + this.options = options; + this.newLineCharacter = options.newLineCharacter; + this.reset(); + } + + _searchInBuffer(buffer, hexNeedle) { + let found = -1; + + for (let i = 0; i <= buffer.length; i++) { + let b_byte = buffer[i]; + + if (b_byte === hexNeedle) { + found = i; + break; + } + } + + return found; + } + + reset() { + this.eofReached = false; + this.linesCache = []; + this.fdPosition = 0; + } + + close() { + fs.closeSync(this.fd); + this.fd = null; + } + + _extractLines(buffer) { + let line; + const lines = []; + let bufferPosition = 0; + let lastNewLineBufferPosition = 0; + + while (true) { + let bufferPositionValue = buffer[bufferPosition++]; + + if (bufferPositionValue === this.newLineCharacter) { + line = buffer.slice(lastNewLineBufferPosition, bufferPosition); + lines.push(line); + lastNewLineBufferPosition = bufferPosition; + } else if (!bufferPositionValue) { + break; + } + } + + let leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition); + + if (leftovers.length) { + lines.push(leftovers); + } + + return lines; + } + + _readChunk(lineLeftovers) { + let totalBytesRead = 0; + let bytesRead; + const buffers = []; + + do { + const readBuffer = new Buffer(this.options.readChunk); + bytesRead = fs.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition); + totalBytesRead = totalBytesRead + bytesRead; + this.fdPosition = this.fdPosition + bytesRead; + buffers.push(readBuffer); + } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1); + + let bufferData = Buffer.concat(buffers); + + if (bytesRead < this.options.readChunk) { + this.eofReached = true; + bufferData = bufferData.slice(0, totalBytesRead); + } + + if (totalBytesRead) { + this.linesCache = this._extractLines(bufferData); + + if (lineLeftovers) { + this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]); + } + } + + return totalBytesRead; + } + + next() { + if (!this.fd) return false; + let line = false; + + if (this.eofReached && this.linesCache.length === 0) { + return line; + } + + let bytesRead; + + if (!this.linesCache.length) { + bytesRead = this._readChunk(); + } + + if (this.linesCache.length) { + line = this.linesCache.shift(); + const lastLineCharacter = line[line.length - 1]; + + if (lastLineCharacter !== 0x0a) { + bytesRead = this._readChunk(line); + + if (bytesRead) { + line = this.linesCache.shift(); + } + } + } + + if (this.eofReached && this.linesCache.length === 0) { + this.close(); + } + + if (line && line[line.length - 1] === this.newLineCharacter) { + line = line.slice(0, line.length - 1); + } + + return line; + } + + } + + var readlines = LineByLine; + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + + return result; + } + + var fromPairs_1 = fromPairs; + + class ConfigError extends Error {} + + class DebugError extends Error {} + + class UndefinedParserError extends Error {} + + var errors = { + ConfigError, + DebugError, + UndefinedParserError + }; + + function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; + } + + function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); + } + + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + + function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined'); + } + + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } // if setTimeout wasn't available but was latter defined + + + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + } + + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } // if clearTimeout wasn't available but was latter defined + + + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + } + + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + + draining = false; + + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + + while (len) { + currentQueue = queue; + queue = []; + + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + + queueIndex = -1; + len = queue.length; + } + + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + function nextTick(fun) { + var args = new Array(arguments.length - 1); + + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + + queue.push(new Item(fun, args)); + + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } // v8 likes predictible objects + + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version$1 = ''; // empty string to avoid regexp issues + + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + function binding(name) { + throw new Error('process.binding is not supported'); + } + function cwd() { + return '/'; + } + function chdir(dir) { + throw new Error('process.chdir is not supported'); + } + function umask() { + return 0; + } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + + var performance = global$1.performance || {}; + + var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { + return new Date().getTime(); + }; // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + + + function hrtime(previousTimestamp) { + var clocktime = performanceNow.call(performance) * 1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor(clocktime % 1 * 1e9); + + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + + if (nanoseconds < 0) { + seconds--; + nanoseconds += 1e9; + } + } + + return [seconds, nanoseconds]; + } + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version$1, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {}; + var debug_1 = debug; + + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; + const MAX_LENGTH = 256; + const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ + 9007199254740991; // Max safe segment length for coercion. + + const MAX_SAFE_COMPONENT_LENGTH = 16; + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH, + MAX_SAFE_INTEGER, + MAX_SAFE_COMPONENT_LENGTH + }; + + var re_1 = createCommonjsModule(function (module, exports) { + const { + MAX_SAFE_COMPONENT_LENGTH + } = constants; + exports = module.exports = {}; // The actual regexps go on exports.re + + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug_1(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")")); + createToken('MAINVERSIONLOOSE', "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")")); // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', "(?:".concat(src[t.NUMERICIDENTIFIER], "|").concat(src[t.NONNUMERICIDENTIFIER], ")")); + createToken('PRERELEASEIDENTIFIERLOOSE', "(?:".concat(src[t.NUMERICIDENTIFIERLOOSE], "|").concat(src[t.NONNUMERICIDENTIFIER], ")")); // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', "(?:-(".concat(src[t.PRERELEASEIDENTIFIER], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIER], ")*))")); + createToken('PRERELEASELOOSE', "(?:-?(".concat(src[t.PRERELEASEIDENTIFIERLOOSE], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIERLOOSE], ")*))")); // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', "(?:\\+(".concat(src[t.BUILDIDENTIFIER], "(?:\\.").concat(src[t.BUILDIDENTIFIER], ")*))")); // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', "v?".concat(src[t.MAINVERSION]).concat(src[t.PRERELEASE], "?").concat(src[t.BUILD], "?")); + createToken('FULL', "^".concat(src[t.FULLPLAIN], "$")); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + + createToken('LOOSEPLAIN', "[v=\\s]*".concat(src[t.MAINVERSIONLOOSE]).concat(src[t.PRERELEASELOOSE], "?").concat(src[t.BUILD], "?")); + createToken('LOOSE', "^".concat(src[t.LOOSEPLAIN], "$")); + createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + + createToken('XRANGEIDENTIFIERLOOSE', "".concat(src[t.NUMERICIDENTIFIERLOOSE], "|x|X|\\*")); + createToken('XRANGEIDENTIFIER', "".concat(src[t.NUMERICIDENTIFIER], "|x|X|\\*")); + createToken('XRANGEPLAIN', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:".concat(src[t.PRERELEASE], ")?").concat(src[t.BUILD], "?") + ")?)?"); + createToken('XRANGEPLAINLOOSE', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:".concat(src[t.PRERELEASELOOSE], ")?").concat(src[t.BUILD], "?") + ")?)?"); + createToken('XRANGE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAIN], "$")); + createToken('XRANGELOOSE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAINLOOSE], "$")); // Coercion. + // Extract anything that could conceivably be a part of a valid semver + + createToken('COERCE', "".concat('(^|[^\\d])' + '(\\d{1,').concat(MAX_SAFE_COMPONENT_LENGTH, "})") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:$|[^\\d])"); + createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges. + // Meaning is "reasonably at or greater than" + + createToken('LONETILDE', '(?:~>?)'); + createToken('TILDETRIM', "(\\s*)".concat(src[t.LONETILDE], "\\s+"), true); + exports.tildeTrimReplace = '$1~'; + createToken('TILDE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAIN], "$")); + createToken('TILDELOOSE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAINLOOSE], "$")); // Caret ranges. + // Meaning is "at least and backwards compatible with" + + createToken('LONECARET', '(?:\\^)'); + createToken('CARETTRIM', "(\\s*)".concat(src[t.LONECARET], "\\s+"), true); + exports.caretTrimReplace = '$1^'; + createToken('CARET', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAIN], "$")); + createToken('CARETLOOSE', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAINLOOSE], "$")); // A simple gt/lt/eq thing, or just "" to indicate "any version" + + createToken('COMPARATORLOOSE', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], ")$|^$")); + createToken('COMPARATOR', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.FULLPLAIN], ")$|^$")); // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + + createToken('COMPARATORTRIM', "(\\s*)".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], "|").concat(src[t.XRANGEPLAIN], ")"), true); + exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + + createToken('HYPHENRANGE', "^\\s*(".concat(src[t.XRANGEPLAIN], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAIN], ")") + "\\s*$"); + createToken('HYPHENRANGELOOSE', "^\\s*(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s*$"); // Star ranges basically just allow anything at all. + + createToken('STAR', '(<|>)?=?\\s*\\*'); + }); + var re_2 = re_1.re; + var re_3 = re_1.src; + var re_4 = re_1.t; + var re_5 = re_1.tildeTrimReplace; + var re_6 = re_1.caretTrimReplace; + var re_7 = re_1.comparatorTrimReplace; + + const numeric = /^[0-9]+$/; + + const compareIdentifiers = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + }; + + const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); + + var identifiers = { + compareIdentifiers, + rcompareIdentifiers + }; + + const { + MAX_LENGTH: MAX_LENGTH$1, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1 + } = constants; + const { + re, + t + } = re_1; + const { + compareIdentifiers: compareIdentifiers$1 + } = identifiers; + + class SemVer { + constructor(version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError("Invalid Version: ".concat(version)); + } + + if (version.length > MAX_LENGTH$1) { + throw new TypeError("version is longer than ".concat(MAX_LENGTH$1, " characters")); + } + + debug_1('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + + this.includePrerelease = !!options.includePrerelease; + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); + + if (!m) { + throw new TypeError("Invalid Version: ".concat(version)); + } + + this.raw = version; // these are actually numbers + + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) { + throw new TypeError('Invalid major version'); + } + + if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) { + throw new TypeError('Invalid minor version'); + } + + if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) { + throw new TypeError('Invalid patch version'); + } // numberify any prerelease numeric ids + + + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map(id => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + + if (num >= 0 && num < MAX_SAFE_INTEGER$1) { + return num; + } + } + + return id; + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format() { + this.version = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); + + if (this.prerelease.length) { + this.version += "-".concat(this.prerelease.join('.')); + } + + return this.version; + } + + toString() { + return this.version; + } + + compare(other) { + debug_1('SemVer.compare', this.version, this.options, other); + + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0; + } + + other = new SemVer(other, this.options); + } + + if (other.version === this.version) { + return 0; + } + + return this.compareMain(other) || this.comparePre(other); + } + + compareMain(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + + return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch); + } + + comparePre(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } // NOT having a prerelease is > having one + + + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + + let i = 0; + + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug_1('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers$1(a, b); + } + } while (++i); + } + + compareBuild(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + + let i = 0; + + do { + const a = this.build[i]; + const b = other.build[i]; + debug_1('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers$1(a, b); + } + } while (++i); + } // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + + + inc(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + + this.patch = 0; + this.prerelease = []; + break; + + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + + break; + + default: + throw new Error("invalid increment argument: ".concat(release)); + } + + this.format(); + this.raw = this.version; + return this; + } + + } + + var semver = SemVer; + + const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose)); + + var compare_1 = compare; + + const lt = (a, b, loose) => compare_1(a, b, loose) < 0; + + var lt_1 = lt; + + const gte = (a, b, loose) => compare_1(a, b, loose) >= 0; + + var gte_1 = gte; + + var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({ + [keyName]: key + }, value)); + + var dedent_1 = createCommonjsModule(function (module) { + + function dedent(strings) { + var raw = void 0; + + if (typeof strings === "string") { + // dedent can be used as a plain function + raw = [strings]; + } else { + raw = strings.raw; + } // first, perform interpolation + + + var result = ""; + + for (var i = 0; i < raw.length; i++) { + result += raw[i]. // join lines when there is a suppressed newline + replace(/\\\n[ \t]*/g, ""). // handle escaped backticks + replace(/\\`/g, "`"); + + if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) { + result += arguments.length <= i + 1 ? undefined : arguments[i + 1]; + } + } // now strip indentation + + + var lines = result.split("\n"); + var mindent = null; + lines.forEach(function (l) { + var m = l.match(/^(\s+)\S+/); + + if (m) { + var indent = m[1].length; + + if (!mindent) { + // this is the first indented line + mindent = indent; + } else { + mindent = Math.min(mindent, indent); + } + } + }); + + if (mindent !== null) { + result = lines.map(function (l) { + return l[0] === " " ? l.slice(mindent) : l; + }).join("\n"); + } // dedent eats leading and trailing whitespace too + + + result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too + + return result.replace(/\\n/g, "\n"); + } + + { + module.exports = dedent; + } + }); + + function _templateObject6() { + const data = _taggedTemplateLiteral(["\n Require either '@prettier' or '@format' to be present in the file's first docblock comment\n in order for it to be formatted.\n "]); + + _templateObject6 = function _templateObject6() { + return data; + }; + + return data; + } + + function _templateObject5() { + const data = _taggedTemplateLiteral(["\n Format code starting at a given character offset.\n The range will extend backwards to the start of the first line containing the selected statement.\n This option cannot be used with --cursor-offset.\n "]); + + _templateObject5 = function _templateObject5() { + return data; + }; + + return data; + } + + function _templateObject4() { + const data = _taggedTemplateLiteral(["\n Format code ending at a given character offset (exclusive).\n The range will extend forwards to the end of the selected statement.\n This option cannot be used with --cursor-offset.\n "]); + + _templateObject4 = function _templateObject4() { + return data; + }; + + return data; + } + + function _templateObject3() { + const data = _taggedTemplateLiteral(["\n Custom directory that contains prettier plugins in node_modules subdirectory.\n Overrides default behavior when plugins are searched relatively to the location of Prettier.\n Multiple values are accepted.\n "]); + + _templateObject3 = function _templateObject3() { + return data; + }; + + return data; + } + + function _templateObject2() { + const data = _taggedTemplateLiteral(["\n Maintain existing\n (mixed values within one file are normalised by looking at what's used after the first line)\n "]); + + _templateObject2 = function _templateObject2() { + return data; + }; + + return data; + } + + function _templateObject() { + const data = _taggedTemplateLiteral(["\n Print (to stderr) where a cursor at the given position would move to after formatting.\n This option cannot be used with --range-start and --range-end.\n "]); + + _templateObject = function _templateObject() { + return data; + }; + + return data; + } + + const CATEGORY_CONFIG = "Config"; + const CATEGORY_EDITOR = "Editor"; + const CATEGORY_FORMAT = "Format"; + const CATEGORY_OTHER = "Other"; + const CATEGORY_OUTPUT = "Output"; + const CATEGORY_GLOBAL = "Global"; + const CATEGORY_SPECIAL = "Special"; + /** + * @typedef {Object} OptionInfo + * @property {string} [since] - available since version + * @property {string} category + * @property {'int' | 'boolean' | 'choice' | 'path'} type + * @property {boolean} [array] - indicate it's an array of the specified type + * @property {OptionValueInfo} [default] + * @property {OptionRangeInfo} [range] - for type int + * @property {string} description + * @property {string} [deprecated] - deprecated since version + * @property {OptionRedirectInfo} [redirect] - redirect deprecated option + * @property {(value: any) => boolean} [exception] + * @property {OptionChoiceInfo[]} [choices] - for type choice + * @property {string} [cliName] + * @property {string} [cliCategory] + * @property {string} [cliDescription] + * + * @typedef {number | boolean | string} OptionValue + * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo + * + * @typedef {Object} OptionRedirectInfo + * @property {string} option + * @property {OptionValue} value + * + * @typedef {Object} OptionRangeInfo + * @property {number} start - recommended range start + * @property {number} end - recommended range end + * @property {number} step - recommended range step + * + * @typedef {Object} OptionChoiceInfo + * @property {boolean | string} value - boolean for the option that is originally boolean type + * @property {string} description + * @property {string} [since] - undefined if available since the first version of the option + * @property {string} [deprecated] - deprecated since version + * @property {OptionValueInfo} [redirect] - redirect deprecated value + */ + + /** @type {{ [name: string]: OptionInfo }} */ + + const options = { + cursorOffset: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: -1, + range: { + start: -1, + end: Infinity, + step: 1 + }, + description: dedent_1(_templateObject()), + cliCategory: CATEGORY_EDITOR + }, + endOfLine: { + since: "1.15.0", + category: CATEGORY_GLOBAL, + type: "choice", + default: [{ + since: "1.15.0", + value: "auto" + }, { + since: "2.0.0", + value: "lf" + }], + description: "Which end of line characters to apply.", + choices: [{ + value: "lf", + description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos" + }, { + value: "crlf", + description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows" + }, { + value: "cr", + description: "Carriage Return character only (\\r), used very rarely" + }, { + value: "auto", + description: dedent_1(_templateObject2()) + }] + }, + filepath: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "path", + description: "Specify the input filepath. This will be used to do parser inference.", + cliName: "stdin-filepath", + cliCategory: CATEGORY_OTHER, + cliDescription: "Path to the file to pretend that stdin comes from." + }, + insertPragma: { + since: "1.8.0", + category: CATEGORY_SPECIAL, + type: "boolean", + default: false, + description: "Insert @format pragma into file's first docblock comment.", + cliCategory: CATEGORY_OTHER + }, + parser: { + since: "0.0.10", + category: CATEGORY_GLOBAL, + type: "choice", + default: [{ + since: "0.0.10", + value: "babylon" + }, { + since: "1.13.0", + value: undefined + }], + description: "Which parser to use.", + exception: value => typeof value === "string" || typeof value === "function", + choices: [{ + value: "flow", + description: "Flow" + }, { + value: "babel", + since: "1.16.0", + description: "JavaScript" + }, { + value: "babel-flow", + since: "1.16.0", + description: "Flow" + }, { + value: "babel-ts", + since: "2.0.0", + description: "TypeScript" + }, { + value: "typescript", + since: "1.4.0", + description: "TypeScript" + }, { + value: "css", + since: "1.7.1", + description: "CSS" + }, { + value: "less", + since: "1.7.1", + description: "Less" + }, { + value: "scss", + since: "1.7.1", + description: "SCSS" + }, { + value: "json", + since: "1.5.0", + description: "JSON" + }, { + value: "json5", + since: "1.13.0", + description: "JSON5" + }, { + value: "json-stringify", + since: "1.13.0", + description: "JSON.stringify" + }, { + value: "graphql", + since: "1.5.0", + description: "GraphQL" + }, { + value: "markdown", + since: "1.8.0", + description: "Markdown" + }, { + value: "mdx", + since: "1.15.0", + description: "MDX" + }, { + value: "vue", + since: "1.10.0", + description: "Vue" + }, { + value: "yaml", + since: "1.14.0", + description: "YAML" + }, { + value: "glimmer", + since: null, + description: "Handlebars" + }, { + value: "html", + since: "1.15.0", + description: "HTML" + }, { + value: "angular", + since: "1.15.0", + description: "Angular" + }, { + value: "lwc", + since: "1.17.0", + description: "Lightning Web Components" + }] + }, + plugins: { + since: "1.10.0", + type: "path", + array: true, + default: [{ + value: [] + }], + category: CATEGORY_GLOBAL, + description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.", + exception: value => typeof value === "string" || typeof value === "object", + cliName: "plugin", + cliCategory: CATEGORY_CONFIG + }, + pluginSearchDirs: { + since: "1.13.0", + type: "path", + array: true, + default: [{ + value: [] + }], + category: CATEGORY_GLOBAL, + description: dedent_1(_templateObject3()), + exception: value => typeof value === "string" || typeof value === "object", + cliName: "plugin-search-dir", + cliCategory: CATEGORY_CONFIG + }, + printWidth: { + since: "0.0.0", + category: CATEGORY_GLOBAL, + type: "int", + default: 80, + description: "The line length where Prettier will try wrap.", + range: { + start: 0, + end: Infinity, + step: 1 + } + }, + rangeEnd: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: Infinity, + range: { + start: 0, + end: Infinity, + step: 1 + }, + description: dedent_1(_templateObject4()), + cliCategory: CATEGORY_EDITOR + }, + rangeStart: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: 0, + range: { + start: 0, + end: Infinity, + step: 1 + }, + description: dedent_1(_templateObject5()), + cliCategory: CATEGORY_EDITOR + }, + requirePragma: { + since: "1.7.0", + category: CATEGORY_SPECIAL, + type: "boolean", + default: false, + description: dedent_1(_templateObject6()), + cliCategory: CATEGORY_OTHER + }, + tabWidth: { + type: "int", + category: CATEGORY_GLOBAL, + default: 2, + description: "Number of spaces per indentation level.", + range: { + start: 0, + end: Infinity, + step: 1 + } + }, + useTabs: { + since: "1.0.0", + category: CATEGORY_GLOBAL, + type: "boolean", + default: false, + description: "Indent with tabs instead of spaces." + } + }; + var coreOptions = { + CATEGORY_CONFIG, + CATEGORY_EDITOR, + CATEGORY_FORMAT, + CATEGORY_OTHER, + CATEGORY_OUTPUT, + CATEGORY_GLOBAL, + CATEGORY_SPECIAL, + options + }; + + var require$$0 = getCjsExportFromNamespace(_package$1); + + const semver$1 = { + compare: compare_1, + lt: lt_1, + gte: gte_1 + }; + const currentVersion = require$$0.version; + const coreOptions$1 = coreOptions.options; + /** + * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version + * of this function created by `withPlugins`. Don't pass them here directly. + * @param {object} param0 + * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`. + * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`. + * @param {boolean=} param0.showUnreleased + * @param {boolean=} param0.showDeprecated + * @param {boolean=} param0.showInternal + */ + + function getSupportInfo({ + plugins = [], + showUnreleased = false, + showDeprecated = false, + showInternal = false + } = {}) { + // pre-release version is smaller than the normal version in semver, + // we need to treat it as the normal one so as to test new features. + const version = currentVersion.split("-", 1)[0]; + const options = arrayify(Object.assign({}, ...plugins.map(({ + options + }) => options), coreOptions$1), "name").filter(option => filterSince(option) && filterDeprecated(option)).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1).map(mapInternal).map(option => { + option = Object.assign({}, option); + + if (Array.isArray(option.default)) { + option.default = option.default.length === 1 ? option.default[0].value : option.default.filter(filterSince).sort((info1, info2) => semver$1.compare(info2.since, info1.since))[0].value; + } + + if (Array.isArray(option.choices)) { + option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option)); + } + + const filteredPlugins = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined); + const pluginDefaults = filteredPlugins.reduce((reduced, plugin) => { + reduced[plugin.name] = plugin.defaultOptions[option.name]; + return reduced; + }, {}); + return Object.assign({}, option, { + pluginDefaults + }); + }); + const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince); + return { + languages, + options + }; + + function filterSince(object) { + return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since); + } + + function filterDeprecated(object) { + return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated); + } + + function mapInternal(object) { + if (showInternal) { + return object; + } + + const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]); + + return newObject; + } + } + + var support = { + getSupportInfo + }; + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. All rights reserved. + Licensed under the Apache License, Version 2.0 (the "License"); you may not use + this file except in compliance with the License. You may obtain a copy of the + License at http://www.apache.org/licenses/LICENSE-2.0 + + THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED + WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, + MERCHANTABLITY OR NON-INFRINGEMENT. + + See the Apache Version 2.0 License for specific language governing permissions + and limitations under the License. + ***************************************************************************** */ + + /* global Reflect, Promise */ + var _extendStatics = function extendStatics(d, b) { + _extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + }; + + return _extendStatics(d, b); + }; + + function __extends(d, b) { + _extendStatics(d, b); + + function __() { + this.constructor = d; + } + + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var _assign = function __assign() { + _assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + + return t; + }; + + return _assign.apply(this, arguments); + }; + function __rest(s, e) { + var t = {}; + + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; + } + function __decorate(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + } + function __param(paramIndex, decorator) { + return function (target, key) { + decorator(target, key, paramIndex); + }; + } + function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + } + function __awaiter(thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + + function step(result) { + result.done ? resolve(result.value) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + function __generator(thisArg, body) { + var _ = { + label: 0, + sent: function sent() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, + f, + y, + t, + g; + return g = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + + switch (op[0]) { + case 0: + case 1: + t = op; + break; + + case 4: + _.label++; + return { + value: op[1], + done: false + }; + + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + + case 7: + op = _.ops.pop(); + + _.trys.pop(); + + continue; + + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + + if (t && _.label < t[2]) { + _.label = t[2]; + + _.ops.push(op); + + break; + } + + if (t[2]) _.ops.pop(); + + _.trys.pop(); + + continue; + } + + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } + } + function __exportStar(m, exports) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + function __values(o) { + var m = typeof Symbol === "function" && o[Symbol.iterator], + i = 0; + if (m) return m.call(o); + return { + next: function next() { + if (o && i >= o.length) o = void 0; + return { + value: o && o[i++], + done: !o + }; + } + }; + } + function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), + r, + ar = [], + e; + + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error) { + e = { + error: error + }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + + return ar; + } + function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); + + return ar; + } + function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + + for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; + + return r; + } + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i; + + function verb(n) { + if (g[n]) i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + + function fulfill(value) { + resume("next", value); + } + + function reject(value) { + resume("throw", value); + } + + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } + } + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function () { + return this; + }, i; + + function verb(n, f) { + i[n] = o[n] ? function (v) { + return (p = !p) ? { + value: __await(o[n](v)), + done: n === "return" + } : f ? f(v) : v; + } : f; + } + } + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + + function verb(n) { + i[n] = o[n] && function (v) { + return new Promise(function (resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); + }); + }; + } + + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } + } + function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { + value: raw + }); + } else { + cooked.raw = raw; + } + + return cooked; + } + function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result.default = mod; + return result; + } + function __importDefault(mod) { + return mod && mod.__esModule ? mod : { + default: mod + }; + } + + var tslib_es6 = /*#__PURE__*/Object.freeze({ + __proto__: null, + __extends: __extends, + get __assign () { return _assign; }, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault + }); + + var api = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.apiDescriptor = { + key: _key => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(_key) ? _key : JSON.stringify(_key), + + value(value) { + if (value === null || typeof value !== 'object') { + return JSON.stringify(value); + } + + if (Array.isArray(value)) { + return "[".concat(value.map(subValue => exports.apiDescriptor.value(subValue)).join(', '), "]"); + } + + const keys = Object.keys(value); + return keys.length === 0 ? '{}' : "{ ".concat(keys.map(key => "".concat(exports.apiDescriptor.key(key), ": ").concat(exports.apiDescriptor.value(value[key]))).join(', '), " }"); + }, + + pair: ({ + key, + value + }) => exports.apiDescriptor.value({ + [key]: value + }) + }; + }); + unwrapExports(api); + var api_1 = api.apiDescriptor; + + var tslib_1 = getCjsExportFromNamespace(tslib_es6); + + var descriptors = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(api, exports); + }); + unwrapExports(descriptors); + + var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + + var escapeStringRegexp = function escapeStringRegexp(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); + }; + + var colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + + var conversions = createCommonjsModule(function (module) { + /* MIT license */ + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + var reverseKeywords = {}; + + for (var key in colorName) { + if (colorName.hasOwnProperty(key)) { + reverseKeywords[colorName[key]] = key; + } + } + + var convert = module.exports = { + rgb: { + channels: 3, + labels: 'rgb' + }, + hsl: { + channels: 3, + labels: 'hsl' + }, + hsv: { + channels: 3, + labels: 'hsv' + }, + hwb: { + channels: 3, + labels: 'hwb' + }, + cmyk: { + channels: 4, + labels: 'cmyk' + }, + xyz: { + channels: 3, + labels: 'xyz' + }, + lab: { + channels: 3, + labels: 'lab' + }, + lch: { + channels: 3, + labels: 'lch' + }, + hex: { + channels: 1, + labels: ['hex'] + }, + keyword: { + channels: 1, + labels: ['keyword'] + }, + ansi16: { + channels: 1, + labels: ['ansi16'] + }, + ansi256: { + channels: 1, + labels: ['ansi256'] + }, + hcg: { + channels: 3, + labels: ['h', 'c', 'g'] + }, + apple: { + channels: 3, + labels: ['r16', 'g16', 'b16'] + }, + gray: { + channels: 1, + labels: ['gray'] + } + }; // hide .channels and .labels properties + + for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', { + value: channels + }); + Object.defineProperty(convert[model], 'labels', { + value: labels + }); + } + } + + convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + + var diffc = function diffc(c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = 1 / 3 + rdif - bdif; + } else if (b === v) { + h = 2 / 3 + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [h * 360, s * 100, v * 100]; + }; + + convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + return [h, w * 100, b * 100]; + }; + + convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; + }; + /** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ + + + function comparativeDistance(x, y) { + return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); + } + + convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in colorName) { + if (colorName.hasOwnProperty(keyword)) { + var value = colorName[keyword]; // Compute comparative distance + + var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest + + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; + }; + + convert.keyword.rgb = function (keyword) { + return colorName[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; // assume sRGB + + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + var x = r * 0.4124 + g * 0.3576 + b * 0.1805; + var y = r * 0.2126 + g * 0.7152 + b * 0.0722; + var z = r * 0.0193 + g * 0.1192 + b * 0.9505; + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + rgb = [0, 0, 0]; + + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - s * f); + var t = 255 * v * (1 - s * (1 - f)); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + + case 1: + return [q, v, p]; + + case 2: + return [p, v, t]; + + case 3: + return [p, q, v]; + + case 4: + return [t, p, v]; + + case 5: + return [v, p, q]; + } + }; + + convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; + }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + + + convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; // wh + bl cant be > 1 + + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + + switch (i) { + default: + case 6: + case 0: + r = v; + g = n; + b = wh; + break; + + case 1: + r = n; + g = v; + b = wh; + break; + + case 2: + r = wh; + g = v; + b = n; + break; + + case 3: + r = wh; + g = n; + b = v; + break; + + case 4: + r = n; + g = wh; + b = v; + break; + + case 5: + r = v; + g = wh; + b = n; + break; + } + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + r = x * 3.2406 + y * -1.5372 + z * -0.4986; + g = x * -0.9689 + y * 1.8758 + z * 0.0415; + b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB + + r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; + g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; + b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + x *= 95.047; + y *= 100; + z *= 108.883; + return [x, y, z]; + }; + + convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + + convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round((r - 8) / 247 * 24) + 232; + } + + var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); + return ansi; + }; + + convert.ansi16.rgb = function (args) { + var color = args % 10; // handle greyscale + + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = (color & 1) * mult * 255; + var g = (color >> 1 & 1) * mult * 255; + var b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = rem % 6 / 5 * 255; + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = integer >> 16 & 0xFF; + var g = integer >> 8 & 0xFF; + var b = integer & 0xFF; + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = max - min; + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b) / chroma % 6; + } else if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = h % 1 * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + + case 1: + pure[0] = w; + pure[1] = 1; + pure[2] = 0; + break; + + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + + case 3: + pure[0] = 0; + pure[1] = w; + pure[2] = 1; + break; + + case 4: + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w; + } + + mg = (1.0 - c) * g; + return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; + }; + + convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert.apple.rgb = function (apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + + convert.rgb.apple = function (rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + + convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; + }; + + convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + }); + var conversions_1 = conversions.rgb; + var conversions_2 = conversions.hsl; + var conversions_3 = conversions.hsv; + var conversions_4 = conversions.hwb; + var conversions_5 = conversions.cmyk; + var conversions_6 = conversions.xyz; + var conversions_7 = conversions.lab; + var conversions_8 = conversions.lch; + var conversions_9 = conversions.hex; + var conversions_10 = conversions.keyword; + var conversions_11 = conversions.ansi16; + var conversions_12 = conversions.ansi256; + var conversions_13 = conversions.hcg; + var conversions_14 = conversions.apple; + var conversions_15 = conversions.gray; + + /* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. + */ + + function buildGraph() { + var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; + } // https://en.wikipedia.org/wiki/Breadth-first_search + + + function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; + } + + function link(from, to) { + return function (args) { + return to(from(args)); + }; + } + + function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + var cur = graph[toModel].parent; + + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; + } + + var route = function route(fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + var models = Object.keys(graph); + + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; + }; + + var convert = {}; + var models = Object.keys(conversions); + + function wrapRaw(fn) { + var wrappedFn = function wrappedFn(args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; // preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + function wrapRounded(fn) { + var wrappedFn = function wrappedFn(args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; // preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + models.forEach(function (fromModel) { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], 'channels', { + value: conversions[fromModel].channels + }); + Object.defineProperty(convert[fromModel], 'labels', { + value: conversions[fromModel].labels + }); + var routes = route(fromModel); + var routeModels = Object.keys(routes); + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + var colorConvert = convert; + + var ansiStyles = createCommonjsModule(function (module) { + + const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return "\x1B[".concat(code + offset, "m"); + }; + + const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); + }; + + const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; // Fix humans + + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + styles[styleName] = { + open: "\x1B[".concat(style[0], "m"), + close: "\x1B[".concat(style[1], "m") + }; + group[styleName] = styles[styleName]; + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; + } // Make the export immutable + + + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); + }); + + var require$$0$1 = { + EOL: "\n" + }; + + var hasFlag = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + }; + + const env$1 = process.env; + let forceColor; + + if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; + } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { + forceColor = true; + } + + if ('FORCE_COLOR' in env$1) { + forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0; + } + + function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + + function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = require$$0$1.release().split('.'); + + if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$1) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$1.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$1) { + const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$1.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$1.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { + return 1; + } + + if ('COLORTERM' in env$1) { + return 1; + } + + if (env$1.TERM === 'dumb') { + return min; + } + + return min; + } + + function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); + } + + var supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) + }; + + const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); + + function unescape(c) { + if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; + } + + function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if (matches = chunk.match(STRING_REGEX)) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); + } + } + + return results; + } + + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error("Unknown Chalk style: ".concat(styleName)); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; + } + + var templates = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; // eslint-disable-next-line max-params + + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({ + inverse, + styles: parseStyle(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); + throw new Error(errMsg); + } + + return chunks.join(''); + }; + + var chalk = createCommonjsModule(function (module) { + + const stdoutColor = supportsColor_1.stdout; + const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping + + const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such + + const skipModels = new Set(['gray']); + const styles = Object.create(null); + + function applyOptions(obj, options) { + options = options || {}; // Detect level if not set manually + + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; + } + + function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + chalk.template.constructor = Chalk; + return chalk.template; + } + + applyOptions(this, options); + } // Use bright blue on Windows as the normal blue color is illegible + + + if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; + } + + for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + + }; + } + + styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } + + }; + ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); + + for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + + }; + } + + ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); + + for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + + }; + } + + const proto = Object.defineProperties(() => {}, styles); + + function build(_styles, _empty, key) { + const builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + const self = this; + Object.defineProperty(builder, 'level', { + enumerable: true, + + get() { + return self.level; + }, + + set(level) { + self.level = level; + } + + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + + get() { + return self.enabled; + }, + + set(enabled) { + self.enabled = enabled; + } + + }); // See below for fix regarding invisible grey/dim combination on Windows + + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; + } + + function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + + + const originalDim = ansiStyles.dim.open; + + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + + str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); + } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + + + ansiStyles.dim.open = originalDim; + return str; + } + + function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return templates(chalk, parts.join('')); + } + + Object.defineProperties(Chalk.prototype, styles); + module.exports = Chalk(); // eslint-disable-line new-cap + + module.exports.supportsColor = stdoutColor; + module.exports.default = module.exports; // For TypeScript + }); + var chalk_1 = chalk.supportsColor; + + var common = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.commonDeprecatedHandler = (keyOrPair, redirectTo, { + descriptor + }) => { + const messages = ["".concat(chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair)), " is deprecated")]; + + if (redirectTo) { + messages.push("we now treat it as ".concat(chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo)))); + } + + return messages.join('; ') + '.'; + }; + }); + unwrapExports(common); + var common_1 = common.commonDeprecatedHandler; + + var deprecated = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(common, exports); + }); + unwrapExports(deprecated); + + var common$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.commonInvalidHandler = (key, value, utils) => ["Invalid ".concat(chalk.default.red(utils.descriptor.key(key)), " value."), "Expected ".concat(chalk.default.blue(utils.schemas[key].expected(utils)), ","), "but received ".concat(chalk.default.red(utils.descriptor.value(value)), ".")].join(' '); + }); + unwrapExports(common$1); + var common_1$1 = common$1.commonInvalidHandler; + + var invalid = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(common$1, exports); + }); + unwrapExports(invalid); + + /* eslint-disable no-nested-ternary */ + + var arr = []; + var charCodeCache = []; + + var leven = function leven(a, b) { + if (a === b) { + return 0; + } + + var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the + // shortest & which one is the longest + + if (a.length > b.length) { + a = b; + b = swap; + } + + var aLen = a.length; + var bLen = b.length; + + if (aLen === 0) { + return bLen; + } + + if (bLen === 0) { + return aLen; + } // Performing suffix trimming: + // We can linearly drop suffix common to both strings since they + // don't increase distance at all + // Note: `~-` is the bitwise way to perform a `- 1` operation + + + while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) { + aLen--; + bLen--; + } + + if (aLen === 0) { + return bLen; + } // Performing prefix trimming + // We can linearly drop prefix common to both strings since they + // don't increase distance at all + + + var start = 0; + + while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) { + start++; + } + + aLen -= start; + bLen -= start; + + if (aLen === 0) { + return bLen; + } + + var bCharCode; + var ret; + var tmp; + var tmp2; + var i = 0; + var j = 0; + + while (i < aLen) { + charCodeCache[start + i] = a.charCodeAt(start + i); + arr[i] = ++i; + } + + while (j < bLen) { + bCharCode = b.charCodeAt(start + j); + tmp = j++; + ret = j; + + for (i = 0; i < aLen; i++) { + tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1; + tmp = arr[i]; + ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2; + } + } + + return ret; + }; + + var leven_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.levenUnknownHandler = (key, value, { + descriptor, + logger, + schemas + }) => { + const messages = ["Ignored unknown option ".concat(chalk.default.yellow(descriptor.pair({ + key, + value + })), ".")]; + const suggestion = Object.keys(schemas).sort().find(knownKey => leven(key, knownKey) < 3); + + if (suggestion) { + messages.push("Did you mean ".concat(chalk.default.blue(descriptor.key(suggestion)), "?")); + } + + logger.warn(messages.join(' ')); + }; + }); + unwrapExports(leven_1); + var leven_2 = leven_1.levenUnknownHandler; + + var unknown = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(leven_1, exports); + }); + unwrapExports(unknown); + + var handlers = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(deprecated, exports); + + tslib_1.__exportStar(invalid, exports); + + tslib_1.__exportStar(unknown, exports); + }); + unwrapExports(handlers); + + var schema = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + const HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess']; + + function createSchema(SchemaConstructor, parameters) { + const schema = new SchemaConstructor(parameters); + const subSchema = Object.create(schema); + + for (const handlerKey of HANDLER_KEYS) { + if (handlerKey in parameters) { + subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length); + } + } + + return subSchema; + } + + exports.createSchema = createSchema; + + class Schema { + constructor(parameters) { + this.name = parameters.name; + } + + static create(parameters) { + // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863 + return createSchema(this, parameters); + } + + default(_utils) { + return undefined; + } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` + + + expected(_utils) { + return 'nothing'; + } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` + + + validate(_value, _utils) { + return false; + } + + deprecated(_value, _utils) { + return false; + } + + forward(_value, _utils) { + return undefined; + } + + redirect(_value, _utils) { + return undefined; + } + + overlap(currentValue, _newValue, _utils) { + return currentValue; + } + + preprocess(value, _utils) { + return value; + } + + postprocess(value, _utils) { + return value; + } + + } + + exports.Schema = Schema; + + function normalizeHandler(handler, superSchema, handlerArgumentsLength) { + return typeof handler === 'function' ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1)) : () => handler; + } + }); + unwrapExports(schema); + var schema_1 = schema.createSchema; + var schema_2 = schema.Schema; + + var alias = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class AliasSchema extends schema.Schema { + constructor(parameters) { + super(parameters); + this._sourceName = parameters.sourceName; + } + + expected(utils) { + return utils.schemas[this._sourceName].expected(utils); + } + + validate(value, utils) { + return utils.schemas[this._sourceName].validate(value, utils); + } + + redirect(_value, _utils) { + return this._sourceName; + } + + } + + exports.AliasSchema = AliasSchema; + }); + unwrapExports(alias); + var alias_1 = alias.AliasSchema; + + var any = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class AnySchema extends schema.Schema { + expected() { + return 'anything'; + } + + validate() { + return true; + } + + } + + exports.AnySchema = AnySchema; + }); + unwrapExports(any); + var any_1 = any.AnySchema; + + var array = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ArraySchema extends schema.Schema { + constructor(_a) { + var { + valueSchema, + name = valueSchema.name + } = _a, + handlers = tslib_1.__rest(_a, ["valueSchema", "name"]); + + super(Object.assign({}, handlers, { + name + })); + this._valueSchema = valueSchema; + } + + expected(utils) { + return "an array of ".concat(this._valueSchema.expected(utils)); + } + + validate(value, utils) { + if (!Array.isArray(value)) { + return false; + } + + const invalidValues = []; + + for (const subValue of value) { + const subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue); + + if (subValidateResult !== true) { + invalidValues.push(subValidateResult.value); + } + } + + return invalidValues.length === 0 ? true : { + value: invalidValues + }; + } + + deprecated(value, utils) { + const deprecatedResult = []; + + for (const subValue of value) { + const subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue); + + if (subDeprecatedResult !== false) { + deprecatedResult.push(...subDeprecatedResult.map(({ + value: deprecatedValue + }) => ({ + value: [deprecatedValue] + }))); + } + } + + return deprecatedResult; + } + + forward(value, utils) { + const forwardResult = []; + + for (const subValue of value) { + const subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue); + forwardResult.push(...subForwardResult.map(wrapTransferResult)); + } + + return forwardResult; + } + + redirect(value, utils) { + const remain = []; + const redirect = []; + + for (const subValue of value) { + const subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue); + + if ('remain' in subRedirectResult) { + remain.push(subRedirectResult.remain); + } + + redirect.push(...subRedirectResult.redirect.map(wrapTransferResult)); + } + + return remain.length === 0 ? { + redirect + } : { + redirect, + remain + }; + } + + overlap(currentValue, newValue) { + return currentValue.concat(newValue); + } + + } + + exports.ArraySchema = ArraySchema; + + function wrapTransferResult({ + from, + to + }) { + return { + from: [from], + to + }; + } + }); + unwrapExports(array); + var array_1 = array.ArraySchema; + + var boolean_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class BooleanSchema extends schema.Schema { + expected() { + return 'true or false'; + } + + validate(value) { + return typeof value === 'boolean'; + } + + } + + exports.BooleanSchema = BooleanSchema; + }); + unwrapExports(boolean_1); + var boolean_2 = boolean_1.BooleanSchema; + + var utils = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function recordFromArray(array, mainKey) { + const record = Object.create(null); + + for (const value of array) { + const key = value[mainKey]; // istanbul ignore next + + if (record[key]) { + throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key))); + } // @ts-ignore + + + record[key] = value; + } + + return record; + } + + exports.recordFromArray = recordFromArray; + + function mapFromArray(array, mainKey) { + const map = new Map(); + + for (const value of array) { + const key = value[mainKey]; // istanbul ignore next + + if (map.has(key)) { + throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key))); + } + + map.set(key, value); + } + + return map; + } + + exports.mapFromArray = mapFromArray; + + function createAutoChecklist() { + const map = Object.create(null); + return id => { + const idString = JSON.stringify(id); + + if (map[idString]) { + return true; + } + + map[idString] = true; + return false; + }; + } + + exports.createAutoChecklist = createAutoChecklist; + + function partition(array, predicate) { + const trueArray = []; + const falseArray = []; + + for (const value of array) { + if (predicate(value)) { + trueArray.push(value); + } else { + falseArray.push(value); + } + } + + return [trueArray, falseArray]; + } + + exports.partition = partition; + + function isInt(value) { + return value === Math.floor(value); + } + + exports.isInt = isInt; + + function comparePrimitive(a, b) { + if (a === b) { + return 0; + } + + const typeofA = typeof a; + const typeofB = typeof b; + const orders = ['undefined', 'object', 'boolean', 'number', 'string']; + + if (typeofA !== typeofB) { + return orders.indexOf(typeofA) - orders.indexOf(typeofB); + } + + if (typeofA !== 'string') { + return Number(a) - Number(b); + } + + return a.localeCompare(b); + } + + exports.comparePrimitive = comparePrimitive; + + function normalizeDefaultResult(result) { + return result === undefined ? {} : result; + } + + exports.normalizeDefaultResult = normalizeDefaultResult; + + function normalizeValidateResult(result, value) { + return result === true ? true : result === false ? { + value + } : result; + } + + exports.normalizeValidateResult = normalizeValidateResult; + + function normalizeDeprecatedResult(result, value, doNotNormalizeTrue = false) { + return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{ + value + }] : 'value' in result ? [result] : result.length === 0 ? false : result; + } + + exports.normalizeDeprecatedResult = normalizeDeprecatedResult; + + function normalizeTransferResult(result, value) { + return typeof result === 'string' || 'key' in result ? { + from: value, + to: result + } : 'from' in result ? { + from: result.from, + to: result.to + } : { + from: value, + to: result.to + }; + } + + exports.normalizeTransferResult = normalizeTransferResult; + + function normalizeForwardResult(result, value) { + return result === undefined ? [] : Array.isArray(result) ? result.map(transferResult => normalizeTransferResult(transferResult, value)) : [normalizeTransferResult(result, value)]; + } + + exports.normalizeForwardResult = normalizeForwardResult; + + function normalizeRedirectResult(result, value) { + const redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value); + return redirect.length === 0 ? { + remain: value, + redirect + } : typeof result === 'object' && 'remain' in result ? { + remain: result.remain, + redirect + } : { + redirect + }; + } + + exports.normalizeRedirectResult = normalizeRedirectResult; + }); + unwrapExports(utils); + var utils_1 = utils.recordFromArray; + var utils_2 = utils.mapFromArray; + var utils_3 = utils.createAutoChecklist; + var utils_4 = utils.partition; + var utils_5 = utils.isInt; + var utils_6 = utils.comparePrimitive; + var utils_7 = utils.normalizeDefaultResult; + var utils_8 = utils.normalizeValidateResult; + var utils_9 = utils.normalizeDeprecatedResult; + var utils_10 = utils.normalizeTransferResult; + var utils_11 = utils.normalizeForwardResult; + var utils_12 = utils.normalizeRedirectResult; + + var choice = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ChoiceSchema extends schema.Schema { + constructor(parameters) { + super(parameters); + this._choices = utils.mapFromArray(parameters.choices.map(choice => choice && typeof choice === 'object' ? choice : { + value: choice + }), 'value'); + } + + expected({ + descriptor + }) { + const choiceValues = Array.from(this._choices.keys()).map(value => this._choices.get(value)).filter(choiceInfo => !choiceInfo.deprecated).map(choiceInfo => choiceInfo.value).sort(utils.comparePrimitive).map(descriptor.value); + const head = choiceValues.slice(0, -2); + const tail = choiceValues.slice(-2); + return head.concat(tail.join(' or ')).join(', '); + } + + validate(value) { + return this._choices.has(value); + } + + deprecated(value) { + const choiceInfo = this._choices.get(value); + + return choiceInfo && choiceInfo.deprecated ? { + value + } : false; + } + + forward(value) { + const choiceInfo = this._choices.get(value); + + return choiceInfo ? choiceInfo.forward : undefined; + } + + redirect(value) { + const choiceInfo = this._choices.get(value); + + return choiceInfo ? choiceInfo.redirect : undefined; + } + + } + + exports.ChoiceSchema = ChoiceSchema; + }); + unwrapExports(choice); + var choice_1 = choice.ChoiceSchema; + + var number = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class NumberSchema extends schema.Schema { + expected() { + return 'a number'; + } + + validate(value, _utils) { + return typeof value === 'number'; + } + + } + + exports.NumberSchema = NumberSchema; + }); + unwrapExports(number); + var number_1 = number.NumberSchema; + + var integer = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class IntegerSchema extends number.NumberSchema { + expected() { + return 'an integer'; + } + + validate(value, utils$1) { + return utils$1.normalizeValidateResult(super.validate(value, utils$1), value) === true && utils.isInt(value); + } + + } + + exports.IntegerSchema = IntegerSchema; + }); + unwrapExports(integer); + var integer_1 = integer.IntegerSchema; + + var string = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class StringSchema extends schema.Schema { + expected() { + return 'a string'; + } + + validate(value) { + return typeof value === 'string'; + } + + } + + exports.StringSchema = StringSchema; + }); + unwrapExports(string); + var string_1 = string.StringSchema; + + var schemas = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(alias, exports); + + tslib_1.__exportStar(any, exports); + + tslib_1.__exportStar(array, exports); + + tslib_1.__exportStar(boolean_1, exports); + + tslib_1.__exportStar(choice, exports); + + tslib_1.__exportStar(integer, exports); + + tslib_1.__exportStar(number, exports); + + tslib_1.__exportStar(string, exports); + }); + unwrapExports(schemas); + + var defaults = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.defaultDescriptor = api.apiDescriptor; + exports.defaultUnknownHandler = leven_1.levenUnknownHandler; + exports.defaultInvalidHandler = invalid.commonInvalidHandler; + exports.defaultDeprecatedHandler = common.commonDeprecatedHandler; + }); + unwrapExports(defaults); + var defaults_1 = defaults.defaultDescriptor; + var defaults_2 = defaults.defaultUnknownHandler; + var defaults_3 = defaults.defaultInvalidHandler; + var defaults_4 = defaults.defaultDeprecatedHandler; + + var normalize = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.normalize = (options, schemas, opts) => new Normalizer(schemas, opts).normalize(options); + + class Normalizer { + constructor(schemas, opts) { + // istanbul ignore next + const { + logger = console, + descriptor = defaults.defaultDescriptor, + unknown = defaults.defaultUnknownHandler, + invalid = defaults.defaultInvalidHandler, + deprecated = defaults.defaultDeprecatedHandler + } = opts || {}; + this._utils = { + descriptor, + logger: + /* istanbul ignore next */ + logger || { + warn: () => {} + }, + schemas: utils.recordFromArray(schemas, 'name'), + normalizeDefaultResult: utils.normalizeDefaultResult, + normalizeDeprecatedResult: utils.normalizeDeprecatedResult, + normalizeForwardResult: utils.normalizeForwardResult, + normalizeRedirectResult: utils.normalizeRedirectResult, + normalizeValidateResult: utils.normalizeValidateResult + }; + this._unknownHandler = unknown; + this._invalidHandler = invalid; + this._deprecatedHandler = deprecated; + this.cleanHistory(); + } + + cleanHistory() { + this._hasDeprecationWarned = utils.createAutoChecklist(); + } + + normalize(options) { + const normalized = {}; + const restOptionsArray = [options]; + + const applyNormalization = () => { + while (restOptionsArray.length !== 0) { + const currentOptions = restOptionsArray.shift(); + + const transferredOptionsArray = this._applyNormalization(currentOptions, normalized); + + restOptionsArray.push(...transferredOptionsArray); + } + }; + + applyNormalization(); + + for (const key of Object.keys(this._utils.schemas)) { + const schema = this._utils.schemas[key]; + + if (!(key in normalized)) { + const defaultResult = utils.normalizeDefaultResult(schema.default(this._utils)); + + if ('value' in defaultResult) { + restOptionsArray.push({ + [key]: defaultResult.value + }); + } + } + } + + applyNormalization(); + + for (const key of Object.keys(this._utils.schemas)) { + const schema = this._utils.schemas[key]; + + if (key in normalized) { + normalized[key] = schema.postprocess(normalized[key], this._utils); + } + } + + return normalized; + } + + _applyNormalization(options, normalized) { + const transferredOptionsArray = []; + const [knownOptionNames, unknownOptionNames] = utils.partition(Object.keys(options), key => key in this._utils.schemas); + + for (const key of knownOptionNames) { + const schema = this._utils.schemas[key]; + const value = schema.preprocess(options[key], this._utils); + const validateResult = utils.normalizeValidateResult(schema.validate(value, this._utils), value); + + if (validateResult !== true) { + const { + value: invalidValue + } = validateResult; + + const errorMessageOrError = this._invalidHandler(key, invalidValue, this._utils); + + throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) : + /* istanbul ignore next*/ + errorMessageOrError; + } + + const appendTransferredOptions = ({ + from, + to + }) => { + transferredOptionsArray.push(typeof to === 'string' ? { + [to]: from + } : { + [to.key]: to.value + }); + }; + + const warnDeprecated = ({ + value: currentValue, + redirectTo + }) => { + const deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, this._utils), value, + /* doNotNormalizeTrue */ + true); + + if (deprecatedResult === false) { + return; + } + + if (deprecatedResult === true) { + if (!this._hasDeprecationWarned(key)) { + this._utils.logger.warn(this._deprecatedHandler(key, redirectTo, this._utils)); + } + } else { + for (const { + value: deprecatedValue + } of deprecatedResult) { + const pair = { + key, + value: deprecatedValue + }; + + if (!this._hasDeprecationWarned(pair)) { + const redirectToPair = typeof redirectTo === 'string' ? { + key: redirectTo, + value: deprecatedValue + } : redirectTo; + + this._utils.logger.warn(this._deprecatedHandler(pair, redirectToPair, this._utils)); + } + } + } + }; + + const forwardResult = utils.normalizeForwardResult(schema.forward(value, this._utils), value); + forwardResult.forEach(appendTransferredOptions); + const redirectResult = utils.normalizeRedirectResult(schema.redirect(value, this._utils), value); + redirectResult.redirect.forEach(appendTransferredOptions); + + if ('remain' in redirectResult) { + const remainingValue = redirectResult.remain; + normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, this._utils) : remainingValue; + warnDeprecated({ + value: remainingValue + }); + } + + for (const { + from, + to + } of redirectResult.redirect) { + warnDeprecated({ + value: from, + redirectTo: to + }); + } + } + + for (const key of unknownOptionNames) { + const value = options[key]; + + const unknownResult = this._unknownHandler(key, value, this._utils); + + if (unknownResult) { + for (const unknownKey of Object.keys(unknownResult)) { + const unknownOption = { + [unknownKey]: unknownResult[unknownKey] + }; + + if (unknownKey in this._utils.schemas) { + transferredOptionsArray.push(unknownOption); + } else { + Object.assign(normalized, unknownOption); + } + } + } + } + + return transferredOptionsArray; + } + + } + + exports.Normalizer = Normalizer; + }); + unwrapExports(normalize); + var normalize_1 = normalize.normalize; + var normalize_2 = normalize.Normalizer; + + var lib = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(descriptors, exports); + + tslib_1.__exportStar(handlers, exports); + + tslib_1.__exportStar(schemas, exports); + + tslib_1.__exportStar(normalize, exports); + + tslib_1.__exportStar(schema, exports); + }); + unwrapExports(lib); + + const array$1 = []; + const charCodeCache$1 = []; + + const leven$1 = (left, right) => { + if (left === right) { + return 0; + } + + const swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the + // shortest & which one is the longest + + if (left.length > right.length) { + left = right; + right = swap; + } + + let leftLength = left.length; + let rightLength = right.length; // Performing suffix trimming: + // We can linearly drop suffix common to both strings since they + // don't increase distance at all + // Note: `~-` is the bitwise way to perform a `- 1` operation + + while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) { + leftLength--; + rightLength--; + } // Performing prefix trimming + // We can linearly drop prefix common to both strings since they + // don't increase distance at all + + + let start = 0; + + while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) { + start++; + } + + leftLength -= start; + rightLength -= start; + + if (leftLength === 0) { + return rightLength; + } + + let bCharCode; + let result; + let temp; + let temp2; + let i = 0; + let j = 0; + + while (i < leftLength) { + charCodeCache$1[i] = left.charCodeAt(start + i); + array$1[i] = ++i; + } + + while (j < rightLength) { + bCharCode = right.charCodeAt(start + j); + temp = j++; + result = j; + + for (i = 0; i < leftLength; i++) { + temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1; + temp = array$1[i]; // eslint-disable-next-line no-multi-assign + + result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2; + } + } + + return result; + }; + + var leven_1$1 = leven$1; // TODO: Remove this for the next major release + + var default_1 = leven$1; + leven_1$1.default = default_1; + + var colorName$1 = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + + /* MIT license */ + + /* eslint-disable no-mixed-operators */ + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + + const reverseKeywords = {}; + + for (const key of Object.keys(colorName$1)) { + reverseKeywords[colorName$1[key]] = key; + } + + const convert$1 = { + rgb: { + channels: 3, + labels: 'rgb' + }, + hsl: { + channels: 3, + labels: 'hsl' + }, + hsv: { + channels: 3, + labels: 'hsv' + }, + hwb: { + channels: 3, + labels: 'hwb' + }, + cmyk: { + channels: 4, + labels: 'cmyk' + }, + xyz: { + channels: 3, + labels: 'xyz' + }, + lab: { + channels: 3, + labels: 'lab' + }, + lch: { + channels: 3, + labels: 'lch' + }, + hex: { + channels: 1, + labels: ['hex'] + }, + keyword: { + channels: 1, + labels: ['keyword'] + }, + ansi16: { + channels: 1, + labels: ['ansi16'] + }, + ansi256: { + channels: 1, + labels: ['ansi256'] + }, + hcg: { + channels: 3, + labels: ['h', 'c', 'g'] + }, + apple: { + channels: 3, + labels: ['r16', 'g16', 'b16'] + }, + gray: { + channels: 1, + labels: ['gray'] + } + }; + var conversions$1 = convert$1; // Hide .channels and .labels properties + + for (const model of Object.keys(convert$1)) { + if (!('channels' in convert$1[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert$1[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert$1[model].labels.length !== convert$1[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + const { + channels, + labels + } = convert$1[model]; + delete convert$1[model].channels; + delete convert$1[model].labels; + Object.defineProperty(convert$1[model], 'channels', { + value: channels + }); + Object.defineProperty(convert$1[model], 'labels', { + value: labels + }); + } + + convert$1.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + const l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert$1.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + + const diffc = function diffc(c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = 1 / 3 + rdif - bdif; + } else if (b === v) { + h = 2 / 3 + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [h * 360, s * 100, v * 100]; + }; + + convert$1.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert$1.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + return [h, w * 100, b * 100]; + }; + + convert$1.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; + }; + + function comparativeDistance(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2; + } + + convert$1.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + + if (reversed) { + return reversed; + } + + let currentClosestDistance = Infinity; + let currentClosestKeyword; + + for (const keyword of Object.keys(colorName$1)) { + const value = colorName$1[keyword]; // Compute comparative distance + + const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest + + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + + return currentClosestKeyword; + }; + + convert$1.keyword.rgb = function (keyword) { + return colorName$1[keyword]; + }; + + convert$1.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; // Assume sRGB + + r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92; + g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92; + b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92; + const x = r * 0.4124 + g * 0.3576 + b * 0.1805; + const y = r * 0.2126 + g * 0.7152 + b * 0.0722; + const z = r * 0.0193 + g * 0.1192 + b * 0.9505; + return [x * 100, y * 100, z * 100]; + }; + + convert$1.rgb.lab = function (rgb) { + const xyz = convert$1.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116; + const l = 116 * y - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + return [l, a, b]; + }; + + convert$1.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + const t1 = 2 * l - t2; + const rgb = [0, 0, 0]; + + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert$1.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; + }; + + convert$1.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - s * f); + const t = 255 * v * (1 - s * (1 - f)); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + + case 1: + return [q, v, p]; + + case 2: + return [p, v, t]; + + case 3: + return [p, q, v]; + + case 4: + return [t, p, v]; + + case 5: + return [v, p, q]; + } + }; + + convert$1.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; + }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + + + convert$1.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; // Wh + bl cant be > 1 + + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + const n = wh + f * (v - wh); // Linear interpolation + + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + + switch (i) { + default: + case 6: + case 0: + r = v; + g = n; + b = wh; + break; + + case 1: + r = n; + g = v; + b = wh; + break; + + case 2: + r = wh; + g = v; + b = n; + break; + + case 3: + r = wh; + g = n; + b = v; + break; + + case 4: + r = n; + g = wh; + b = v; + break; + + case 5: + r = v; + g = wh; + b = n; + break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ + + + return [r * 255, g * 255, b * 255]; + }; + + convert$1.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; + }; + + convert$1.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + r = x * 3.2406 + y * -1.5372 + z * -0.4986; + g = x * -0.9689 + y * 1.8758 + z * 0.0415; + b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB + + r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92; + g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92; + b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + return [r * 255, g * 255, b * 255]; + }; + + convert$1.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116; + const l = 116 * y - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + return [l, a, b]; + }; + + convert$1.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + x *= 95.047; + y *= 100; + z *= 108.883; + return [x, y, z]; + }; + + convert$1.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + const c = Math.sqrt(a * a + b * b); + return [l, c, h]; + }; + + convert$1.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + return [l, a, b]; + }; + + convert$1.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert$1.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]); + }; + + convert$1.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round((r - 8) / 247 * 24) + 232; + } + + const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); + return ansi; + }; + + convert$1.ansi16.rgb = function (args) { + let color = args % 10; // Handle greyscale + + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + return [color, color, color]; + } + + const mult = (~~(args > 50) + 1) * 0.5; + const r = (color & 1) * mult * 255; + const g = (color >> 1 & 1) * mult * 255; + const b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; + }; + + convert$1.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = rem % 6 / 5 * 255; + return [r, g, b]; + }; + + convert$1.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert$1.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + + if (!match) { + return [0, 0, 0]; + } + + let colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } + + const integer = parseInt(colorString, 16); + const r = integer >> 16 & 0xFF; + const g = integer >> 8 & 0xFF; + const b = integer & 0xFF; + return [r, g, b]; + }; + + convert$1.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = max - min; + let grayscale; + let hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b) / chroma % 6; + } else if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert$1.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l); + let f = 0; + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert$1.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const c = s * v; + let f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert$1.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + const pure = [0, 0, 0]; + const hi = h % 1 * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + /* eslint-disable max-statements-per-line */ + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + + case 1: + pure[0] = w; + pure[1] = 1; + pure[2] = 0; + break; + + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + + case 3: + pure[0] = 0; + pure[1] = w; + pure[2] = 1; + break; + + case 4: + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w; + } + /* eslint-enable max-statements-per-line */ + + + mg = (1.0 - c) * g; + return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; + }; + + convert$1.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + let f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert$1.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert$1.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert$1.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert$1.apple.rgb = function (apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + + convert$1.rgb.apple = function (rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + + convert$1.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert$1.gray.hsl = function (args) { + return [0, 0, args[0]]; + }; + + convert$1.gray.hsv = convert$1.gray.hsl; + + convert$1.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert$1.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert$1.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert$1.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert$1.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + + /* + This function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. + */ + + function buildGraph$1() { + const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + + const models = Object.keys(conversions$1); + + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; + } // https://en.wikipedia.org/wiki/Breadth-first_search + + + function deriveBFS$1(fromModel) { + const graph = buildGraph$1(); + const queue = [fromModel]; // Unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions$1[current]); + + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; + } + + function link$1(from, to) { + return function (args) { + return to(from(args)); + }; + } + + function wrapConversion$1(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions$1[graph[toModel].parent][toModel]; + let cur = graph[toModel].parent; + + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link$1(conversions$1[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; + } + + var route$1 = function route(fromModel) { + const graph = deriveBFS$1(fromModel); + const conversion = {}; + const models = Object.keys(graph); + + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; + + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion$1(toModel, graph); + } + + return conversion; + }; + + const convert$2 = {}; + const models$1 = Object.keys(conversions$1); + + function wrapRaw$1(fn) { + const wrappedFn = function wrappedFn(...args) { + const arg0 = args[0]; + + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + return fn(args); + }; // Preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + function wrapRounded$1(fn) { + const wrappedFn = function wrappedFn(...args) { + const arg0 = args[0]; + + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + const result = fn(args); // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; // Preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + models$1.forEach(fromModel => { + convert$2[fromModel] = {}; + Object.defineProperty(convert$2[fromModel], 'channels', { + value: conversions$1[fromModel].channels + }); + Object.defineProperty(convert$2[fromModel], 'labels', { + value: conversions$1[fromModel].labels + }); + const routes = route$1(fromModel); + const routeModels = Object.keys(routes); + routeModels.forEach(toModel => { + const fn = routes[toModel]; + convert$2[fromModel][toModel] = wrapRounded$1(fn); + convert$2[fromModel][toModel].raw = wrapRaw$1(fn); + }); + }); + var colorConvert$1 = convert$2; + + var ansiStyles$1 = createCommonjsModule(function (module) { + + const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return "\x1B[".concat(code + offset, "m"); + }; + + const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); + }; + + const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); + }; + + const ansi2ansi = n => n; + + const rgb2rgb = (r, g, b) => [r, g, b]; + + const setLazyProperty = (object, property, _get) => { + Object.defineProperty(object, property, { + get: () => { + const value = _get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + return value; + }, + enumerable: true, + configurable: true + }); + }; + /** @type {typeof import('color-convert')} */ + + + let colorConvert; + + const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = colorConvert$1; + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; // Alias bright black as gray (and grey) + + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: "\x1B[".concat(style[0], "m"), + close: "\x1B[".concat(style[1], "m") + }; + group[styleName] = styles[styleName]; + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + return styles; + } // Make the export immutable + + + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); + }); + + var tty = { + isatty() { + return false; + } + + }; + + var hasFlag$1 = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; + + const { + env: env$2 + } = process; + let forceColor$1; + + if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) { + forceColor$1 = 0; + } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) { + forceColor$1 = 1; + } + + if ('FORCE_COLOR' in env$2) { + if (env$2.FORCE_COLOR === 'true') { + forceColor$1 = 1; + } else if (env$2.FORCE_COLOR === 'false') { + forceColor$1 = 0; + } else { + forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3); + } + } + + function translateLevel$1(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + + function supportsColor$1(haveStream, streamIsTTY) { + if (forceColor$1 === 0) { + return 0; + } + + if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) { + return 3; + } + + if (hasFlag$1('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor$1 === undefined) { + return 0; + } + + const min = forceColor$1 || 0; + + if (env$2.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = require$$0$1.release().split('.'); + + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$2) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$2) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; + } + + if ('GITHUB_ACTIONS' in env$2) { + return 1; + } + + if (env$2.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$2) { + const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$2.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$2.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { + return 1; + } + + if ('COLORTERM' in env$2) { + return 1; + } + + return min; + } + + function getSupportLevel$1(stream) { + const level = supportsColor$1(stream, stream && stream.isTTY); + return translateLevel$1(level); + } + + var supportsColor_1$1 = { + supportsColor: getSupportLevel$1, + stdout: translateLevel$1(supportsColor$1(true, tty.isatty(1))), + stderr: translateLevel$1(supportsColor$1(true, tty.isatty(2))) + }; + + const stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + + if (index === -1) { + return string; + } + + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; + }; + + const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; + }; + + var util = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex + }; + + const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + const ESCAPES$1 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); + + function unescape$1(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; + + if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } + + return ESCAPES$1.get(c) || c; + } + + function parseArguments$1(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + const number = Number(chunk); + + if (!Number.isNaN(number)) { + results.push(number); + } else if (matches = chunk.match(STRING_REGEX$1)) { + results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character)); + } else { + throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); + } + } + + return results; + } + + function parseStyle$1(style) { + STYLE_REGEX$1.lastIndex = 0; + const results = []; + let matches; + + while ((matches = STYLE_REGEX$1.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments$1(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle$1(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } + + if (!(styleName in current)) { + throw new Error("Unknown Chalk style: ".concat(styleName)); + } + + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } + + return current; + } + + var templates$1 = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; // eslint-disable-next-line max-params + + temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape$1(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string)); + styles.push({ + inverse, + styles: parseStyle$1(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle$1(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMessage = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); + throw new Error(errMessage); + } + + return chunks.join(''); + }; + + const { + stdout: stdoutColor, + stderr: stderrColor + } = supportsColor_1$1; + const { + stringReplaceAll: stringReplaceAll$1, + stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 + } = util; // `supportsColor.level` → `ansiStyles.color[name]` mapping + + const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + const styles = Object.create(null); + + const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } // Detect level if not set manually + + + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; + }; + + class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } + + } + + const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; + + chalk.template.Instance = ChalkClass; + return chalk.template; + }; + + function Chalk(options) { + return chalkFactory(options); + } + + for (const [styleName, style] of Object.entries(ansiStyles$1)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, { + value: builder + }); + return builder; + } + + }; + } + + styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', { + value: builder + }); + return builder; + } + + }; + const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; + + for (const model of usedModels) { + styles[model] = { + get() { + const { + level + } = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + + }; + } + + for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const { + level + } = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + + }; + } + + const proto = Object.defineProperties(() => {}, Object.assign({}, styles, { + level: { + enumerable: true, + + get() { + return this._generator.level; + }, + + set(level) { + this._generator.level = level; + } + + } + })); + + const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + + return { + open, + close, + openAll, + closeAll, + parent + }; + }; + + const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' ')); + }; // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + + + Object.setPrototypeOf(builder, proto); + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; + return builder; + }; + + const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } + + let styler = self._styler; + + if (styler === undefined) { + return string; + } + + const { + openAll, + closeAll + } = styler; + + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll$1(string, styler.close, styler.open); + styler = styler.parent; + } + } // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + + + const lfIndex = string.indexOf('\n'); + + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex); + } + + return openAll + string + closeAll; + }; + + let template; + + const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; + + if (!Array.isArray(firstString)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } + + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; + + for (let i = 1; i < firstString.length; i++) { + parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i])); + } + + if (template === undefined) { + template = templates$1; + } + + return template(chalk, parts.join('')); + }; + + Object.defineProperties(Chalk.prototype, styles); + const chalk$1 = Chalk(); // eslint-disable-line new-cap + + chalk$1.supportsColor = stdoutColor; + chalk$1.stderr = Chalk({ + level: stderrColor ? stderrColor.level : 0 + }); // eslint-disable-line new-cap + + chalk$1.stderr.supportsColor = stderrColor; + var source = chalk$1; + + const cliDescriptor = { + key: _key => _key.length === 1 ? "-".concat(_key) : "--".concat(_key), + value: _value => lib.apiDescriptor.value(_value), + pair: ({ + key, + value + }) => value === false ? "--no-".concat(key) : value === true ? cliDescriptor.key(key) : value === "" ? "".concat(cliDescriptor.key(key), " without an argument") : "".concat(cliDescriptor.key(key), "=").concat(value) + }; + + class FlagSchema extends lib.ChoiceSchema { + constructor({ + name, + flags + }) { + super({ + name, + choices: flags + }); + this._flags = flags.slice().sort(); + } + + preprocess(value, utils) { + if (typeof value === "string" && value.length !== 0 && !this._flags.includes(value)) { + const suggestion = this._flags.find(flag => leven_1$1(flag, value) < 3); + + if (suggestion) { + utils.logger.warn(["Unknown flag ".concat(source.yellow(utils.descriptor.value(value)), ","), "did you mean ".concat(source.blue(utils.descriptor.value(suggestion)), "?")].join(" ")); + return suggestion; + } + } + + return value; + } + + expected() { + return "a flag"; + } + + } + + let hasDeprecationWarned; + + function normalizeOptions(options, optionInfos, { + logger, + isCLI = false, + passThrough = false + } = {}) { + const unknown = !passThrough ? lib.levenUnknownHandler : Array.isArray(passThrough) ? (key, value) => !passThrough.includes(key) ? undefined : { + [key]: value + } : (key, value) => ({ + [key]: value + }); + const descriptor = isCLI ? cliDescriptor : lib.apiDescriptor; + const schemas = optionInfosToSchemas(optionInfos, { + isCLI + }); + const normalizer = new lib.Normalizer(schemas, { + logger, + unknown, + descriptor + }); + const shouldSuppressDuplicateDeprecationWarnings = logger !== false; + + if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) { + normalizer._hasDeprecationWarned = hasDeprecationWarned; + } + + const normalized = normalizer.normalize(options); + + if (shouldSuppressDuplicateDeprecationWarnings) { + hasDeprecationWarned = normalizer._hasDeprecationWarned; + } + + return normalized; + } + + function optionInfosToSchemas(optionInfos, { + isCLI + }) { + const schemas = []; + + if (isCLI) { + schemas.push(lib.AnySchema.create({ + name: "_" + })); + } + + for (const optionInfo of optionInfos) { + schemas.push(optionInfoToSchema(optionInfo, { + isCLI, + optionInfos + })); + + if (optionInfo.alias && isCLI) { + schemas.push(lib.AliasSchema.create({ + name: optionInfo.alias, + sourceName: optionInfo.name + })); + } + } + + return schemas; + } + + function optionInfoToSchema(optionInfo, { + isCLI, + optionInfos + }) { + let SchemaConstructor; + const parameters = { + name: optionInfo.name + }; + const handlers = {}; + + switch (optionInfo.type) { + case "int": + SchemaConstructor = lib.IntegerSchema; + + if (isCLI) { + parameters.preprocess = value => Number(value); + } + + break; + + case "string": + SchemaConstructor = lib.StringSchema; + break; + + case "choice": + SchemaConstructor = lib.ChoiceSchema; + parameters.choices = optionInfo.choices.map(choiceInfo => typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, { + redirect: { + to: { + key: optionInfo.name, + value: choiceInfo.redirect + } + } + }) : choiceInfo); + break; + + case "boolean": + SchemaConstructor = lib.BooleanSchema; + break; + + case "flag": + SchemaConstructor = FlagSchema; + parameters.flags = optionInfos.map(optionInfo => [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? "no-".concat(optionInfo.name) : [])).reduce((a, b) => a.concat(b), []); + break; + + case "path": + SchemaConstructor = lib.StringSchema; + break; + + default: + throw new Error("Unexpected type ".concat(optionInfo.type)); + } + + if (optionInfo.exception) { + parameters.validate = (value, schema, utils) => { + return optionInfo.exception(value) || schema.validate(value, utils); + }; + } else { + parameters.validate = (value, schema, utils) => { + return value === undefined || schema.validate(value, utils); + }; + } + + if (optionInfo.redirect) { + handlers.redirect = value => !value ? undefined : { + to: { + key: optionInfo.redirect.option, + value: optionInfo.redirect.value + } + }; + } + + if (optionInfo.deprecated) { + handlers.deprecated = true; + } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2 + + + if (isCLI && !optionInfo.array) { + const originalPreprocess = parameters.preprocess || (x => x); + + parameters.preprocess = (value, schema, utils) => schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils); + } + + return optionInfo.array ? lib.ArraySchema.create(Object.assign({}, isCLI ? { + preprocess: v => [].concat(v) + } : {}, {}, handlers, { + valueSchema: SchemaConstructor.create(parameters) + })) : SchemaConstructor.create(Object.assign({}, parameters, {}, handlers)); + } + + function normalizeApiOptions(options, optionInfos, opts) { + return normalizeOptions(options, optionInfos, opts); + } + + function normalizeCliOptions(options, optionInfos, opts) { + return normalizeOptions(options, optionInfos, Object.assign({ + isCLI: true + }, opts)); + } + + var optionsNormalizer = { + normalizeApiOptions, + normalizeCliOptions + }; + + var getLast = arr => arr[arr.length - 1]; + + function locStart(node, opts) { + opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator + + if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) { + return locStart(node.declaration.decorators[0]); + } + + if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) { + return locStart(node.decorators[0]); + } + + if (node.__location) { + return node.__location.startOffset; + } + + if (node.range) { + return node.range[0]; + } + + if (typeof node.start === "number") { + return node.start; + } + + if (node.loc) { + return node.loc.start; + } + + return null; + } + + function locEnd(node) { + const endNode = node.nodes && getLast(node.nodes); + + if (endNode && node.source && !node.source.end) { + node = endNode; + } + + if (node.__location) { + return node.__location.endOffset; + } + + const loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null; + + if (node.typeAnnotation) { + return Math.max(loc, locEnd(node.typeAnnotation)); + } + + if (node.loc && !loc) { + return node.loc.end; + } + + return loc; + } + + function composeLoc(startNode, endNodeOrLength = startNode) { + const length = typeof endNodeOrLength === "number" ? endNodeOrLength : -1; + const start = locStart(startNode); + const end = length !== -1 ? start + length : locEnd(endNodeOrLength); + const startLoc = startNode.loc.start; + return { + start, + end, + range: [start, end], + loc: { + start: startLoc, + end: length !== -1 ? { + line: startLoc.line, + column: startLoc.column + length + } : endNodeOrLength.loc.end + } + }; + } + + var loc = { + locStart, + locEnd, + composeLoc + }; + + var jsTokens = createCommonjsModule(function (module, exports) { + // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell + // License: MIT. (See LICENSE.) + Object.defineProperty(exports, "__esModule", { + value: true + }); // This regex comes from regex.coffee, and is inserted here by generate-index.js + // (run `npm run build`). + + exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; + + exports.matchToToken = function (match) { + var token = { + type: "invalid", + value: match[0], + closed: undefined + }; + if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace"; + return token; + }; + }); + unwrapExports(jsTokens); + var jsTokens_1 = jsTokens.matchToToken; + + var ast = createCommonjsModule(function (module) { + /* + Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com> + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + + function isExpression(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'ArrayExpression': + case 'AssignmentExpression': + case 'BinaryExpression': + case 'CallExpression': + case 'ConditionalExpression': + case 'FunctionExpression': + case 'Identifier': + case 'Literal': + case 'LogicalExpression': + case 'MemberExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'SequenceExpression': + case 'ThisExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return true; + } + + return false; + } + + function isIterationStatement(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'DoWhileStatement': + case 'ForInStatement': + case 'ForStatement': + case 'WhileStatement': + return true; + } + + return false; + } + + function isStatement(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'BlockStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'DebuggerStatement': + case 'DoWhileStatement': + case 'EmptyStatement': + case 'ExpressionStatement': + case 'ForInStatement': + case 'ForStatement': + case 'IfStatement': + case 'LabeledStatement': + case 'ReturnStatement': + case 'SwitchStatement': + case 'ThrowStatement': + case 'TryStatement': + case 'VariableDeclaration': + case 'WhileStatement': + case 'WithStatement': + return true; + } + + return false; + } + + function isSourceElement(node) { + return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; + } + + function trailingStatement(node) { + switch (node.type) { + case 'IfStatement': + if (node.alternate != null) { + return node.alternate; + } + + return node.consequent; + + case 'LabeledStatement': + case 'ForStatement': + case 'ForInStatement': + case 'WhileStatement': + case 'WithStatement': + return node.body; + } + + return null; + } + + function isProblematicIfStatement(node) { + var current; + + if (node.type !== 'IfStatement') { + return false; + } + + if (node.alternate == null) { + return false; + } + + current = node.consequent; + + do { + if (current.type === 'IfStatement') { + if (current.alternate == null) { + return true; + } + } + + current = trailingStatement(current); + } while (current); + + return false; + } + + module.exports = { + isExpression: isExpression, + isStatement: isStatement, + isIterationStatement: isIterationStatement, + isSourceElement: isSourceElement, + isProblematicIfStatement: isProblematicIfStatement, + trailingStatement: trailingStatement + }; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + + }); + var ast_1 = ast.isExpression; + var ast_2 = ast.isStatement; + var ast_3 = ast.isIterationStatement; + var ast_4 = ast.isSourceElement; + var ast_5 = ast.isProblematicIfStatement; + var ast_6 = ast.trailingStatement; + + var code = createCommonjsModule(function (module) { + /* + Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com> + Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com> + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + + var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`. + + ES5Regex = { + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ + }; + ES6Regex = { + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + + function isDecimalDigit(ch) { + return 0x30 <= ch && ch <= 0x39; // 0..9 + } + + function isHexDigit(ch) { + return 0x30 <= ch && ch <= 0x39 || // 0..9 + 0x61 <= ch && ch <= 0x66 || // a..f + 0x41 <= ch && ch <= 0x46; // A..F + } + + function isOctalDigit(ch) { + return ch >= 0x30 && ch <= 0x37; // 0..7 + } // 7.2 White Space + + + NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF]; + + function isWhiteSpace(ch) { + return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; + } // 7.3 Line Terminators + + + function isLineTerminator(ch) { + return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; + } // 7.6 Identifier Names and Identifiers + + + function fromCodePoint(cp) { + if (cp <= 0xFFFF) { + return String.fromCharCode(cp); + } + + var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); + var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); + return cu1 + cu2; + } + + IDENTIFIER_START = new Array(0x80); + + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + IDENTIFIER_PART = new Array(0x80); + + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch >= 0x30 && ch <= 0x39 || // 0..9 + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + function isIdentifierStartES5(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES5(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + function isIdentifierStartES6(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES6(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStartES5: isIdentifierStartES5, + isIdentifierPartES5: isIdentifierPartES5, + isIdentifierStartES6: isIdentifierStartES6, + isIdentifierPartES6: isIdentifierPartES6 + }; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + + }); + var code_1 = code.isDecimalDigit; + var code_2 = code.isHexDigit; + var code_3 = code.isOctalDigit; + var code_4 = code.isWhiteSpace; + var code_5 = code.isLineTerminator; + var code_6 = code.isIdentifierStartES5; + var code_7 = code.isIdentifierPartES5; + var code_8 = code.isIdentifierStartES6; + var code_9 = code.isIdentifierPartES6; + + var keyword = createCommonjsModule(function (module) { + /* + Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com> + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + + var code$1 = code; + + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + + default: + return false; + } + } + + function isKeywordES5(id, strict) { + // yield should not be treated as keyword under non-strict mode. + if (!strict && id === 'yield') { + return false; + } + + return isKeywordES6(id, strict); + } + + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + + switch (id.length) { + case 2: + return id === 'if' || id === 'in' || id === 'do'; + + case 3: + return id === 'var' || id === 'for' || id === 'new' || id === 'try'; + + case 4: + return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum'; + + case 5: + return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super'; + + case 6: + return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import'; + + case 7: + return id === 'default' || id === 'finally' || id === 'extends'; + + case 8: + return id === 'function' || id === 'continue' || id === 'debugger'; + + case 10: + return id === 'instanceof'; + + default: + return false; + } + } + + function isReservedWordES5(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + } + + function isReservedWordES6(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + function isIdentifierNameES5(id) { + var i, iz, ch; + + if (id.length === 0) { + return false; + } + + ch = id.charCodeAt(0); + + if (!code$1.isIdentifierStartES5(ch)) { + return false; + } + + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + + if (!code$1.isIdentifierPartES5(ch)) { + return false; + } + } + + return true; + } + + function decodeUtf16(lead, trail) { + return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + } + + function isIdentifierNameES6(id) { + var i, iz, ch, lowCh, check; + + if (id.length === 0) { + return false; + } + + check = code$1.isIdentifierStartES6; + + for (i = 0, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + + if (0xD800 <= ch && ch <= 0xDBFF) { + ++i; + + if (i >= iz) { + return false; + } + + lowCh = id.charCodeAt(i); + + if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { + return false; + } + + ch = decodeUtf16(ch, lowCh); + } + + if (!check(ch)) { + return false; + } + + check = code$1.isIdentifierPartES6; + } + + return true; + } + + function isIdentifierES5(id, strict) { + return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); + } + + function isIdentifierES6(id, strict) { + return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); + } + + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierNameES5: isIdentifierNameES5, + isIdentifierNameES6: isIdentifierNameES6, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + + }); + var keyword_1 = keyword.isKeywordES5; + var keyword_2 = keyword.isKeywordES6; + var keyword_3 = keyword.isReservedWordES5; + var keyword_4 = keyword.isReservedWordES6; + var keyword_5 = keyword.isRestrictedWord; + var keyword_6 = keyword.isIdentifierNameES5; + var keyword_7 = keyword.isIdentifierNameES6; + var keyword_8 = keyword.isIdentifierES5; + var keyword_9 = keyword.isIdentifierES6; + + var utils$1 = createCommonjsModule(function (module, exports) { + /* + Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com> + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + + exports.ast = ast; + exports.code = code; + exports.keyword = keyword; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + + }); + var utils_1$1 = utils$1.ast; + var utils_2$1 = utils$1.code; + var utils_3$1 = utils$1.keyword; + + var matchOperatorsRe$1 = /[|\\{}()[\]^$+*?.]/g; + + var escapeStringRegexp$1 = function escapeStringRegexp(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe$1, '\\$&'); + }; + + var colorName$2 = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + + var conversions$2 = createCommonjsModule(function (module) { + /* MIT license */ + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + var reverseKeywords = {}; + + for (var key in colorName$2) { + if (colorName$2.hasOwnProperty(key)) { + reverseKeywords[colorName$2[key]] = key; + } + } + + var convert = module.exports = { + rgb: { + channels: 3, + labels: 'rgb' + }, + hsl: { + channels: 3, + labels: 'hsl' + }, + hsv: { + channels: 3, + labels: 'hsv' + }, + hwb: { + channels: 3, + labels: 'hwb' + }, + cmyk: { + channels: 4, + labels: 'cmyk' + }, + xyz: { + channels: 3, + labels: 'xyz' + }, + lab: { + channels: 3, + labels: 'lab' + }, + lch: { + channels: 3, + labels: 'lch' + }, + hex: { + channels: 1, + labels: ['hex'] + }, + keyword: { + channels: 1, + labels: ['keyword'] + }, + ansi16: { + channels: 1, + labels: ['ansi16'] + }, + ansi256: { + channels: 1, + labels: ['ansi256'] + }, + hcg: { + channels: 3, + labels: ['h', 'c', 'g'] + }, + apple: { + channels: 3, + labels: ['r16', 'g16', 'b16'] + }, + gray: { + channels: 1, + labels: ['gray'] + } + }; // hide .channels and .labels properties + + for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', { + value: channels + }); + Object.defineProperty(convert[model], 'labels', { + value: labels + }); + } + } + + convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + + var diffc = function diffc(c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = 1 / 3 + rdif - bdif; + } else if (b === v) { + h = 2 / 3 + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [h * 360, s * 100, v * 100]; + }; + + convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + return [h, w * 100, b * 100]; + }; + + convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; + }; + /** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ + + + function comparativeDistance(x, y) { + return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); + } + + convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in colorName$2) { + if (colorName$2.hasOwnProperty(keyword)) { + var value = colorName$2[keyword]; // Compute comparative distance + + var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest + + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; + }; + + convert.keyword.rgb = function (keyword) { + return colorName$2[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; // assume sRGB + + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + var x = r * 0.4124 + g * 0.3576 + b * 0.1805; + var y = r * 0.2126 + g * 0.7152 + b * 0.0722; + var z = r * 0.0193 + g * 0.1192 + b * 0.9505; + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + rgb = [0, 0, 0]; + + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - s * f); + var t = 255 * v * (1 - s * (1 - f)); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + + case 1: + return [q, v, p]; + + case 2: + return [p, v, t]; + + case 3: + return [p, q, v]; + + case 4: + return [t, p, v]; + + case 5: + return [v, p, q]; + } + }; + + convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; + }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + + + convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; // wh + bl cant be > 1 + + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + + switch (i) { + default: + case 6: + case 0: + r = v; + g = n; + b = wh; + break; + + case 1: + r = n; + g = v; + b = wh; + break; + + case 2: + r = wh; + g = v; + b = n; + break; + + case 3: + r = wh; + g = n; + b = v; + break; + + case 4: + r = n; + g = wh; + b = v; + break; + + case 5: + r = v; + g = wh; + b = n; + break; + } + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + r = x * 3.2406 + y * -1.5372 + z * -0.4986; + g = x * -0.9689 + y * 1.8758 + z * 0.0415; + b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB + + r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; + g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; + b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + x *= 95.047; + y *= 100; + z *= 108.883; + return [x, y, z]; + }; + + convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + + convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round((r - 8) / 247 * 24) + 232; + } + + var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); + return ansi; + }; + + convert.ansi16.rgb = function (args) { + var color = args % 10; // handle greyscale + + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = (color & 1) * mult * 255; + var g = (color >> 1 & 1) * mult * 255; + var b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = rem % 6 / 5 * 255; + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = integer >> 16 & 0xFF; + var g = integer >> 8 & 0xFF; + var b = integer & 0xFF; + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = max - min; + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b) / chroma % 6; + } else if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = h % 1 * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + + case 1: + pure[0] = w; + pure[1] = 1; + pure[2] = 0; + break; + + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + + case 3: + pure[0] = 0; + pure[1] = w; + pure[2] = 1; + break; + + case 4: + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w; + } + + mg = (1.0 - c) * g; + return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; + }; + + convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert.apple.rgb = function (apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + + convert.rgb.apple = function (rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + + convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; + }; + + convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + }); + var conversions_1$1 = conversions$2.rgb; + var conversions_2$1 = conversions$2.hsl; + var conversions_3$1 = conversions$2.hsv; + var conversions_4$1 = conversions$2.hwb; + var conversions_5$1 = conversions$2.cmyk; + var conversions_6$1 = conversions$2.xyz; + var conversions_7$1 = conversions$2.lab; + var conversions_8$1 = conversions$2.lch; + var conversions_9$1 = conversions$2.hex; + var conversions_10$1 = conversions$2.keyword; + var conversions_11$1 = conversions$2.ansi16; + var conversions_12$1 = conversions$2.ansi256; + var conversions_13$1 = conversions$2.hcg; + var conversions_14$1 = conversions$2.apple; + var conversions_15$1 = conversions$2.gray; + + /* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. + */ + + function buildGraph$2() { + var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + + var models = Object.keys(conversions$2); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; + } // https://en.wikipedia.org/wiki/Breadth-first_search + + + function deriveBFS$2(fromModel) { + var graph = buildGraph$2(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions$2[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; + } + + function link$2(from, to) { + return function (args) { + return to(from(args)); + }; + } + + function wrapConversion$2(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions$2[graph[toModel].parent][toModel]; + var cur = graph[toModel].parent; + + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link$2(conversions$2[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; + } + + var route$2 = function route(fromModel) { + var graph = deriveBFS$2(fromModel); + var conversion = {}; + var models = Object.keys(graph); + + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion$2(toModel, graph); + } + + return conversion; + }; + + var convert$3 = {}; + var models$2 = Object.keys(conversions$2); + + function wrapRaw$2(fn) { + var wrappedFn = function wrappedFn(args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; // preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + function wrapRounded$2(fn) { + var wrappedFn = function wrappedFn(args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; // preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + models$2.forEach(function (fromModel) { + convert$3[fromModel] = {}; + Object.defineProperty(convert$3[fromModel], 'channels', { + value: conversions$2[fromModel].channels + }); + Object.defineProperty(convert$3[fromModel], 'labels', { + value: conversions$2[fromModel].labels + }); + var routes = route$2(fromModel); + var routeModels = Object.keys(routes); + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + convert$3[fromModel][toModel] = wrapRounded$2(fn); + convert$3[fromModel][toModel].raw = wrapRaw$2(fn); + }); + }); + var colorConvert$2 = convert$3; + + var ansiStyles$2 = createCommonjsModule(function (module) { + + const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert$2, arguments); + return "\x1B[".concat(code + offset, "m"); + }; + + const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert$2, arguments); + return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); + }; + + const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert$2, arguments); + return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; // Fix humans + + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + styles[styleName] = { + open: "\x1B[".concat(style[0], "m"), + close: "\x1B[".concat(style[1], "m") + }; + group[styleName] = styles[styleName]; + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert$2)) { + if (typeof colorConvert$2[key] !== 'object') { + continue; + } + + const suite = colorConvert$2[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; + } // Make the export immutable + + + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); + }); + + const env$3 = process.env; + let forceColor$2; + + if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor$2 = false; + } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { + forceColor$2 = true; + } + + if ('FORCE_COLOR' in env$3) { + forceColor$2 = env$3.FORCE_COLOR.length === 0 || parseInt(env$3.FORCE_COLOR, 10) !== 0; + } + + function translateLevel$2(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + + function supportsColor$2(stream) { + if (forceColor$2 === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor$2 !== true) { + return 0; + } + + const min = forceColor$2 ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = require$$0$1.release().split('.'); + + if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$3) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$3) || env$3.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$3) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$3.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$3.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$3) { + const version = parseInt((env$3.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$3.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$3.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$3.TERM)) { + return 1; + } + + if ('COLORTERM' in env$3) { + return 1; + } + + if (env$3.TERM === 'dumb') { + return min; + } + + return min; + } + + function getSupportLevel$2(stream) { + const level = supportsColor$2(stream); + return translateLevel$2(level); + } + + var supportsColor_1$2 = { + supportsColor: getSupportLevel$2, + stdout: getSupportLevel$2(process.stdout), + stderr: getSupportLevel$2(process.stderr) + }; + + const TEMPLATE_REGEX$2 = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + const STYLE_REGEX$2 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + const STRING_REGEX$2 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + const ESCAPE_REGEX$2 = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + const ESCAPES$2 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); + + function unescape$2(c) { + if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES$2.get(c) || c; + } + + function parseArguments$2(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if (matches = chunk.match(STRING_REGEX$2)) { + results.push(matches[2].replace(ESCAPE_REGEX$2, (m, escape, chr) => escape ? unescape$2(escape) : chr)); + } else { + throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); + } + } + + return results; + } + + function parseStyle$2(style) { + STYLE_REGEX$2.lastIndex = 0; + const results = []; + let matches; + + while ((matches = STYLE_REGEX$2.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments$2(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle$2(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error("Unknown Chalk style: ".concat(styleName)); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; + } + + var templates$2 = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; // eslint-disable-next-line max-params + + tmp.replace(TEMPLATE_REGEX$2, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape$2(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle$2(chalk, styles)(str)); + styles.push({ + inverse, + styles: parseStyle$2(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle$2(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); + throw new Error(errMsg); + } + + return chunks.join(''); + }; + + var chalk$2 = createCommonjsModule(function (module) { + + const stdoutColor = supportsColor_1$2.stdout; + const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping + + const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such + + const skipModels = new Set(['gray']); + const styles = Object.create(null); + + function applyOptions(obj, options) { + options = options || {}; // Detect level if not set manually + + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; + } + + function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + chalk.template.constructor = Chalk; + return chalk.template; + } + + applyOptions(this, options); + } // Use bright blue on Windows as the normal blue color is illegible + + + if (isSimpleWindowsTerm) { + ansiStyles$2.blue.open = '\u001B[94m'; + } + + for (const key of Object.keys(ansiStyles$2)) { + ansiStyles$2[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2[key].close), 'g'); + styles[key] = { + get() { + const codes = ansiStyles$2[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + + }; + } + + styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } + + }; + ansiStyles$2.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.color.close), 'g'); + + for (const model of Object.keys(ansiStyles$2.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles$2.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles$2.color.close, + closeRe: ansiStyles$2.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + + }; + } + + ansiStyles$2.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.bgColor.close), 'g'); + + for (const model of Object.keys(ansiStyles$2.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles$2.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles$2.bgColor.close, + closeRe: ansiStyles$2.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + + }; + } + + const proto = Object.defineProperties(() => {}, styles); + + function build(_styles, _empty, key) { + const builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + const self = this; + Object.defineProperty(builder, 'level', { + enumerable: true, + + get() { + return self.level; + }, + + set(level) { + self.level = level; + } + + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + + get() { + return self.enabled; + }, + + set(enabled) { + self.enabled = enabled; + } + + }); // See below for fix regarding invisible grey/dim combination on Windows + + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; + } + + function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + + + const originalDim = ansiStyles$2.dim.open; + + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles$2.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + + str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); + } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + + + ansiStyles$2.dim.open = originalDim; + return str; + } + + function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return templates$2(chalk, parts.join('')); + } + + Object.defineProperties(Chalk.prototype, styles); + module.exports = Chalk(); // eslint-disable-line new-cap + + module.exports.supportsColor = stdoutColor; + module.exports.default = module.exports; // For TypeScript + }); + var chalk_1$1 = chalk$2.supportsColor; + + var lib$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.shouldHighlight = shouldHighlight; + exports.getChalk = getChalk; + exports.default = highlight; + + var _jsTokens = _interopRequireWildcard(jsTokens); + + var _esutils = _interopRequireDefault(utils$1); + + var _chalk = _interopRequireDefault(chalk$2); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + + function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); + + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + + return cache; + } + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + + var cache = _getRequireWildcardCache(); + + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + + newObj.default = obj; + + if (cache) { + cache.set(obj, newObj); + } + + return newObj; + } + + function getDefs(chalk) { + return { + keyword: chalk.cyan, + capitalized: chalk.yellow, + jsx_tag: chalk.yellow, + punctuator: chalk.yellow, + number: chalk.magenta, + string: chalk.green, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.white.bgRed.bold + }; + } + + const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + const JSX_TAG = /^[a-z][\w-]*$/i; + const BRACKET = /^[()[\]{}]$/; + + function getTokenType(match) { + const [offset, text] = match.slice(-2); + const token = (0, _jsTokens.matchToToken)(match); + + if (token.type === "name") { + if (_esutils.default.keyword.isReservedWordES6(token.value)) { + return "keyword"; + } + + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) { + return "jsx_tag"; + } + + if (token.value[0] !== token.value[0].toLowerCase()) { + return "capitalized"; + } + } + + if (token.type === "punctuator" && BRACKET.test(token.value)) { + return "bracket"; + } + + if (token.type === "invalid" && (token.value === "@" || token.value === "#")) { + return "punctuator"; + } + + return token.type; + } + + function highlightTokens(defs, text) { + return text.replace(_jsTokens.default, function (...args) { + const type = getTokenType(args); + const colorize = defs[type]; + + if (colorize) { + return args[0].split(NEWLINE).map(str => colorize(str)).join("\n"); + } else { + return args[0]; + } + }); + } + + function shouldHighlight(options) { + return _chalk.default.supportsColor || options.forceColor; + } + + function getChalk(options) { + let chalk = _chalk.default; + + if (options.forceColor) { + chalk = new _chalk.default.constructor({ + enabled: true, + level: 1 + }); + } + + return chalk; + } + + function highlight(code, options = {}) { + if (shouldHighlight(options)) { + const chalk = getChalk(options); + const defs = getDefs(chalk); + return highlightTokens(defs, code); + } else { + return code; + } + } + }); + unwrapExports(lib$1); + var lib_1 = lib$1.shouldHighlight; + var lib_2 = lib$1.getChalk; + + var lib$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.codeFrameColumns = codeFrameColumns; + exports.default = _default; + + var _highlight = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); + + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + + return cache; + } + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + + var cache = _getRequireWildcardCache(); + + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + + newObj.default = obj; + + if (cache) { + cache.set(obj, newObj); + } + + return newObj; + } + + let deprecationWarningShown = false; + + function getDefs(chalk) { + return { + gutter: chalk.grey, + marker: chalk.red.bold, + message: chalk.red.bold + }; + } + + const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + + function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, {}, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + + if (startLine === -1) { + start = 0; + } + + if (endLine === -1) { + end = source.length; + } + + const lineDiff = endLine - startLine; + const markerLines = {}; + + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + + return { + start, + end, + markerLines + }; + } + + function codeFrameColumns(rawLines, loc, opts = {}) { + const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); + const chalk = (0, _highlight.getChalk)(opts); + const defs = getDefs(chalk); + + const maybeHighlight = (chalkFn, string) => { + return highlighted ? chalkFn(string) : string; + }; + + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; + let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = " ".concat(number).slice(-numberMaxWidth); + const gutter = " ".concat(paddedNumber, " | "); + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + + if (hasMarker) { + let markerLine = ""; + + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } + } + + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); + } else { + return " ".concat(maybeHighlight(defs.gutter, gutter)).concat(line); + } + }).join("\n"); + + if (opts.message && !hasColumns) { + frame = "".concat(" ".repeat(numberMaxWidth + 1)).concat(opts.message, "\n").concat(frame); + } + + if (highlighted) { + return chalk.reset(frame); + } else { + return frame; + } + } + + function _default(rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); + } + }); + unwrapExports(lib$2); + var lib_1$1 = lib$2.codeFrameColumns; + + const { + ConfigError: ConfigError$1 + } = errors; + const { + locStart: locStart$1, + locEnd: locEnd$1 + } = loc; // Use defineProperties()/getOwnPropertyDescriptor() to prevent + // triggering the parsers getters. + + const ownNames = Object.getOwnPropertyNames; + const ownDescriptor = Object.getOwnPropertyDescriptor; + + function getParsers(options) { + const parsers = {}; + + for (const plugin of options.plugins) { + if (!plugin.parsers) { + continue; + } + + for (const name of ownNames(plugin.parsers)) { + Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name)); + } + } + + return parsers; + } + + function resolveParser(opts, parsers) { + parsers = parsers || getParsers(opts); + + if (typeof opts.parser === "function") { + // Custom parser API always works with JavaScript. + return { + parse: opts.parser, + astFormat: "estree", + locStart: locStart$1, + locEnd: locEnd$1 + }; + } + + if (typeof opts.parser === "string") { + if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) { + return parsers[opts.parser]; + } + /* istanbul ignore next */ + + + { + throw new ConfigError$1("Couldn't resolve parser \"".concat(opts.parser, "\". Parsers must be explicitly added to the standalone bundle.")); + } + } + } + + function parse(text, opts) { + const parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call + // the parsers getters when actually calling the parser `parse` function. + + const parsersForCustomParserApi = Object.keys(parsers).reduce((object, parserName) => Object.defineProperty(object, parserName, { + enumerable: true, + + get() { + return parsers[parserName].parse; + } + + }), {}); + const parser = resolveParser(opts, parsers); + + try { + if (parser.preprocess) { + text = parser.preprocess(text, opts); + } + + return { + text, + ast: parser.parse(text, parsersForCustomParserApi, opts) + }; + } catch (error) { + const { + loc + } = error; + + if (loc) { + const codeFrame = lib$2; + error.codeFrame = codeFrame.codeFrameColumns(text, loc, { + highlightCode: true + }); + error.message += "\n" + error.codeFrame; + throw error; + } + /* istanbul ignore next */ + + + throw error.stack; + } + } + + var parser = { + parse, + resolveParser + }; + + const { + UndefinedParserError: UndefinedParserError$1 + } = errors; + const { + getSupportInfo: getSupportInfo$1 + } = support; + const { + resolveParser: resolveParser$1 + } = parser; + const hiddenDefaults = { + astFormat: "estree", + printer: {}, + originalText: undefined, + locStart: null, + locEnd: null + }; // Copy options and fill in default values. + + function normalize$1(options, opts) { + opts = opts || {}; + const rawOptions = Object.assign({}, options); + const supportOptions = getSupportInfo$1({ + plugins: options.plugins, + showUnreleased: true, + showDeprecated: true + }).options; + const defaults = Object.assign({}, hiddenDefaults, {}, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default]))); + + if (!rawOptions.parser) { + if (!rawOptions.filepath) { + const logger = opts.logger || console; + logger.warn("No parser and no filepath given, using 'babel' the parser now " + "but this will throw an error in the future. " + "Please specify a parser or a filepath so one can be inferred."); + rawOptions.parser = "babel"; + } else { + rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins); + + if (!rawOptions.parser) { + throw new UndefinedParserError$1("No parser could be inferred for file: ".concat(rawOptions.filepath)); + } + } + } + + const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === "parser")], { + passThrough: true, + logger: false + })); + rawOptions.astFormat = parser.astFormat; + rawOptions.locEnd = parser.locEnd; + rawOptions.locStart = parser.locStart; + const plugin = getPlugin(rawOptions); + rawOptions.printer = plugin.printers[rawOptions.astFormat]; + const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, { + [optionInfo.name]: optionInfo.pluginDefaults[plugin.name] + }), {}); + const mixedDefaults = Object.assign({}, defaults, {}, pluginDefaults); + Object.keys(mixedDefaults).forEach(k => { + if (rawOptions[k] == null) { + rawOptions[k] = mixedDefaults[k]; + } + }); + + if (rawOptions.parser === "json") { + rawOptions.trailingComma = "none"; + } + + return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({ + passThrough: Object.keys(hiddenDefaults) + }, opts)); + } + + function getPlugin(options) { + const { + astFormat + } = options; + + if (!astFormat) { + throw new Error("getPlugin() requires astFormat to be set"); + } + + const printerPlugin = options.plugins.find(plugin => plugin.printers && plugin.printers[astFormat]); + + if (!printerPlugin) { + throw new Error("Couldn't find plugin for AST format \"".concat(astFormat, "\"")); + } + + return printerPlugin; + } + + function getInterpreter(filepath) { + if (typeof filepath !== "string") { + return ""; + } + + let fd; + + try { + fd = fs.openSync(filepath, "r"); + } catch (err) { + // istanbul ignore next + return ""; + } + + try { + const liner = new readlines(fd); + const firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node + + const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/); + + if (m1) { + return m1[1]; + } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node + + + const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/); + + if (m2) { + return m2[1]; + } + + return ""; + } catch (err) { + // There are some weird cases where paths are missing, causing Jest + // failures. It's unclear what these correspond to in the real world. + return ""; + } finally { + try { + // There are some weird cases where paths are missing, causing Jest + // failures. It's unclear what these correspond to in the real world. + fs.closeSync(fd); + } catch (err) {// nop + } + } + } + + function inferParser(filepath, plugins) { + const filename = path.basename(filepath).toLowerCase(); + const languages = getSupportInfo$1({ + plugins + }).languages.filter(language => language.since !== null); // If the file has no extension, we can try to infer the language from the + // interpreter in the shebang line, if any; but since this requires FS access, + // do it last. + + let language = languages.find(language => language.extensions && language.extensions.some(extension => filename.endsWith(extension)) || language.filenames && language.filenames.find(name => name.toLowerCase() === filename)); + + if (!language && !filename.includes(".")) { + const interpreter = getInterpreter(filepath); + language = languages.find(language => language.interpreters && language.interpreters.includes(interpreter)); + } + + return language && language.parsers[0]; + } + + var options$1 = { + normalize: normalize$1, + hiddenDefaults, + inferParser + }; + + function massageAST(ast, options, parent) { + if (Array.isArray(ast)) { + return ast.map(e => massageAST(e, options, parent)).filter(Boolean); + } + + if (!ast || typeof ast !== "object") { + return ast; + } + + const newObj = {}; + + for (const key of Object.keys(ast)) { + if (typeof ast[key] !== "function") { + newObj[key] = massageAST(ast[key], options, ast); + } + } + + if (options.printer.massageAstNode) { + const result = options.printer.massageAstNode(ast, newObj, parent); + + if (result === null) { + return undefined; + } + + if (result) { + return result; + } + } + + return newObj; + } + + var massageAst = massageAST; + + function assert() {} + + assert.ok = function () {}; + + assert.strictEqual = function () {}; + + /** + * @param {Doc[]} parts + * @returns Doc + */ + + + function concat(parts) { + // access the internals of a document directly. + // if(parts.length === 1) { + // // If it's a single document, no need to concat it. + // return parts[0]; + // } + + + return { + type: "concat", + parts + }; + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function indent(contents) { + + return { + type: "indent", + contents + }; + } + /** + * @param {number} n + * @param {Doc} contents + * @returns Doc + */ + + + function align(n, contents) { + + return { + type: "align", + contents, + n + }; + } + /** + * @param {Doc} contents + * @param {object} [opts] - TBD ??? + * @returns Doc + */ + + + function group(contents, opts) { + opts = opts || {}; + + return { + type: "group", + id: opts.id, + contents, + break: !!opts.shouldBreak, + expandedStates: opts.expandedStates + }; + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function dedentToRoot(contents) { + return align(-Infinity, contents); + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function markAsRoot(contents) { + // @ts-ignore - TBD ???: + return align({ + type: "root" + }, contents); + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function dedent(contents) { + return align(-1, contents); + } + /** + * @param {Doc[]} states + * @param {object} [opts] - TBD ??? + * @returns Doc + */ + + + function conditionalGroup(states, opts) { + return group(states[0], Object.assign({}, opts, { + expandedStates: states + })); + } + /** + * @param {Doc[]} parts + * @returns Doc + */ + + + function fill(parts) { + + return { + type: "fill", + parts + }; + } + /** + * @param {Doc} [breakContents] + * @param {Doc} [flatContents] + * @param {object} [opts] - TBD ??? + * @returns Doc + */ + + + function ifBreak(breakContents, flatContents, opts) { + opts = opts || {}; + + return { + type: "if-break", + breakContents, + flatContents, + groupId: opts.groupId + }; + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function lineSuffix(contents) { + + return { + type: "line-suffix", + contents + }; + } + + const lineSuffixBoundary = { + type: "line-suffix-boundary" + }; + const breakParent = { + type: "break-parent" + }; + const trim = { + type: "trim" + }; + const line = { + type: "line" + }; + const softline = { + type: "line", + soft: true + }; + const hardline = concat([{ + type: "line", + hard: true + }, breakParent]); + const literalline = concat([{ + type: "line", + hard: true, + literal: true + }, breakParent]); + const cursor = { + type: "cursor", + placeholder: Symbol("cursor") + }; + /** + * @param {Doc} sep + * @param {Doc[]} arr + * @returns Doc + */ + + function join(sep, arr) { + const res = []; + + for (let i = 0; i < arr.length; i++) { + if (i !== 0) { + res.push(sep); + } + + res.push(arr[i]); + } + + return concat(res); + } + /** + * @param {Doc} doc + * @param {number} size + * @param {number} tabWidth + */ + + + function addAlignmentToDoc(doc, size, tabWidth) { + let aligned = doc; + + if (size > 0) { + // Use indent to add tabs for all the levels of tabs we need + for (let i = 0; i < Math.floor(size / tabWidth); ++i) { + aligned = indent(aligned); + } // Use align for all the spaces that are needed + + + aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current + // indentation, so we use -Infinity to reset the indentation to 0 + + aligned = align(-Infinity, aligned); + } + + return aligned; + } + + var docBuilders = { + concat, + join, + line, + softline, + hardline, + literalline, + group, + conditionalGroup, + fill, + lineSuffix, + lineSuffixBoundary, + cursor, + breakParent, + ifBreak, + trim, + indent, + align, + addAlignmentToDoc, + markAsRoot, + dedentToRoot, + dedent + }; + + var ansiRegex = ({ + onlyFirst = false + } = {}) => { + const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|'); + return new RegExp(pattern, onlyFirst ? undefined : 'g'); + }; + + var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + + /* eslint-disable yoda */ + + const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + + + if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals + 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A + 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables + 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs + 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms + 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants + 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms + 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement + 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement + 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + 0x20000 <= codePoint && codePoint <= 0x3FFFD)) { + return true; + } + + return false; + }; + + var isFullwidthCodePoint_1 = isFullwidthCodePoint; + var default_1$1 = isFullwidthCodePoint; + isFullwidthCodePoint_1.default = default_1$1; + + var emojiRegex = function emojiRegex() { + // https://mths.be/emoji + 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\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; + }; + + const stringWidth = string => { + string = string.replace(emojiRegex(), ' '); + + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); // Ignore control characters + + if (code <= 0x1F || code >= 0x7F && code <= 0x9F) { + continue; + } // Ignore combining characters + + + if (code >= 0x300 && code <= 0x36F) { + continue; + } // Surrogates + + + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint_1(code) ? 2 : 1; + } + + return width; + }; + + var stringWidth_1 = stringWidth; // TODO: remove this in the next major version + + var default_1$2 = stringWidth; + stringWidth_1.default = default_1$2; + + const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g; + + var escapeStringRegexp$2 = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + + return string.replace(matchOperatorsRegex, '\\$&'); + }; + + const notAsciiRegex = /[^\x20-\x7F]/; + + function getPenultimate(arr) { + if (arr.length > 1) { + return arr[arr.length - 2]; + } + + return null; + } + /** + * @typedef {{backwards?: boolean}} SkipOptions + */ + + /** + * @param {string | RegExp} chars + * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + + function skip(chars) { + return (text, index, opts) => { + const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having + // to check for failures (did someone say monads?). + + if (index === false) { + return false; + } + + const { + length + } = text; + let cursor = index; + + while (cursor >= 0 && cursor < length) { + const c = text.charAt(cursor); + + if (chars instanceof RegExp) { + if (!chars.test(c)) { + return cursor; + } + } else if (!chars.includes(c)) { + return cursor; + } + + backwards ? cursor-- : cursor++; + } + + if (cursor === -1 || cursor === length) { + // If we reached the beginning or end of the file, return the + // out-of-bounds cursor. It's up to the caller to handle this + // correctly. We don't want to indicate `false` though if it + // actually skipped valid characters. + return cursor; + } + + return false; + }; + } + /** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + + const skipWhitespace = skip(/\s/); + /** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + const skipSpaces = skip(" \t"); + /** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + const skipToLineEnd = skip(",; \t"); + /** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + const skipEverythingButNewLine = skip(/[^\r\n]/); + /** + * @param {string} text + * @param {number | false} index + * @returns {number | false} + */ + + function skipInlineComment(text, index) { + if (index === false) { + return false; + } + + if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") { + for (let i = index + 2; i < text.length; ++i) { + if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") { + return i + 2; + } + } + } + + return index; + } + /** + * @param {string} text + * @param {number | false} index + * @returns {number | false} + */ + + + function skipTrailingComment(text, index) { + if (index === false) { + return false; + } + + if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") { + return skipEverythingButNewLine(text, index); + } + + return index; + } // This one doesn't use the above helper function because it wants to + // test \r\n in order and `skip` doesn't support ordering and we only + // want to skip one newline. It's simple to implement. + + /** + * @param {string} text + * @param {number | false} index + * @param {SkipOptions=} opts + * @returns {number | false} + */ + + + function skipNewline(text, index, opts) { + const backwards = opts && opts.backwards; + + if (index === false) { + return false; + } + + const atIndex = text.charAt(index); + + if (backwards) { + if (text.charAt(index - 1) === "\r" && atIndex === "\n") { + return index - 2; + } + + if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { + return index - 1; + } + } else { + if (atIndex === "\r" && text.charAt(index + 1) === "\n") { + return index + 2; + } + + if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { + return index + 1; + } + } + + return index; + } + /** + * @param {string} text + * @param {number} index + * @param {SkipOptions=} opts + * @returns {boolean} + */ + + + function hasNewline(text, index, opts) { + opts = opts || {}; + const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); + const idx2 = skipNewline(text, idx, opts); + return idx !== idx2; + } + /** + * @param {string} text + * @param {number} start + * @param {number} end + * @returns {boolean} + */ + + + function hasNewlineInRange(text, start, end) { + for (let i = start; i < end; ++i) { + if (text.charAt(i) === "\n") { + return true; + } + } + + return false; + } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty + + /** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locStart + */ + + + function isPreviousLineEmpty(text, node, locStart) { + /** @type {number | false} */ + let idx = locStart(node) - 1; + idx = skipSpaces(text, idx, { + backwards: true + }); + idx = skipNewline(text, idx, { + backwards: true + }); + idx = skipSpaces(text, idx, { + backwards: true + }); + const idx2 = skipNewline(text, idx, { + backwards: true + }); + return idx !== idx2; + } + /** + * @param {string} text + * @param {number} index + * @returns {boolean} + */ + + + function isNextLineEmptyAfterIndex(text, index) { + /** @type {number | false} */ + let oldIdx = null; + /** @type {number | false} */ + + let idx = index; + + while (idx !== oldIdx) { + // We need to skip all the potential trailing inline comments + oldIdx = idx; + idx = skipToLineEnd(text, idx); + idx = skipInlineComment(text, idx); + idx = skipSpaces(text, idx); + } + + idx = skipTrailingComment(text, idx); + idx = skipNewline(text, idx); + return idx !== false && hasNewline(text, idx); + } + /** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locEnd + * @returns {boolean} + */ + + + function isNextLineEmpty(text, node, locEnd) { + return isNextLineEmptyAfterIndex(text, locEnd(node)); + } + /** + * @param {string} text + * @param {number} idx + * @returns {number | false} + */ + + + function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) { + /** @type {number | false} */ + let oldIdx = null; + /** @type {number | false} */ + + let nextIdx = idx; + + while (nextIdx !== oldIdx) { + oldIdx = nextIdx; + nextIdx = skipSpaces(text, nextIdx); + nextIdx = skipInlineComment(text, nextIdx); + nextIdx = skipTrailingComment(text, nextIdx); + nextIdx = skipNewline(text, nextIdx); + } + + return nextIdx; + } + /** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locEnd + * @returns {number | false} + */ + + + function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) { + return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node)); + } + /** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locEnd + * @returns {string} + */ + + + function getNextNonSpaceNonCommentCharacter(text, node, locEnd) { + return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback? + getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)); + } + /** + * @param {string} text + * @param {number} index + * @param {SkipOptions=} opts + * @returns {boolean} + */ + + + function hasSpaces(text, index, opts) { + opts = opts || {}; + const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); + return idx !== index; + } + /** + * @param {{range?: [number, number], start?: number}} node + * @param {number} index + */ + + + function setLocStart(node, index) { + if (node.range) { + node.range[0] = index; + } else { + node.start = index; + } + } + /** + * @param {{range?: [number, number], end?: number}} node + * @param {number} index + */ + + + function setLocEnd(node, index) { + if (node.range) { + node.range[1] = index; + } else { + node.end = index; + } + } + + const PRECEDENCE = {}; + [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => { + tier.forEach(op => { + PRECEDENCE[op] = i; + }); + }); + + function getPrecedence(op) { + return PRECEDENCE[op]; + } + + const equalityOperators = { + "==": true, + "!=": true, + "===": true, + "!==": true + }; + const multiplicativeOperators = { + "*": true, + "/": true, + "%": true + }; + const bitshiftOperators = { + ">>": true, + ">>>": true, + "<<": true + }; + + function shouldFlatten(parentOp, nodeOp) { + if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) { + return false; + } // ** is right-associative + // x ** y ** z --> x ** (y ** z) + + + if (parentOp === "**") { + return false; + } // x == y == z --> (x == y) == z + + + if (equalityOperators[parentOp] && equalityOperators[nodeOp]) { + return false; + } // x * y % z --> (x * y) % z + + + if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) { + return false; + } // x * y / z --> (x * y) / z + // x / y * z --> (x / y) * z + + + if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) { + return false; + } // x << y << z --> (x << y) << z + + + if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) { + return false; + } + + return true; + } + + function isBitwiseOperator(operator) { + return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&"; + } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr + // holds) `function`, `class`, or `do {}`. Will be overzealous if there's + // already necessary grouping parentheses. + + + function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) { + node = getLeftMost(node); + + switch (node.type) { + case "FunctionExpression": + case "ClassExpression": + case "DoExpression": + return forbidFunctionClassAndDoExpr; + + case "ObjectExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); + + case "TaggedTemplateExpression": + if (node.tag.type === "FunctionExpression") { + // IIFEs are always already parenthesized + return false; + } + + return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr); + + case "CallExpression": + case "OptionalCallExpression": + if (node.callee.type === "FunctionExpression") { + // IIFEs are always already parenthesized + return false; + } + + return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr); + + case "ConditionalExpression": + return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr); + + case "UpdateExpression": + return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr); + + case "BindExpression": + return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); + + case "SequenceExpression": + return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr); + + case "TSAsExpression": + return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr); + + default: + return false; + } + } + + function getLeftMost(node) { + if (node.left) { + return getLeftMost(node.left); + } + + return node; + } + /** + * @param {string} value + * @param {number} tabWidth + * @param {number=} startIndex + * @returns {number} + */ + + + function getAlignmentSize(value, tabWidth, startIndex) { + startIndex = startIndex || 0; + let size = 0; + + for (let i = startIndex; i < value.length; ++i) { + if (value[i] === "\t") { + // Tabs behave in a way that they are aligned to the nearest + // multiple of tabWidth: + // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4 + // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ... + size = size + tabWidth - size % tabWidth; + } else { + size++; + } + } + + return size; + } + /** + * @param {string} value + * @param {number} tabWidth + * @returns {number} + */ + + + function getIndentSize(value, tabWidth) { + const lastNewlineIndex = value.lastIndexOf("\n"); + + if (lastNewlineIndex === -1) { + return 0; + } + + return getAlignmentSize( // All the leading whitespaces + value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth); + } + /** + * @typedef {'"' | "'"} Quote + */ + + /** + * + * @param {string} raw + * @param {Quote} preferredQuote + * @returns {Quote} + */ + + + function getPreferredQuote(raw, preferredQuote) { + // `rawContent` is the string exactly like it appeared in the input source + // code, without its enclosing quotes. + const rawContent = raw.slice(1, -1); + /** @type {{ quote: '"', regex: RegExp }} */ + + const double = { + quote: '"', + regex: /"/g + }; + /** @type {{ quote: "'", regex: RegExp }} */ + + const single = { + quote: "'", + regex: /'/g + }; + const preferred = preferredQuote === "'" ? single : double; + const alternate = preferred === single ? double : single; + let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing + // the string, we might want to enclose with the alternate quote instead, to + // minimize the number of escaped quotes. + + if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) { + const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length; + const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length; + result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote; + } + + return result; + } + + function printString(raw, options, isDirectiveLiteral) { + // `rawContent` is the string exactly like it appeared in the input source + // code, without its enclosing quotes. + const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap + // the quotes on a DirectiveLiteral. + + const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'"); + /** @type {Quote} */ + + const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't + // change the escape sequences they use. + // See https://github.com/prettier/prettier/issues/1555 + // and https://tc39.github.io/ecma262/#directive-prologue + + if (isDirectiveLiteral) { + if (canChangeDirectiveQuotes) { + return enclosingQuote + rawContent + enclosingQuote; + } + + return raw; + } // It might sound unnecessary to use `makeString` even if the string already + // is enclosed with `enclosingQuote`, but it isn't. The string could contain + // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes + // sure that we consistently output the minimum amount of escaped quotes. + + + return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml)); + } + /** + * @param {string} rawContent + * @param {Quote} enclosingQuote + * @param {boolean=} unescapeUnnecessaryEscapes + * @returns {string} + */ + + + function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) { + const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double). + + const regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to + // enclose `rawContent` with `enclosingQuote`. + + const newContent = rawContent.replace(regex, (match, escaped, quote) => { + // If we matched an escape, and the escaped character is a quote of the + // other type than we intend to enclose the string with, there's no need for + // it to be escaped, so return it _without_ the backslash. + if (escaped === otherQuote) { + return escaped; + } // If we matched an unescaped quote and it is of the _same_ type as we + // intend to enclose the string with, it must be escaped, so return it with + // a backslash. + + + if (quote === enclosingQuote) { + return "\\" + quote; + } + + if (quote) { + return quote; + } // Unescape any unnecessarily escaped character. + // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27 + + + return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped; + }); + return enclosingQuote + newContent + enclosingQuote; + } + + function printNumber(rawNumber) { + return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation. + .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0). + .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit. + .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes. + .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot. + .replace(/\.(?=e|$)/, ""); + } + /** + * @param {string} str + * @param {string} target + * @returns {number} + */ + + + function getMaxContinuousCount(str, target) { + const results = str.match(new RegExp("(".concat(escapeStringRegexp$2(target), ")+"), "g")); + + if (results === null) { + return 0; + } + + return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0); + } + + function getMinNotPresentContinuousCount(str, target) { + const matches = str.match(new RegExp("(".concat(escapeStringRegexp$2(target), ")+"), "g")); + + if (matches === null) { + return 0; + } + + const countPresent = new Map(); + let max = 0; + + for (const match of matches) { + const count = match.length / target.length; + countPresent.set(count, true); + + if (count > max) { + max = count; + } + } + + for (let i = 1; i < max; i++) { + if (!countPresent.get(i)) { + return i; + } + } + + return max + 1; + } + /** + * @param {string} text + * @returns {number} + */ + + + function getStringWidth(text) { + if (!text) { + return 0; + } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width` + + + if (!notAsciiRegex.test(text)) { + return text.length; + } + + return stringWidth_1(text); + } + + function hasIgnoreComment(path) { + const node = path.getValue(); + return hasNodeIgnoreComment(node); + } + + function hasNodeIgnoreComment(node) { + return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore); + } + + function isNodeIgnoreComment(comment) { + return comment.value.trim() === "prettier-ignore"; + } + + function addCommentHelper(node, comment) { + const comments = node.comments || (node.comments = []); + comments.push(comment); + comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment + // We already "print" it via the raw text, we don't need to re-print it as a + // comment + + if (node.type === "JSXText") { + comment.printed = true; + } + } + + function addLeadingComment(node, comment) { + comment.leading = true; + comment.trailing = false; + addCommentHelper(node, comment); + } + + function addDanglingComment(node, comment) { + comment.leading = false; + comment.trailing = false; + addCommentHelper(node, comment); + } + + function addTrailingComment(node, comment) { + comment.leading = false; + comment.trailing = true; + addCommentHelper(node, comment); + } + + function isWithinParentArrayProperty(path, propertyName) { + const node = path.getValue(); + const parent = path.getParentNode(); + + if (parent == null) { + return false; + } + + if (!Array.isArray(parent[propertyName])) { + return false; + } + + const key = path.getName(); + return parent[propertyName][key] === node; + } + + function replaceEndOfLineWith(text, replacement) { + const parts = []; + + for (const part of text.split("\n")) { + if (parts.length !== 0) { + parts.push(replacement); + } + + parts.push(part); + } + + return parts; + } + + var util$1 = { + replaceEndOfLineWith, + getStringWidth, + getMaxContinuousCount, + getMinNotPresentContinuousCount, + getPrecedence, + shouldFlatten, + isBitwiseOperator, + getPenultimate, + getLast, + getNextNonSpaceNonCommentCharacterIndexWithStartIndex, + getNextNonSpaceNonCommentCharacterIndex, + getNextNonSpaceNonCommentCharacter, + skip, + skipWhitespace, + skipSpaces, + skipToLineEnd, + skipEverythingButNewLine, + skipInlineComment, + skipTrailingComment, + skipNewline, + isNextLineEmptyAfterIndex, + isNextLineEmpty, + isPreviousLineEmpty, + hasNewline, + hasNewlineInRange, + hasSpaces, + setLocStart, + setLocEnd, + startsWithNoLookaheadToken, + getAlignmentSize, + getIndentSize, + getPreferredQuote, + printString, + printNumber, + hasIgnoreComment, + hasNodeIgnoreComment, + isNodeIgnoreComment, + makeString, + addLeadingComment, + addDanglingComment, + addTrailingComment, + isWithinParentArrayProperty + }; + + function guessEndOfLine(text) { + const index = text.indexOf("\r"); + + if (index >= 0) { + return text.charAt(index + 1) === "\n" ? "crlf" : "cr"; + } + + return "lf"; + } + + function convertEndOfLineToChars(value) { + switch (value) { + case "cr": + return "\r"; + + case "crlf": + return "\r\n"; + + default: + return "\n"; + } + } + + var endOfLine = { + guessEndOfLine, + convertEndOfLineToChars + }; + + const { + getStringWidth: getStringWidth$1 + } = util$1; + const { + convertEndOfLineToChars: convertEndOfLineToChars$1 + } = endOfLine; + const { + concat: concat$1, + fill: fill$1, + cursor: cursor$1 + } = docBuilders; + /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */ + + let groupModeMap; + const MODE_BREAK = 1; + const MODE_FLAT = 2; + + function rootIndent() { + return { + value: "", + length: 0, + queue: [] + }; + } + + function makeIndent(ind, options) { + return generateInd(ind, { + type: "indent" + }, options); + } + + function makeAlign(ind, n, options) { + return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, { + type: "dedent" + }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, { + root: ind + }) : typeof n === "string" ? generateInd(ind, { + type: "stringAlign", + n + }, options) : generateInd(ind, { + type: "numberAlign", + n + }, options); + } + + function generateInd(ind, newPart, options) { + const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart); + let value = ""; + let length = 0; + let lastTabs = 0; + let lastSpaces = 0; + + for (const part of queue) { + switch (part.type) { + case "indent": + flush(); + + if (options.useTabs) { + addTabs(1); + } else { + addSpaces(options.tabWidth); + } + + break; + + case "stringAlign": + flush(); + value += part.n; + length += part.n.length; + break; + + case "numberAlign": + lastTabs += 1; + lastSpaces += part.n; + break; + + /* istanbul ignore next */ + + default: + throw new Error("Unexpected type '".concat(part.type, "'")); + } + } + + flushSpaces(); + return Object.assign({}, ind, { + value, + length, + queue + }); + + function addTabs(count) { + value += "\t".repeat(count); + length += options.tabWidth * count; + } + + function addSpaces(count) { + value += " ".repeat(count); + length += count; + } + + function flush() { + if (options.useTabs) { + flushTabs(); + } else { + flushSpaces(); + } + } + + function flushTabs() { + if (lastTabs > 0) { + addTabs(lastTabs); + } + + resetLast(); + } + + function flushSpaces() { + if (lastSpaces > 0) { + addSpaces(lastSpaces); + } + + resetLast(); + } + + function resetLast() { + lastTabs = 0; + lastSpaces = 0; + } + } + + function trim$1(out) { + if (out.length === 0) { + return 0; + } + + let trimCount = 0; // Trim whitespace at the end of line + + while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) { + trimCount += out.pop().length; + } + + if (out.length && typeof out[out.length - 1] === "string") { + const trimmed = out[out.length - 1].replace(/[ \t]*$/, ""); + trimCount += out[out.length - 1].length - trimmed.length; + out[out.length - 1] = trimmed; + } + + return trimCount; + } + + function fits(next, restCommands, width, options, mustBeFlat) { + let restIdx = restCommands.length; + const cmds = [next]; // `out` is only used for width counting because `trim` requires to look + // backwards for space characters. + + const out = []; + + while (width >= 0) { + if (cmds.length === 0) { + if (restIdx === 0) { + return true; + } + + cmds.push(restCommands[restIdx - 1]); + restIdx--; + continue; + } + + const [ind, mode, doc] = cmds.pop(); + + if (typeof doc === "string") { + out.push(doc); + width -= getStringWidth$1(doc); + } else { + switch (doc.type) { + case "concat": + for (let i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "indent": + cmds.push([makeIndent(ind, options), mode, doc.contents]); + break; + + case "align": + cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); + break; + + case "trim": + width += trim$1(out); + break; + + case "group": + if (mustBeFlat && doc.break) { + return false; + } + + cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]); + + if (doc.id) { + groupModeMap[doc.id] = cmds[cmds.length - 1][1]; + } + + break; + + case "fill": + for (let i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "if-break": + { + const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; + + if (groupMode === MODE_BREAK) { + if (doc.breakContents) { + cmds.push([ind, mode, doc.breakContents]); + } + } + + if (groupMode === MODE_FLAT) { + if (doc.flatContents) { + cmds.push([ind, mode, doc.flatContents]); + } + } + + break; + } + + case "line": + switch (mode) { + // fallthrough + case MODE_FLAT: + if (!doc.hard) { + if (!doc.soft) { + out.push(" "); + width -= 1; + } + + break; + } + + return true; + + case MODE_BREAK: + return true; + } + + break; + } + } + } + + return false; + } + + function printDocToString(doc, options) { + groupModeMap = {}; + const width = options.printWidth; + const newLine = convertEndOfLineToChars$1(options.endOfLine); + let pos = 0; // cmds is basically a stack. We've turned a recursive call into a + // while loop which is much faster. The while loop below adds new + // cmds to the array instead of recursively calling `print`. + + const cmds = [[rootIndent(), MODE_BREAK, doc]]; + const out = []; + let shouldRemeasure = false; + let lineSuffix = []; + + while (cmds.length !== 0) { + const [ind, mode, doc] = cmds.pop(); + + if (typeof doc === "string") { + const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc; + out.push(formatted); + pos += getStringWidth$1(formatted); + } else { + switch (doc.type) { + case "cursor": + out.push(cursor$1.placeholder); + break; + + case "concat": + for (let i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "indent": + cmds.push([makeIndent(ind, options), mode, doc.contents]); + break; + + case "align": + cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); + break; + + case "trim": + pos -= trim$1(out); + break; + + case "group": + switch (mode) { + case MODE_FLAT: + if (!shouldRemeasure) { + cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]); + break; + } + + // fallthrough + + case MODE_BREAK: + { + shouldRemeasure = false; + const next = [ind, MODE_FLAT, doc.contents]; + const rem = width - pos; + + if (!doc.break && fits(next, cmds, rem, options)) { + cmds.push(next); + } else { + // Expanded states are a rare case where a document + // can manually provide multiple representations of + // itself. It provides an array of documents + // going from the least expanded (most flattened) + // representation first to the most expanded. If a + // group has these, we need to manually go through + // these states and find the first one that fits. + if (doc.expandedStates) { + const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1]; + + if (doc.break) { + cmds.push([ind, MODE_BREAK, mostExpanded]); + break; + } else { + for (let i = 1; i < doc.expandedStates.length + 1; i++) { + if (i >= doc.expandedStates.length) { + cmds.push([ind, MODE_BREAK, mostExpanded]); + break; + } else { + const state = doc.expandedStates[i]; + const cmd = [ind, MODE_FLAT, state]; + + if (fits(cmd, cmds, rem, options)) { + cmds.push(cmd); + break; + } + } + } + } + } else { + cmds.push([ind, MODE_BREAK, doc.contents]); + } + } + + break; + } + } + + if (doc.id) { + groupModeMap[doc.id] = cmds[cmds.length - 1][1]; + } + + break; + // Fills each line with as much code as possible before moving to a new + // line with the same indentation. + // + // Expects doc.parts to be an array of alternating content and + // whitespace. The whitespace contains the linebreaks. + // + // For example: + // ["I", line, "love", line, "monkeys"] + // or + // [{ type: group, ... }, softline, { type: group, ... }] + // + // It uses this parts structure to handle three main layout cases: + // * The first two content items fit on the same line without + // breaking + // -> output the first content item and the whitespace "flat". + // * Only the first content item fits on the line without breaking + // -> output the first content item "flat" and the whitespace with + // "break". + // * Neither content item fits on the line without breaking + // -> output the first content item and the whitespace with "break". + + case "fill": + { + const rem = width - pos; + const { + parts + } = doc; + + if (parts.length === 0) { + break; + } + + const [content, whitespace] = parts; + const contentFlatCmd = [ind, MODE_FLAT, content]; + const contentBreakCmd = [ind, MODE_BREAK, content]; + const contentFits = fits(contentFlatCmd, [], rem, options, true); + + if (parts.length === 1) { + if (contentFits) { + cmds.push(contentFlatCmd); + } else { + cmds.push(contentBreakCmd); + } + + break; + } + + const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace]; + const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace]; + + if (parts.length === 2) { + if (contentFits) { + cmds.push(whitespaceFlatCmd); + cmds.push(contentFlatCmd); + } else { + cmds.push(whitespaceBreakCmd); + cmds.push(contentBreakCmd); + } + + break; + } // At this point we've handled the first pair (context, separator) + // and will create a new fill doc for the rest of the content. + // Ideally we wouldn't mutate the array here but copying all the + // elements to a new array would make this algorithm quadratic, + // which is unusable for large arrays (e.g. large texts in JSX). + + + parts.splice(0, 2); + const remainingCmd = [ind, mode, fill$1(parts)]; + const secondContent = parts[0]; + const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])]; + const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true); + + if (firstAndSecondContentFits) { + cmds.push(remainingCmd); + cmds.push(whitespaceFlatCmd); + cmds.push(contentFlatCmd); + } else if (contentFits) { + cmds.push(remainingCmd); + cmds.push(whitespaceBreakCmd); + cmds.push(contentFlatCmd); + } else { + cmds.push(remainingCmd); + cmds.push(whitespaceBreakCmd); + cmds.push(contentBreakCmd); + } + + break; + } + + case "if-break": + { + const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; + + if (groupMode === MODE_BREAK) { + if (doc.breakContents) { + cmds.push([ind, mode, doc.breakContents]); + } + } + + if (groupMode === MODE_FLAT) { + if (doc.flatContents) { + cmds.push([ind, mode, doc.flatContents]); + } + } + + break; + } + + case "line-suffix": + lineSuffix.push([ind, mode, doc.contents]); + break; + + case "line-suffix-boundary": + if (lineSuffix.length > 0) { + cmds.push([ind, mode, { + type: "line", + hard: true + }]); + } + + break; + + case "line": + switch (mode) { + case MODE_FLAT: + if (!doc.hard) { + if (!doc.soft) { + out.push(" "); + pos += 1; + } + + break; + } else { + // This line was forced into the output even if we + // were in flattened mode, so we need to tell the next + // group that no matter what, it needs to remeasure + // because the previous measurement didn't accurately + // capture the entire expression (this is necessary + // for nested groups) + shouldRemeasure = true; + } + + // fallthrough + + case MODE_BREAK: + if (lineSuffix.length) { + cmds.push([ind, mode, doc]); + cmds.push(...lineSuffix.reverse()); + lineSuffix = []; + break; + } + + if (doc.literal) { + if (ind.root) { + out.push(newLine, ind.root.value); + pos = ind.root.length; + } else { + out.push(newLine); + pos = 0; + } + } else { + pos -= trim$1(out); + out.push(newLine + ind.value); + pos = ind.length; + } + + break; + } + + break; + } + } + } + + const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder); + + if (cursorPlaceholderIndex !== -1) { + const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1); + const beforeCursor = out.slice(0, cursorPlaceholderIndex).join(""); + const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join(""); + const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join(""); + return { + formatted: beforeCursor + aroundCursor + afterCursor, + cursorNodeStart: beforeCursor.length, + cursorNodeText: aroundCursor + }; + } + + return { + formatted: out.join("") + }; + } + + var docPrinter = { + printDocToString + }; + + const traverseDocOnExitStackMarker = {}; + + function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { + const docsStack = [doc]; + + while (docsStack.length !== 0) { + const doc = docsStack.pop(); + + if (doc === traverseDocOnExitStackMarker) { + onExit(docsStack.pop()); + continue; + } + + let shouldRecurse = true; + + if (onEnter) { + if (onEnter(doc) === false) { + shouldRecurse = false; + } + } + + if (onExit) { + docsStack.push(doc); + docsStack.push(traverseDocOnExitStackMarker); + } + + if (shouldRecurse) { + // When there are multiple parts to process, + // the parts need to be pushed onto the stack in reverse order, + // so that they are processed in the original order + // when the stack is popped. + if (doc.type === "concat" || doc.type === "fill") { + for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) { + docsStack.push(doc.parts[i]); + } + } else if (doc.type === "if-break") { + if (doc.flatContents) { + docsStack.push(doc.flatContents); + } + + if (doc.breakContents) { + docsStack.push(doc.breakContents); + } + } else if (doc.type === "group" && doc.expandedStates) { + if (shouldTraverseConditionalGroups) { + for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) { + docsStack.push(doc.expandedStates[i]); + } + } else { + docsStack.push(doc.contents); + } + } else if (doc.contents) { + docsStack.push(doc.contents); + } + } + } + } + + function mapDoc(doc, cb) { + if (doc.type === "concat" || doc.type === "fill") { + const parts = doc.parts.map(part => mapDoc(part, cb)); + return cb(Object.assign({}, doc, { + parts + })); + } else if (doc.type === "if-break") { + const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb); + const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb); + return cb(Object.assign({}, doc, { + breakContents, + flatContents + })); + } else if (doc.contents) { + const contents = mapDoc(doc.contents, cb); + return cb(Object.assign({}, doc, { + contents + })); + } + + return cb(doc); + } + + function findInDoc(doc, fn, defaultValue) { + let result = defaultValue; + let hasStopped = false; + + function findInDocOnEnterFn(doc) { + const maybeResult = fn(doc); + + if (maybeResult !== undefined) { + hasStopped = true; + result = maybeResult; + } + + if (hasStopped) { + return false; + } + } + + traverseDoc(doc, findInDocOnEnterFn); + return result; + } + + function isEmpty(n) { + return typeof n === "string" && n.length === 0; + } + + function isLineNextFn(doc) { + if (typeof doc === "string") { + return false; + } + + if (doc.type === "line") { + return true; + } + } + + function isLineNext(doc) { + return findInDoc(doc, isLineNextFn, false); + } + + function willBreakFn(doc) { + if (doc.type === "group" && doc.break) { + return true; + } + + if (doc.type === "line" && doc.hard) { + return true; + } + + if (doc.type === "break-parent") { + return true; + } + } + + function willBreak(doc) { + return findInDoc(doc, willBreakFn, false); + } + + function breakParentGroup(groupStack) { + if (groupStack.length > 0) { + const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because + // the user is expected to manually handle what breaks. + + if (!parentGroup.expandedStates) { + parentGroup.break = true; + } + } + + return null; + } + + function propagateBreaks(doc) { + const alreadyVisitedSet = new Set(); + const groupStack = []; + + function propagateBreaksOnEnterFn(doc) { + if (doc.type === "break-parent") { + breakParentGroup(groupStack); + } + + if (doc.type === "group") { + groupStack.push(doc); + + if (alreadyVisitedSet.has(doc)) { + return false; + } + + alreadyVisitedSet.add(doc); + } + } + + function propagateBreaksOnExitFn(doc) { + if (doc.type === "group") { + const group = groupStack.pop(); + + if (group.break) { + breakParentGroup(groupStack); + } + } + } + + traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn, + /* shouldTraverseConditionalGroups */ + true); + } + + function removeLinesFn(doc) { + // Force this doc into flat mode by statically converting all + // lines into spaces (or soft lines into nothing). Hard lines + // should still output because there's too great of a chance + // of breaking existing assumptions otherwise. + if (doc.type === "line" && !doc.hard) { + return doc.soft ? "" : " "; + } else if (doc.type === "if-break") { + return doc.flatContents || ""; + } + + return doc; + } + + function removeLines(doc) { + return mapDoc(doc, removeLinesFn); + } + + function stripTrailingHardline(doc) { + // HACK remove ending hardline, original PR: #1984 + if (doc.type === "concat" && doc.parts.length !== 0) { + const lastPart = doc.parts[doc.parts.length - 1]; + + if (lastPart.type === "concat") { + if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") { + return { + type: "concat", + parts: doc.parts.slice(0, -1) + }; + } + + return { + type: "concat", + parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart)) + }; + } + } + + return doc; + } + + var docUtils = { + isEmpty, + willBreak, + isLineNext, + traverseDoc, + findInDoc, + mapDoc, + propagateBreaks, + removeLines, + stripTrailingHardline + }; + + function flattenDoc(doc) { + if (doc.type === "concat") { + const res = []; + + for (let i = 0; i < doc.parts.length; ++i) { + const doc2 = doc.parts[i]; + + if (typeof doc2 !== "string" && doc2.type === "concat") { + res.push(...flattenDoc(doc2).parts); + } else { + const flattened = flattenDoc(doc2); + + if (flattened !== "") { + res.push(flattened); + } + } + } + + return Object.assign({}, doc, { + parts: res + }); + } else if (doc.type === "if-break") { + return Object.assign({}, doc, { + breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null, + flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null + }); + } else if (doc.type === "group") { + return Object.assign({}, doc, { + contents: flattenDoc(doc.contents), + expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates + }); + } else if (doc.contents) { + return Object.assign({}, doc, { + contents: flattenDoc(doc.contents) + }); + } + + return doc; + } + + function printDoc(doc) { + if (typeof doc === "string") { + return JSON.stringify(doc); + } + + if (doc.type === "line") { + if (doc.literal) { + return "literalline"; + } + + if (doc.hard) { + return "hardline"; + } + + if (doc.soft) { + return "softline"; + } + + return "line"; + } + + if (doc.type === "break-parent") { + return "breakParent"; + } + + if (doc.type === "trim") { + return "trim"; + } + + if (doc.type === "concat") { + return "[" + doc.parts.map(printDoc).join(", ") + "]"; + } + + if (doc.type === "indent") { + return "indent(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "align") { + 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) + ")"; + } + + if (doc.type === "if-break") { + return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")"; + } + + if (doc.type === "group") { + if (doc.expandedStates) { + return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])"; + } + + return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "fill") { + return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")"; + } + + if (doc.type === "line-suffix") { + return "lineSuffix(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "line-suffix-boundary") { + return "lineSuffixBoundary"; + } + + throw new Error("Unknown doc type " + doc.type); + } + + var docDebug = { + printDocToDebug(doc) { + return printDoc(flattenDoc(doc)); + } + + }; + + var document = { + builders: docBuilders, + printer: docPrinter, + utils: docUtils, + debug: docDebug + }; + + const { + getMaxContinuousCount: getMaxContinuousCount$1, + getStringWidth: getStringWidth$2, + getAlignmentSize: getAlignmentSize$1, + getIndentSize: getIndentSize$1, + skip: skip$1, + skipWhitespace: skipWhitespace$1, + skipSpaces: skipSpaces$1, + skipNewline: skipNewline$1, + skipToLineEnd: skipToLineEnd$1, + skipEverythingButNewLine: skipEverythingButNewLine$1, + skipInlineComment: skipInlineComment$1, + skipTrailingComment: skipTrailingComment$1, + hasNewline: hasNewline$1, + hasNewlineInRange: hasNewlineInRange$1, + hasSpaces: hasSpaces$1, + isNextLineEmpty: isNextLineEmpty$1, + isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1, + isPreviousLineEmpty: isPreviousLineEmpty$1, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, + makeString: makeString$1, + addLeadingComment: addLeadingComment$1, + addDanglingComment: addDanglingComment$1, + addTrailingComment: addTrailingComment$1 + } = util$1; + var utilShared = { + getMaxContinuousCount: getMaxContinuousCount$1, + getStringWidth: getStringWidth$2, + getAlignmentSize: getAlignmentSize$1, + getIndentSize: getIndentSize$1, + skip: skip$1, + skipWhitespace: skipWhitespace$1, + skipSpaces: skipSpaces$1, + skipNewline: skipNewline$1, + skipToLineEnd: skipToLineEnd$1, + skipEverythingButNewLine: skipEverythingButNewLine$1, + skipInlineComment: skipInlineComment$1, + skipTrailingComment: skipTrailingComment$1, + hasNewline: hasNewline$1, + hasNewlineInRange: hasNewlineInRange$1, + hasSpaces: hasSpaces$1, + isNextLineEmpty: isNextLineEmpty$1, + isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1, + isPreviousLineEmpty: isPreviousLineEmpty$1, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, + makeString: makeString$1, + addLeadingComment: addLeadingComment$1, + addDanglingComment: addDanglingComment$1, + addTrailingComment: addTrailingComment$1 + }; + + const { + concat: concat$2, + line: line$1, + hardline: hardline$1, + breakParent: breakParent$1, + indent: indent$1, + lineSuffix: lineSuffix$1, + join: join$1, + cursor: cursor$2 + } = document.builders; + const { + hasNewline: hasNewline$2, + skipNewline: skipNewline$2, + isPreviousLineEmpty: isPreviousLineEmpty$2 + } = util$1; + const { + addLeadingComment: addLeadingComment$2, + addDanglingComment: addDanglingComment$2, + addTrailingComment: addTrailingComment$2 + } = utilShared; + const childNodesCacheKey = Symbol("child-nodes"); + + function getSortedChildNodes(node, options, resultArray) { + if (!node) { + return; + } + + const { + printer, + locStart, + locEnd + } = options; + + if (resultArray) { + if (printer.canAttachComment && printer.canAttachComment(node)) { + // This reverse insertion sort almost always takes constant + // time because we almost always (maybe always?) append the + // nodes in order anyway. + let i; + + for (i = resultArray.length - 1; i >= 0; --i) { + if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) { + break; + } + } + + resultArray.splice(i + 1, 0, node); + return; + } + } else if (node[childNodesCacheKey]) { + return node[childNodesCacheKey]; + } + + const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === "object" && Object.keys(node).filter(n => n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode").map(n => node[n]); + + if (!childNodes) { + return; + } + + if (!resultArray) { + Object.defineProperty(node, childNodesCacheKey, { + value: resultArray = [], + enumerable: false + }); + } + + childNodes.forEach(childNode => { + getSortedChildNodes(childNode, options, resultArray); + }); + return resultArray; + } // As efficiently as possible, decorate the comment object with + // .precedingNode, .enclosingNode, and/or .followingNode properties, at + // least one of which is guaranteed to be defined. + + + function decorateComment(node, comment, options) { + const { + locStart, + locEnd + } = options; + const childNodes = getSortedChildNodes(node, options); + let precedingNode; + let followingNode; // Time to dust off the old binary search robes and wizard hat. + + let left = 0; + let right = childNodes.length; + + while (left < right) { + const middle = left + right >> 1; + const child = childNodes[middle]; + + if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) { + // The comment is completely contained by this child node. + comment.enclosingNode = child; + decorateComment(child, comment, options); + return; // Abandon the binary search at this level. + } + + if (locEnd(child) - locStart(comment) <= 0) { + // This child node falls completely before the comment. + // Because we will never consider this node or any nodes + // before it again, this node must be the closest preceding + // node we have encountered so far. + precedingNode = child; + left = middle + 1; + continue; + } + + if (locEnd(comment) - locStart(child) <= 0) { + // This child node falls completely after the comment. + // Because we will never consider this node or any nodes after + // it again, this node must be the closest following node we + // have encountered so far. + followingNode = child; + right = middle; + continue; + } + /* istanbul ignore next */ + + + throw new Error("Comment location overlaps with node location"); + } // We don't want comments inside of different expressions inside of the same + // template literal to move to another expression. + + + if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") { + const { + quasis + } = comment.enclosingNode; + const commentIndex = findExpressionIndexForComment(quasis, comment, options); + + if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) { + precedingNode = null; + } + + if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) { + followingNode = null; + } + } + + if (precedingNode) { + comment.precedingNode = precedingNode; + } + + if (followingNode) { + comment.followingNode = followingNode; + } + } + + function attach(comments, ast, text, options) { + if (!Array.isArray(comments)) { + return; + } + + const tiesToBreak = []; + const { + locStart, + locEnd + } = options; + comments.forEach((comment, i) => { + if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") { + if (locStart(comment) - locStart(ast) <= 0) { + addLeadingComment$2(ast, comment); + return; + } + + if (locEnd(comment) - locEnd(ast) >= 0) { + addTrailingComment$2(ast, comment); + return; + } + } + + decorateComment(ast, comment, options); + const { + precedingNode, + enclosingNode, + followingNode + } = comment; + const pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : () => false; + const pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : () => false; + const pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : () => false; + const isLastComment = comments.length - 1 === i; + + if (hasNewline$2(text, locStart(comment), { + backwards: true + })) { + // If a comment exists on its own line, prefer a leading comment. + // We also need to check if it's the first line of the file. + if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) { + // Always a leading comment. + addLeadingComment$2(followingNode, comment); + } else if (precedingNode) { + addTrailingComment$2(precedingNode, comment); + } else if (enclosingNode) { + addDanglingComment$2(enclosingNode, comment); + } else { + // There are no nodes, let's attach it to the root of the ast + + /* istanbul ignore next */ + addDanglingComment$2(ast, comment); + } + } else if (hasNewline$2(text, locEnd(comment))) { + if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) { + // There is content before this comment on the same line, but + // none after it, so prefer a trailing comment of the previous node. + addTrailingComment$2(precedingNode, comment); + } else if (followingNode) { + addLeadingComment$2(followingNode, comment); + } else if (enclosingNode) { + addDanglingComment$2(enclosingNode, comment); + } else { + // There are no nodes, let's attach it to the root of the ast + + /* istanbul ignore next */ + addDanglingComment$2(ast, comment); + } + } else { + if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) { + // Otherwise, text exists both before and after the comment on + // the same line. If there is both a preceding and following + // node, use a tie-breaking algorithm to determine if it should + // be attached to the next or previous node. In the last case, + // simply attach the right node; + const tieCount = tiesToBreak.length; + + if (tieCount > 0) { + const lastTie = tiesToBreak[tieCount - 1]; + + if (lastTie.followingNode !== comment.followingNode) { + breakTies(tiesToBreak, text, options); + } + } + + tiesToBreak.push(comment); + } else if (precedingNode) { + addTrailingComment$2(precedingNode, comment); + } else if (followingNode) { + addLeadingComment$2(followingNode, comment); + } else if (enclosingNode) { + addDanglingComment$2(enclosingNode, comment); + } else { + // There are no nodes, let's attach it to the root of the ast + + /* istanbul ignore next */ + addDanglingComment$2(ast, comment); + } + } + }); + breakTies(tiesToBreak, text, options); + comments.forEach(comment => { + // These node references were useful for breaking ties, but we + // don't need them anymore, and they create cycles in the AST that + // may lead to infinite recursion if we don't delete them here. + delete comment.precedingNode; + delete comment.enclosingNode; + delete comment.followingNode; + }); + } + + function breakTies(tiesToBreak, text, options) { + const tieCount = tiesToBreak.length; + + if (tieCount === 0) { + return; + } + + const { + precedingNode, + followingNode, + enclosingNode + } = tiesToBreak[0]; + const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/; + let gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps + // between the tied comments. In order to qualify as leading, a + // comment must be separated from followingNode by an unbroken series of + // gaps (or other comments). Gaps should only contain whitespace or open + // parentheses. + + let indexOfFirstLeadingComment; + + for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) { + const comment = tiesToBreak[indexOfFirstLeadingComment - 1]; + assert.strictEqual(comment.precedingNode, precedingNode); + assert.strictEqual(comment.followingNode, followingNode); + const gap = text.slice(options.locEnd(comment), gapEndPos); + + if (gapRegExp.test(gap)) { + gapEndPos = options.locStart(comment); + } else { + // The gap string contained something other than whitespace or open + // parentheses. + break; + } + } + + tiesToBreak.forEach((comment, i) => { + if (i < indexOfFirstLeadingComment) { + addTrailingComment$2(precedingNode, comment); + } else { + addLeadingComment$2(followingNode, comment); + } + }); + tiesToBreak.length = 0; + } + + function printComment(commentPath, options) { + const comment = commentPath.getValue(); + comment.printed = true; + return options.printer.printComment(commentPath, options); + } + + function findExpressionIndexForComment(quasis, comment, options) { + const startPos = options.locStart(comment) - 1; + + for (let i = 1; i < quasis.length; ++i) { + if (startPos < getQuasiRange(quasis[i]).start) { + return i - 1; + } + } // We haven't found it, it probably means that some of the locations are off. + // Let's just return the first one. + + /* istanbul ignore next */ + + + return 0; + } + + function getQuasiRange(expr) { + if (expr.start !== undefined) { + // Babel + return { + start: expr.start, + end: expr.end + }; + } // Flow + + + return { + start: expr.range[0], + end: expr.range[1] + }; + } + + function printLeadingComment(commentPath, print, options) { + const comment = commentPath.getValue(); + const contents = printComment(commentPath, options); + + if (!contents) { + return ""; + } + + const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the + // same line or not. + + if (isBlock) { + const lineBreak = hasNewline$2(options.originalText, options.locEnd(comment)) ? hasNewline$2(options.originalText, options.locStart(comment), { + backwards: true + }) ? hardline$1 : line$1 : " "; + return concat$2([contents, lineBreak]); + } + + return concat$2([contents, hardline$1]); + } + + function printTrailingComment(commentPath, print, options) { + const comment = commentPath.getValue(); + const contents = printComment(commentPath, options); + + if (!contents) { + return ""; + } + + const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break + // when the parentParentNode is a ClassDeclaration/-Expression + // And the parentNode is in the superClass property + + const parentNode = commentPath.getNode(1); + const parentParentNode = commentPath.getNode(2); + const isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode; + + if (hasNewline$2(options.originalText, options.locStart(comment), { + backwards: true + })) { + // This allows comments at the end of nested structures: + // { + // x: 1, + // y: 2 + // // A comment + // } + // Those kinds of comments are almost always leading comments, but + // here it doesn't go "outside" the block and turns it into a + // trailing comment for `2`. We can simulate the above by checking + // if this a comment on its own line; normal trailing comments are + // always at the end of another expression. + const isLineBeforeEmpty = isPreviousLineEmpty$2(options.originalText, comment, options.locStart); + return lineSuffix$1(concat$2([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents])); + } else if (isBlock || isParentSuperClass) { + // Trailing block comments never need a newline + return concat$2([" ", contents]); + } + + return concat$2([lineSuffix$1(concat$2([" ", contents])), !isBlock ? breakParent$1 : ""]); + } + + function printDanglingComments(path, options, sameIndent, filter) { + const parts = []; + const node = path.getValue(); + + if (!node || !node.comments) { + return ""; + } + + path.each(commentPath => { + const comment = commentPath.getValue(); + + if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) { + parts.push(printComment(commentPath, options)); + } + }, "comments"); + + if (parts.length === 0) { + return ""; + } + + if (sameIndent) { + return join$1(hardline$1, parts); + } + + return indent$1(concat$2([hardline$1, join$1(hardline$1, parts)])); + } + + function prependCursorPlaceholder(path, options, printed) { + if (path.getNode() === options.cursorNode && path.getValue()) { + return concat$2([cursor$2, printed, cursor$2]); + } + + return printed; + } + + function printComments(path, print, options, needsSemi) { + const value = path.getValue(); + const printed = print(path); + const comments = value && value.comments; + + if (!comments || comments.length === 0) { + return prependCursorPlaceholder(path, options, printed); + } + + const leadingParts = []; + const trailingParts = [needsSemi ? ";" : "", printed]; + path.each(commentPath => { + const comment = commentPath.getValue(); + const { + leading, + trailing + } = comment; + + if (leading) { + const contents = printLeadingComment(commentPath, print, options); + + if (!contents) { + return; + } + + leadingParts.push(contents); + const text = options.originalText; + const index = skipNewline$2(text, options.locEnd(comment)); + + if (index !== false && hasNewline$2(text, index)) { + leadingParts.push(hardline$1); + } + } else if (trailing) { + trailingParts.push(printTrailingComment(commentPath, print, options)); + } + }, "comments"); + return prependCursorPlaceholder(path, options, concat$2(leadingParts.concat(trailingParts))); + } + + var comments = { + attach, + printComments, + printDanglingComments, + getSortedChildNodes + }; + + function getNodeHelper(path, count) { + const stackIndex = getNodeStackIndexHelper(path.stack, count); + return stackIndex === -1 ? null : path.stack[stackIndex]; + } + + function getNodeStackIndexHelper(stack, count) { + for (let i = stack.length - 1; i >= 0; i -= 2) { + const value = stack[i]; + + if (value && !Array.isArray(value) && --count < 0) { + return i; + } + } + + return -1; + } + + class FastPath { + constructor(value) { + this.stack = [value]; + } // The name of the current property is always the penultimate element of + // this.stack, and always a String. + + + getName() { + const { + stack + } = this; + const { + length + } = stack; + + if (length > 1) { + return stack[length - 2]; + } // Since the name is always a string, null is a safe sentinel value to + // return if we do not know the name of the (root) value. + + /* istanbul ignore next */ + + + return null; + } // The value of the current property is always the final element of + // this.stack. + + + getValue() { + return getLast(this.stack); + } + + getNode(count = 0) { + return getNodeHelper(this, count); + } + + getParentNode(count = 0) { + return getNodeHelper(this, count + 1); + } // Temporarily push properties named by string arguments given after the + // callback function onto this.stack, then call the callback with a + // reference to this (modified) FastPath object. Note that the stack will + // be restored to its original state after the callback is finished, so it + // is probably a mistake to retain a reference to the path. + + + call(callback, ...names) { + const { + stack + } = this; + const { + length + } = stack; + let value = getLast(stack); + + for (const name of names) { + value = value[name]; + stack.push(name, value); + } + + const result = callback(this); + stack.length = length; + return result; + } + + callParent(callback, count = 0) { + const stackIndex = getNodeStackIndexHelper(this.stack, count + 1); + const parentValues = this.stack.splice(stackIndex + 1); + const result = callback(this); + this.stack.push(...parentValues); + return result; + } // Similar to FastPath.prototype.call, except that the value obtained by + // accessing this.getValue()[name1][name2]... should be array-like. The + // callback will be called with a reference to this path object for each + // element of the array. + + + each(callback, ...names) { + const { + stack + } = this; + const { + length + } = stack; + let value = getLast(stack); + + for (const name of names) { + value = value[name]; + stack.push(name, value); + } + + for (let i = 0; i < value.length; ++i) { + if (i in value) { + stack.push(i, value[i]); // If the callback needs to know the value of i, call + // path.getName(), assuming path is the parameter name. + + callback(this); + stack.length -= 2; + } + } + + stack.length = length; + } // Similar to FastPath.prototype.each, except that the results of the + // callback function invocations are stored in an array and returned at + // the end of the iteration. + + + map(callback, ...names) { + const { + stack + } = this; + const { + length + } = stack; + let value = getLast(stack); + + for (const name of names) { + value = value[name]; + stack.push(name, value); + } + + const result = new Array(value.length); + + for (let i = 0; i < value.length; ++i) { + if (i in value) { + stack.push(i, value[i]); + result[i] = callback(this, i); + stack.length -= 2; + } + } + + stack.length = length; + return result; + } + /** + * @param {...( + * | ((node: any, name: string | null, number: number | null) => boolean) + * | undefined + * )} predicates + */ + + + match(...predicates) { + let stackPointer = this.stack.length - 1; + let name = null; + let node = this.stack[stackPointer--]; + + for (const predicate of predicates) { + if (node === undefined) { + return false; + } // skip index/array + + + let number = null; + + if (typeof name === "number") { + number = name; + name = this.stack[stackPointer--]; + node = this.stack[stackPointer--]; + } + + if (predicate && !predicate(node, name, number)) { + return false; + } + + name = this.stack[stackPointer--]; + node = this.stack[stackPointer--]; + } + + return true; + } + + } + + var fastPath = FastPath; + + const { + normalize: normalize$2 + } = options$1; + + function printSubtree(path, print, options, printAstToDoc) { + if (options.printer.embed) { + return options.printer.embed(path, print, (text, partialNextOptions) => textToDoc(text, partialNextOptions, options, printAstToDoc), options); + } + } + + function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) { + const nextOptions = normalize$2(Object.assign({}, parentOptions, {}, partialNextOptions, { + parentParser: parentOptions.parser, + embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"), + originalText: text + }), { + passThrough: true + }); + const result = parser.parse(text, nextOptions); + const { + ast + } = result; + text = result.text; + const astComments = ast.comments; + delete ast.comments; + comments.attach(astComments, ast, text, nextOptions); + return printAstToDoc(ast, nextOptions); + } + + var multiparser = { + printSubtree + }; + + const doc = document; + const docBuilders$1 = doc.builders; + const { + concat: concat$3, + hardline: hardline$2, + addAlignmentToDoc: addAlignmentToDoc$1 + } = docBuilders$1; + const docUtils$1 = doc.utils; + /** + * Takes an abstract syntax tree (AST) and recursively converts it to a + * document (series of printing primitives). + * + * This is done by descending down the AST recursively. The recursion + * involves two functions that call each other: + * + * 1. printGenerically(), which is defined as an inner function here. + * It basically takes care of node caching. + * 2. callPluginPrintFunction(), which checks for some options, and + * ultimately calls the print() function provided by the plugin. + * + * The plugin function will call printGenerically() again for child nodes + * of the current node, which will do its housekeeping, then call the + * plugin function again, and so on. + * + * All the while, these functions pass a "path" variable around, which + * is a stack-like data structure (FastPath) that maintains the current + * state of the recursion. It is called "path", because it represents + * the path to the current node through the Abstract Syntax Tree. + */ + + function printAstToDoc(ast, options, alignmentSize = 0) { + const { + printer + } = options; + + if (printer.preprocess) { + ast = printer.preprocess(ast, options); + } + + const cache = new Map(); + + function printGenerically(path, args) { + const node = path.getValue(); + const shouldCache = node && typeof node === "object" && args === undefined; + + if (shouldCache && cache.has(node)) { + return cache.get(node); + } // We let JSXElement print its comments itself because it adds () around + // UnionTypeAnnotation has to align the child without the comments + + + let res; + + if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) { + res = callPluginPrintFunction(path, options, printGenerically, args); + } else { + // printComments will call the plugin print function and check for + // comments to print + res = comments.printComments(path, p => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi); + } + + if (shouldCache) { + cache.set(node, res); + } + + return res; + } + + let doc = printGenerically(new fastPath(ast)); + + if (alignmentSize > 0) { + // Add a hardline to make the indents take effect + // It should be removed in index.js format() + doc = addAlignmentToDoc$1(concat$3([hardline$2, doc]), alignmentSize, options.tabWidth); + } + + docUtils$1.propagateBreaks(doc); + return doc; + } + + function callPluginPrintFunction(path, options, printPath, args) { + assert.ok(path instanceof fastPath); + const node = path.getValue(); + const { + printer + } = options; // Escape hatch + + if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) { + return options.originalText.slice(options.locStart(node), options.locEnd(node)); + } + + if (node) { + try { + // Potentially switch to a different parser + const sub = multiparser.printSubtree(path, printPath, options, printAstToDoc); + + if (sub) { + return sub; + } + } catch (error) { + /* istanbul ignore if */ + if (commonjsGlobal.PRETTIER_DEBUG) { + throw error; + } // Continue with current parser + + } + } + + return printer.print(path, options, printPath, args); + } + + var astToDoc = printAstToDoc; + + function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { + let resultStartNode = startNodeAndParents.node; + let resultEndNode = endNodeAndParents.node; + + if (resultStartNode === resultEndNode) { + return { + startNode: resultStartNode, + endNode: resultEndNode + }; + } + + for (const endParent of endNodeAndParents.parentNodes) { + if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) { + resultEndNode = endParent; + } else { + break; + } + } + + for (const startParent of startNodeAndParents.parentNodes) { + if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) { + resultStartNode = startParent; + } else { + break; + } + } + + return { + startNode: resultStartNode, + endNode: resultEndNode + }; + } + + function findNodeAtOffset(node, offset, options, predicate, parentNodes) { + predicate = predicate || (() => true); + + parentNodes = parentNodes || []; + const start = options.locStart(node, options.locStart); + const end = options.locEnd(node, options.locEnd); + + if (start <= offset && offset <= end) { + for (const childNode of comments.getSortedChildNodes(node, options)) { + const childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes)); + + if (childResult) { + return childResult; + } + } + + if (predicate(node)) { + return { + node, + parentNodes + }; + } + } + } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 + + + function isSourceElement(opts, node) { + if (node == null) { + return false; + } // JS and JS like to avoid repetitions + + + const jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015 + "ImportDeclaration", // Module + "ExportDefaultDeclaration", // Module + "ExportNamedDeclaration", // Module + "ExportAllDeclaration", // Module + "TypeAlias", // Flow + "InterfaceDeclaration", // Flow, TypeScript + "TypeAliasDeclaration", // TypeScript + "ExportAssignment", // TypeScript + "ExportDeclaration" // TypeScript + ]; + const jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"]; + const graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"]; + + switch (opts.parser) { + case "flow": + case "babel": + case "babel-flow": + case "babel-ts": + case "typescript": + return jsSourceElements.includes(node.type); + + case "json": + return jsonSourceElements.includes(node.type); + + case "graphql": + return graphqlSourceElements.includes(node.kind); + + case "vue": + return node.tag !== "root"; + } + + return false; + } + + function calculateRange(text, opts, ast) { + // Contract the range so that it has non-whitespace characters at its endpoints. + // This ensures we can format a range that doesn't end on a node. + const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); + const startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart); + let endNonWhitespace; + + for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) { + if (text[endNonWhitespace - 1].match(/\S/)) { + break; + } + } + + const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, node => isSourceElement(opts, node)); + const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, node => isSourceElement(opts, node)); + + if (!startNodeAndParents || !endNodeAndParents) { + return { + rangeStart: 0, + rangeEnd: 0 + }; + } + + const siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts); + const { + startNode, + endNode + } = siblingAncestors; + const rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart)); + const rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd)); + return { + rangeStart, + rangeEnd + }; + } + + var rangeUtil = { + calculateRange, + findNodeAtOffset + }; + + var diff = getCjsExportFromNamespace(index_es6); + + const normalizeOptions$1 = options$1.normalize; + const { + guessEndOfLine: guessEndOfLine$1, + convertEndOfLineToChars: convertEndOfLineToChars$2 + } = endOfLine; + const { + printer: { + printDocToString: printDocToString$1 + }, + debug: { + printDocToDebug + } + } = document; + const BOM = "\uFEFF"; + const CURSOR = Symbol("cursor"); + const PLACEHOLDERS = { + cursorOffset: "<<<PRETTIER_CURSOR>>>", + rangeStart: "<<<PRETTIER_RANGE_START>>>", + rangeEnd: "<<<PRETTIER_RANGE_END>>>" + }; + + function ensureAllCommentsPrinted(astComments) { + if (!astComments) { + return; + } + + for (let i = 0; i < astComments.length; ++i) { + if (util$1.isNodeIgnoreComment(astComments[i])) { + // If there's a prettier-ignore, we're not printing that sub-tree so we + // don't know if the comments was printed or not. + return; + } + } + + astComments.forEach(comment => { + if (!comment.printed) { + throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!'); + } + + delete comment.printed; + }); + } + + function attachComments(text, ast, opts) { + const astComments = ast.comments; + + if (astComments) { + delete ast.comments; + comments.attach(astComments, ast, text, opts); + } + + ast.tokens = []; + opts.originalText = opts.parser === "yaml" ? text : text.trimEnd(); + return astComments; + } + + function coreFormat(text, opts, addAlignmentSize) { + if (!text || !text.trim().length) { + return { + formatted: "", + cursorOffset: 0 + }; + } + + addAlignmentSize = addAlignmentSize || 0; + const parsed = parser.parse(text, opts); + const { + ast + } = parsed; + text = parsed.text; + + if (opts.cursorOffset >= 0) { + const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts); + + if (nodeResult && nodeResult.node) { + opts.cursorNode = nodeResult.node; + } + } + + const astComments = attachComments(text, ast, opts); + const doc = astToDoc(ast, opts, addAlignmentSize); + const result = printDocToString$1(doc, opts); + ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline + + if (addAlignmentSize > 0) { + const trimmed = result.formatted.trim(); + + if (result.cursorNodeStart !== undefined) { + result.cursorNodeStart -= result.formatted.indexOf(trimmed); + } + + result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine); + } + + if (opts.cursorOffset >= 0) { + let oldCursorNodeStart; + let oldCursorNodeText; + let cursorOffsetRelativeToOldCursorNode; + let newCursorNodeStart; + let newCursorNodeText; + + if (opts.cursorNode && result.cursorNodeText) { + oldCursorNodeStart = opts.locStart(opts.cursorNode); + oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode)); + cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart; + newCursorNodeStart = result.cursorNodeStart; + newCursorNodeText = result.cursorNodeText; + } else { + oldCursorNodeStart = 0; + oldCursorNodeText = text; + cursorOffsetRelativeToOldCursorNode = opts.cursorOffset; + newCursorNodeStart = 0; + newCursorNodeText = result.formatted; + } + + if (oldCursorNodeText === newCursorNodeText) { + return { + formatted: result.formatted, + cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode + }; + } // diff old and new cursor node texts, with a special cursor + // symbol inserted to find out where it moves to + + + const oldCursorNodeCharArray = oldCursorNodeText.split(""); + oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR); + const newCursorNodeCharArray = newCursorNodeText.split(""); + const cursorNodeDiff = diff.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray); + let cursorOffset = newCursorNodeStart; + + for (const entry of cursorNodeDiff) { + if (entry.removed) { + if (entry.value.includes(CURSOR)) { + break; + } + } else { + cursorOffset += entry.count; + } + } + + return { + formatted: result.formatted, + cursorOffset + }; + } + + return { + formatted: result.formatted + }; + } + + function formatRange(text, opts) { + const parsed = parser.parse(text, opts); + const { + ast + } = parsed; + text = parsed.text; + const range = rangeUtil.calculateRange(text, opts, ast); + const { + rangeStart, + rangeEnd + } = range; + const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. + // This is so we can detect indentation correctly and restore it. + // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 + + const rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1); + const indentString = text.slice(rangeStart2, rangeStart); + const alignmentSize = util$1.getAlignmentSize(indentString, opts.tabWidth); + const rangeResult = coreFormat(rangeString, Object.assign({}, opts, { + rangeStart: 0, + rangeEnd: Infinity, + // track the cursor offset only if it's within our range + cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1 + }), alignmentSize); // Since the range contracts to avoid trailing whitespace, + // we need to remove the newline that was inserted by the `format` call. + + const rangeTrimmed = rangeResult.formatted.trimEnd(); + const rangeLeft = text.slice(0, rangeStart); + const rangeRight = text.slice(rangeEnd); + let { + cursorOffset + } = opts; + + if (opts.cursorOffset >= rangeEnd) { + // handle the case where the cursor was past the end of the range + cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length); + } else if (rangeResult.cursorOffset !== undefined) { + // handle the case where the cursor was in the range + cursorOffset = rangeResult.cursorOffset + rangeStart; + } // keep the cursor as it was if it was before the start of the range + + + let formatted; + + if (opts.endOfLine === "lf") { + formatted = rangeLeft + rangeTrimmed + rangeRight; + } else { + const eol = convertEndOfLineToChars$2(opts.endOfLine); + + if (cursorOffset >= 0) { + const parts = [rangeLeft, rangeTrimmed, rangeRight]; + let partIndex = 0; + let partOffset = cursorOffset; + + while (partIndex < parts.length) { + const part = parts[partIndex]; + + if (partOffset < part.length) { + parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset); + break; + } + + partIndex++; + partOffset -= part.length; + } + + const [newRangeLeft, newRangeTrimmed, newRangeRight] = parts; + formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, (_, index) => { + cursorOffset = index; + return ""; + }); + } else { + formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol); + } + } + + return { + formatted, + cursorOffset + }; + } + + function format(text, opts) { + const selectedParser = parser.resolveParser(opts); + const hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text); + + if (opts.requirePragma && !hasPragma) { + return { + formatted: text + }; + } + + if (opts.endOfLine === "auto") { + opts.endOfLine = guessEndOfLine$1(text); + } + + const hasCursor = opts.cursorOffset >= 0; + const hasRangeStart = opts.rangeStart > 0; + const hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing + + if (text.includes("\r")) { + const offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort((aKey, bKey) => opts[aKey] - opts[bKey]); + + for (let i = offsetKeys.length - 1; i >= 0; i--) { + const key = offsetKeys[i]; + text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]); + } + + text = text.replace(/\r\n?/g, "\n"); + + for (let i = 0; i < offsetKeys.length; i++) { + const key = offsetKeys[i]; + text = text.replace(PLACEHOLDERS[key], (_, index) => { + opts[key] = index; + return ""; + }); + } + } + + const hasUnicodeBOM = text.charAt(0) === BOM; + + if (hasUnicodeBOM) { + text = text.slice(1); + + if (hasCursor) { + opts.cursorOffset++; + } + + if (hasRangeStart) { + opts.rangeStart++; + } + + if (hasRangeEnd) { + opts.rangeEnd++; + } + } + + if (!hasCursor) { + opts.cursorOffset = -1; + } + + if (opts.rangeStart < 0) { + opts.rangeStart = 0; + } + + if (opts.rangeEnd > text.length) { + opts.rangeEnd = text.length; + } + + const result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts); + + if (hasUnicodeBOM) { + result.formatted = BOM + result.formatted; + + if (hasCursor) { + result.cursorOffset++; + } + } + + return result; + } + + var core = { + formatWithCursor(text, opts) { + opts = normalizeOptions$1(opts); + return format(text, opts); + }, + + parse(text, opts, massage) { + opts = normalizeOptions$1(opts); + + if (text.includes("\r")) { + text = text.replace(/\r\n?/g, "\n"); + } + + const parsed = parser.parse(text, opts); + + if (massage) { + parsed.ast = massageAst(parsed.ast, opts); + } + + return parsed; + }, + + formatAST(ast, opts) { + opts = normalizeOptions$1(opts); + const doc = astToDoc(ast, opts); + return printDocToString$1(doc, opts); + }, + + // Doesn't handle shebang for now + formatDoc(doc, opts) { + const debug = printDocToDebug(doc); + opts = normalizeOptions$1(Object.assign({}, opts, { + parser: "babel" + })); + return format(debug, opts).formatted; + }, + + printToDoc(text, opts) { + opts = normalizeOptions$1(opts); + const parsed = parser.parse(text, opts); + const { + ast + } = parsed; + text = parsed.text; + attachComments(text, ast, opts); + return astToDoc(ast, opts); + }, + + printDocToString(doc, opts) { + return printDocToString$1(doc, normalizeOptions$1(opts)); + } + + }; + + function clean(ast, newObj, parent) { + ["raw", // front-matter + "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(name => { + delete newObj[name]; + }); + + if (ast.type === "yaml") { + delete newObj.value; + } // --insert-pragma + + + if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment + parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) { + /** + * something + * + * @format + */ + delete newObj.text; // standalone pragma + + if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) { + return null; + } + } + + if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") { + delete newObj.value; + } + + if (ast.type === "css-rule") { + delete newObj.params; + } + + if (ast.type === "selector-combinator") { + newObj.value = newObj.value.replace(/\s+/g, " "); + } + + if (ast.type === "media-feature") { + newObj.value = newObj.value.replace(/ /g, ""); + } + + if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].includes(newObj.value.replace().toLowerCase())) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") { + newObj.value = newObj.value.toLowerCase(); + } + + if (ast.type === "css-decl") { + newObj.prop = newObj.prop.toLowerCase(); + } + + if (ast.type === "css-atrule" || ast.type === "css-import") { + newObj.name = newObj.name.toLowerCase(); + } + + if (ast.type === "value-number") { + newObj.unit = newObj.unit.toLowerCase(); + } + + if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) { + newObj.value = cleanCSSStrings(newObj.value); + } + + if (ast.type === "selector-attribute") { + newObj.attribute = newObj.attribute.trim(); + + if (newObj.namespace) { + if (typeof newObj.namespace === "string") { + newObj.namespace = newObj.namespace.trim(); + + if (newObj.namespace.length === 0) { + newObj.namespace = true; + } + } + } + + if (newObj.value) { + newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, ""); + delete newObj.quoted; + } + } + + if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) { + newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, (match, numStr, unit) => { + const num = Number(numStr); + return isNaN(num) ? match : num + unit.toLowerCase(); + }); + } + + if (ast.type === "selector-tag") { + const lowercasedValue = ast.value.toLowerCase(); + + if (["from", "to"].includes(lowercasedValue)) { + newObj.value = lowercasedValue; + } + } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func` + + + if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") { + delete newObj.value; + } // Workaround for SCSS nested properties + + + if (ast.type === "selector-unknown") { + delete newObj.value; + } + } + + function cleanCSSStrings(value) { + return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1"); + } + + var clean_1 = clean; + + const { + builders: { + hardline: hardline$3, + literalline: literalline$1, + concat: concat$4, + markAsRoot: markAsRoot$1 + }, + utils: { + mapDoc: mapDoc$1 + } + } = document; + + function embed(path, print, textToDoc + /*, options */ + ) { + const node = path.getValue(); + + if (node.type === "yaml") { + return markAsRoot$1(concat$4(["---", hardline$3, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, { + parser: "yaml" + })) : "", "---", hardline$3])); + } + + return null; + + function replaceNewlinesWithLiterallines(doc) { + return mapDoc$1(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$4(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$1)) : currentDoc); + } + } + + var embed_1 = embed; + + const detectNewline = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + + const newlines = string.match(/(?:\r?\n)/g) || []; + + if (newlines.length === 0) { + return; + } + + const crlf = newlines.filter(newline => newline === '\r\n').length; + const lf = newlines.length - crlf; + return crlf > lf ? '\r\n' : '\n'; + }; + + var detectNewline_1 = detectNewline; + + var graceful = string => typeof string === 'string' && detectNewline(string) || '\n'; + detectNewline_1.graceful = graceful; + + var build = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.extract = extract; + exports.strip = strip; + exports.parse = parse; + exports.parseWithComments = parseWithComments; + exports.print = print; + + function _os() { + const data = require$$0$1; + + _os = function _os() { + return data; + }; + + return data; + } + + function _detectNewline() { + const data = _interopRequireDefault(detectNewline_1); + + _detectNewline = function _detectNewline() { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + const commentEndRe = /\*\/$/; + const commentStartRe = /^\/\*\*/; + const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; + const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g; + const ltrimNewlineRe = /^(\r?\n)+/; + const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g; + const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; + const stringStartRe = /(\r?\n|^) *\* ?/g; + + function extract(contents) { + const match = contents.match(docblockRe); + return match ? match[0].trimLeft() : ''; + } + + function strip(contents) { + const match = contents.match(docblockRe); + return match && match[0] ? contents.substring(match[0].length) : contents; + } + + function parse(docblock) { + return parseWithComments(docblock).pragmas; + } + + function parseWithComments(docblock) { + const line = (0, _detectNewline().default)(docblock) || _os().EOL; + + docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives + + let prev = ''; + + while (prev !== docblock) { + prev = docblock; + docblock = docblock.replace(multilineRe, "".concat(line, "$1 $2").concat(line)); + } + + docblock = docblock.replace(ltrimNewlineRe, '').trimRight(); + const result = Object.create(null); + const comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight(); + let match; + + while (match = propertyRe.exec(docblock)) { + // strip linecomments from pragmas + const nextPragma = match[2].replace(lineCommentRe, ''); + + if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) { + result[match[1]] = [].concat(result[match[1]], nextPragma); + } else { + result[match[1]] = nextPragma; + } + } + + return { + comments, + pragmas: result + }; + } + + function print({ + comments = '', + pragmas = {} + }) { + const line = (0, _detectNewline().default)(comments) || _os().EOL; + + const head = '/**'; + const start = ' *'; + const tail = ' */'; + const keys = Object.keys(pragmas); + const printedObject = keys.map(key => printKeyValues(key, pragmas[key])).reduce((arr, next) => arr.concat(next), []).map(keyValue => start + ' ' + keyValue + line).join(''); + + if (!comments) { + if (keys.length === 0) { + return ''; + } + + if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) { + const value = pragmas[keys[0]]; + return "".concat(head, " ").concat(printKeyValues(keys[0], value)[0]).concat(tail); + } + } + + const printedComments = comments.split(line).map(textLine => "".concat(start, " ").concat(textLine)).join(line) + line; + return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail; + } + + function printKeyValues(key, valueOrArray) { + return [].concat(valueOrArray).map(value => "@".concat(key, " ").concat(value).trim()); + } + }); + unwrapExports(build); + var build_1 = build.extract; + var build_2 = build.strip; + var build_3 = build.parse; + var build_4 = build.parseWithComments; + var build_5 = build.print; + + function hasPragma(text) { + const pragmas = Object.keys(build.parse(build.extract(text))); + return pragmas.includes("prettier") || pragmas.includes("format"); + } + + function insertPragma(text) { + const parsedDocblock = build.parseWithComments(build.extract(text)); + const pragmas = Object.assign({ + format: "" + }, parsedDocblock.pragmas); + const newDocblock = build.print({ + pragmas, + comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines + + }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock) + + const strippedText = build.strip(text); + const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n"; + return newDocblock + separatingNewlines + strippedText; + } + + var pragma = { + hasPragma, + insertPragma + }; + + const DELIMITER_MAP = { + "---": "yaml", + "+++": "toml" + }; + + function parse$1(text) { + const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp$2).join("|"); + const match = text.match( // trailing spaces after delimiters are allowed + new RegExp("^(".concat(delimiterRegex, ")[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)"))); + + if (match === null) { + return { + frontMatter: null, + content: text + }; + } + + const [raw, delimiter, value] = match; + return { + frontMatter: { + type: DELIMITER_MAP[delimiter], + value, + raw: raw.replace(/\n$/, "") + }, + content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length) + }; + } + + var frontMatter = parse$1; + + function hasPragma$1(text) { + return pragma.hasPragma(frontMatter(text).content); + } + + function insertPragma$1(text) { + const { + frontMatter: frontMatter$1, + content + } = frontMatter(text); + return (frontMatter$1 ? frontMatter$1.raw + "\n\n" : "") + pragma.insertPragma(content); + } + + var pragma$1 = { + hasPragma: hasPragma$1, + insertPragma: insertPragma$1 + }; + + var lineColumnToIndex = function lineColumnToIndex(lineColumn, text) { + let index = 0; + + for (let i = 0; i < lineColumn.line - 1; ++i) { + index = text.indexOf("\n", index) + 1; + + if (index === -1) { + return -1; + } + } + + return index + lineColumn.column; + }; + + const { + getLast: getLast$1, + skipEverythingButNewLine: skipEverythingButNewLine$2 + } = util$1; + + function calculateLocStart(node, text) { + if (node.source) { + return lineColumnToIndex(node.source.start, text) - 1; + } + + return null; + } + + function calculateLocEnd(node, text) { + if (node.type === "css-comment" && node.inline) { + return skipEverythingButNewLine$2(text, node.source.startOffset); + } + + const endNode = node.nodes && getLast$1(node.nodes); + + if (endNode && node.source && !node.source.end) { + node = endNode; + } + + if (node.source && node.source.end) { + return lineColumnToIndex(node.source.end, text); + } + + return null; + } + + function calculateLoc(node, text) { + if (node && typeof node === "object") { + if (node.source) { + node.source.startOffset = calculateLocStart(node, text); + node.source.endOffset = calculateLocEnd(node, text); + } + + for (const key in node) { + calculateLoc(node[key], text); + } + } + } + /** + * Workaround for a bug: quotes in inline comments corrupt loc data of subsequent nodes. + * This function replaces the quotes with U+FFFE and U+FFFF. Later, when the comments are printed, + * their content is extracted from the original text or restored by replacing the placeholder + * characters back with quotes. + * - https://github.com/prettier/prettier/issues/7780 + * - https://github.com/shellscape/postcss-less/issues/145 + * - About noncharacters (U+FFFE and U+FFFF): http://www.unicode.org/faq/private_use.html#nonchar1 + * @param text {string} + */ + + + function replaceQuotesInInlineComments(text) { + /** @typedef { 'initial' | 'single-quotes' | 'double-quotes' | 'url' | 'comment-block' | 'comment-inline' } State */ + + /** @type {State} */ + let state = "initial"; + /** @type {State} */ + + let stateToReturnFromQuotes = "initial"; + let inlineCommentStartIndex; + let inlineCommentContainsQuotes = false; + const inlineCommentsToReplace = []; + + for (let i = 0; i < text.length; i++) { + const c = text[i]; + + switch (state) { + case "initial": + if (c === "'") { + state = "single-quotes"; + continue; + } + + if (c === '"') { + state = "double-quotes"; + continue; + } + + if ((c === "u" || c === "U") && text.slice(i, i + 4).toLowerCase() === "url(") { + state = "url"; + i += 3; + continue; + } + + if (c === "*" && text[i - 1] === "/") { + state = "comment-block"; + continue; + } + + if (c === "/" && text[i - 1] === "/") { + state = "comment-inline"; + inlineCommentStartIndex = i - 1; + continue; + } + + continue; + + case "single-quotes": + if (c === "'" && text[i - 1] !== "\\") { + state = stateToReturnFromQuotes; + stateToReturnFromQuotes = "initial"; + } + + if (c === "\n" || c === "\r") { + return text; // invalid input + } + + continue; + + case "double-quotes": + if (c === '"' && text[i - 1] !== "\\") { + state = stateToReturnFromQuotes; + stateToReturnFromQuotes = "initial"; + } + + if (c === "\n" || c === "\r") { + return text; // invalid input + } + + continue; + + case "url": + if (c === ")") { + state = "initial"; + } + + if (c === "\n" || c === "\r") { + return text; // invalid input + } + + if (c === "'") { + state = "single-quotes"; + stateToReturnFromQuotes = "url"; + continue; + } + + if (c === '"') { + state = "double-quotes"; + stateToReturnFromQuotes = "url"; + continue; + } + + continue; + + case "comment-block": + if (c === "/" && text[i - 1] === "*") { + state = "initial"; + } + + continue; + + case "comment-inline": + if (c === '"' || c === "'") { + inlineCommentContainsQuotes = true; + } + + if (c === "\n" || c === "\r") { + if (inlineCommentContainsQuotes) { + inlineCommentsToReplace.push([inlineCommentStartIndex, i]); + } + + state = "initial"; + inlineCommentContainsQuotes = false; + } + + continue; + } + } + + for (const [start, end] of inlineCommentsToReplace) { + text = text.slice(0, start) + text.slice(start, end).replace(/'/g, "\ufffe").replace(/"/g, "\uffff") + text.slice(end); + } + + return text; + } + + function restoreQuotesInInlineComments(text) { + return text.replace(/\ufffe/g, "'").replace(/\uffff/g, '"'); + } + + var loc$1 = { + calculateLoc, + replaceQuotesInInlineComments, + restoreQuotesInInlineComments + }; + + const colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"]; + + function getAncestorCounter(path, typeOrTypes) { + const types = [].concat(typeOrTypes); + let counter = -1; + let ancestorNode; + + while (ancestorNode = path.getParentNode(++counter)) { + if (types.includes(ancestorNode.type)) { + return counter; + } + } + + return -1; + } + + function getAncestorNode(path, typeOrTypes) { + const counter = getAncestorCounter(path, typeOrTypes); + return counter === -1 ? null : path.getParentNode(counter); + } + + function getPropOfDeclNode(path) { + const declAncestorNode = getAncestorNode(path, "css-decl"); + return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase(); + } + + function isSCSS(parser, text) { + const hasExplicitParserChoice = parser === "less" || parser === "scss"; + const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^}:]+|#){|@import[^\n]+(?:url|,)/; + return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text); + } + + function isWideKeywords(value) { + return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase()); + } + + function isKeyframeAtRuleKeywords(path, value) { + const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); + return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase()); + } + + function maybeToLowerCase(value) { + return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase(); + } + + function insideValueFunctionNode(path, functionName) { + const funcAncestorNode = getAncestorNode(path, "value-func"); + return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName; + } + + function insideICSSRuleNode(path) { + const ruleAncestorNode = getAncestorNode(path, "css-rule"); + return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export")); + } + + function insideAtRuleNode(path, atRuleNameOrAtRuleNames) { + const atRuleNames = [].concat(atRuleNameOrAtRuleNames); + const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); + return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase()); + } + + function insideURLFunctionInImportAtRuleNode(path) { + const node = path.getValue(); + const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); + return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2; + } + + function isURLFunctionNode(node) { + return node.type === "value-func" && node.value.toLowerCase() === "url"; + } + + function isLastNode(path, node) { + const parentNode = path.getParentNode(); + + if (!parentNode) { + return false; + } + + const { + nodes + } = parentNode; + return nodes && nodes.indexOf(node) === nodes.length - 1; + } + + function isDetachedRulesetDeclarationNode(node) { + // If a Less file ends up being parsed with the SCSS parser, Less + // variable declarations will be parsed as atrules with names ending + // with a colon, so keep the original case then. + if (!node.selector) { + return false; + } + + return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value); + } + + function isForKeywordNode(node) { + return node.type === "value-word" && ["from", "through", "end"].includes(node.value); + } + + function isIfElseKeywordNode(node) { + return node.type === "value-word" && ["and", "or", "not"].includes(node.value); + } + + function isEachKeywordNode(node) { + return node.type === "value-word" && node.value === "in"; + } + + function isMultiplicationNode(node) { + return node.type === "value-operator" && node.value === "*"; + } + + function isDivisionNode(node) { + return node.type === "value-operator" && node.value === "/"; + } + + function isAdditionNode(node) { + return node.type === "value-operator" && node.value === "+"; + } + + function isSubtractionNode(node) { + return node.type === "value-operator" && node.value === "-"; + } + + function isModuloNode(node) { + return node.type === "value-operator" && node.value === "%"; + } + + function isMathOperatorNode(node) { + return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node); + } + + function isEqualityOperatorNode(node) { + return node.type === "value-word" && ["==", "!="].includes(node.value); + } + + function isRelationalOperatorNode(node) { + return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value); + } + + function isSCSSControlDirectiveNode(node) { + return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name); + } + + function isSCSSNestedPropertyNode(node) { + if (!node.selector) { + return false; + } + + return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":"); + } + + function isDetachedRulesetCallNode(node) { + return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params); + } + + function isTemplatePlaceholderNode(node) { + return node.name.startsWith("prettier-placeholder"); + } + + function isTemplatePropNode(node) { + return node.prop.startsWith("@prettier-placeholder"); + } + + function isPostcssSimpleVarNode(currentNode, nextNode) { + return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before; + } + + function hasComposesNode(node) { + return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes"; + } + + function hasParensAroundNode(node) { + return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null; + } + + function hasEmptyRawBefore(node) { + return node.raws && node.raws.before === ""; + } + + function isKeyValuePairNode(node) { + return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon"; + } + + function isKeyValuePairInParenGroupNode(node) { + return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]); + } + + function isSCSSMapItemNode(path) { + const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`) + + if (node.groups.length === 0) { + return false; + } + + const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`) + + if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) { + return false; + } + + const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`) + + if (declNode && declNode.prop && declNode.prop.startsWith("$")) { + return true; + } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`) + + + if (isKeyValuePairInParenGroupNode(parentParentNode)) { + return true; + } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`) + + + if (parentParentNode.type === "value-func") { + return true; + } + + return false; + } + + function isInlineValueCommentNode(node) { + return node.type === "value-comment" && node.inline; + } + + function isHashNode(node) { + return node.type === "value-word" && node.value === "#"; + } + + function isLeftCurlyBraceNode(node) { + return node.type === "value-word" && node.value === "{"; + } + + function isRightCurlyBraceNode(node) { + return node.type === "value-word" && node.value === "}"; + } + + function isWordNode(node) { + return ["value-word", "value-atword"].includes(node.type); + } + + function isColonNode(node) { + return node.type === "value-colon"; + } + + function isMediaAndSupportsKeywords(node) { + return node.value && ["not", "and", "or"].includes(node.value.toLowerCase()); + } + + function isColorAdjusterFuncNode(node) { + if (node.type !== "value-func") { + return false; + } + + return colorAdjusterFunctions.includes(node.value.toLowerCase()); + } // TODO: only check `less` when we don't use `less` to parse `css` + + + function isLessParser(options) { + return options.parser === "css" || options.parser === "less"; + } + + function lastLineHasInlineComment(text) { + return /\/\//.test(text.split(/[\r\n]/).pop()); + } + + var utils$2 = { + getAncestorCounter, + getAncestorNode, + getPropOfDeclNode, + maybeToLowerCase, + insideValueFunctionNode, + insideICSSRuleNode, + insideAtRuleNode, + insideURLFunctionInImportAtRuleNode, + isKeyframeAtRuleKeywords, + isWideKeywords, + isSCSS, + isLastNode, + isLessParser, + isSCSSControlDirectiveNode, + isDetachedRulesetDeclarationNode, + isRelationalOperatorNode, + isEqualityOperatorNode, + isMultiplicationNode, + isDivisionNode, + isAdditionNode, + isSubtractionNode, + isModuloNode, + isMathOperatorNode, + isEachKeywordNode, + isForKeywordNode, + isURLFunctionNode, + isIfElseKeywordNode, + hasComposesNode, + hasParensAroundNode, + hasEmptyRawBefore, + isSCSSNestedPropertyNode, + isDetachedRulesetCallNode, + isTemplatePlaceholderNode, + isTemplatePropNode, + isPostcssSimpleVarNode, + isKeyValuePairNode, + isKeyValuePairInParenGroupNode, + isSCSSMapItemNode, + isInlineValueCommentNode, + isHashNode, + isLeftCurlyBraceNode, + isRightCurlyBraceNode, + isWordNode, + isColonNode, + isMediaAndSupportsKeywords, + isColorAdjusterFuncNode, + lastLineHasInlineComment + }; + + const { + insertPragma: insertPragma$2 + } = pragma$1; + const { + printNumber: printNumber$1, + printString: printString$1, + hasIgnoreComment: hasIgnoreComment$1, + hasNewline: hasNewline$3 + } = util$1; + const { + isNextLineEmpty: isNextLineEmpty$2 + } = utilShared; + const { + restoreQuotesInInlineComments: restoreQuotesInInlineComments$1 + } = loc$1; + const { + builders: { + concat: concat$5, + join: join$2, + line: line$2, + hardline: hardline$4, + softline: softline$1, + group: group$1, + fill: fill$2, + indent: indent$2, + dedent: dedent$1, + ifBreak: ifBreak$1 + }, + utils: { + removeLines: removeLines$1 + } + } = document; + const { + getAncestorNode: getAncestorNode$1, + getPropOfDeclNode: getPropOfDeclNode$1, + maybeToLowerCase: maybeToLowerCase$1, + insideValueFunctionNode: insideValueFunctionNode$1, + insideICSSRuleNode: insideICSSRuleNode$1, + insideAtRuleNode: insideAtRuleNode$1, + insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1, + isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1, + isWideKeywords: isWideKeywords$1, + isSCSS: isSCSS$1, + isLastNode: isLastNode$1, + isLessParser: isLessParser$1, + isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1, + isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1, + isRelationalOperatorNode: isRelationalOperatorNode$1, + isEqualityOperatorNode: isEqualityOperatorNode$1, + isMultiplicationNode: isMultiplicationNode$1, + isDivisionNode: isDivisionNode$1, + isAdditionNode: isAdditionNode$1, + isSubtractionNode: isSubtractionNode$1, + isMathOperatorNode: isMathOperatorNode$1, + isEachKeywordNode: isEachKeywordNode$1, + isForKeywordNode: isForKeywordNode$1, + isURLFunctionNode: isURLFunctionNode$1, + isIfElseKeywordNode: isIfElseKeywordNode$1, + hasComposesNode: hasComposesNode$1, + hasParensAroundNode: hasParensAroundNode$1, + hasEmptyRawBefore: hasEmptyRawBefore$1, + isKeyValuePairNode: isKeyValuePairNode$1, + isDetachedRulesetCallNode: isDetachedRulesetCallNode$1, + isTemplatePlaceholderNode: isTemplatePlaceholderNode$1, + isTemplatePropNode: isTemplatePropNode$1, + isPostcssSimpleVarNode: isPostcssSimpleVarNode$1, + isSCSSMapItemNode: isSCSSMapItemNode$1, + isInlineValueCommentNode: isInlineValueCommentNode$1, + isHashNode: isHashNode$1, + isLeftCurlyBraceNode: isLeftCurlyBraceNode$1, + isRightCurlyBraceNode: isRightCurlyBraceNode$1, + isWordNode: isWordNode$1, + isColonNode: isColonNode$1, + isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1, + isColorAdjusterFuncNode: isColorAdjusterFuncNode$1, + lastLineHasInlineComment: lastLineHasInlineComment$1 + } = utils$2; + + function shouldPrintComma(options) { + switch (options.trailingComma) { + case "all": + case "es5": + return true; + + case "none": + default: + return false; + } + } + + function genericPrint(path, options, print) { + const node = path.getValue(); + /* istanbul ignore if */ + + if (!node) { + return ""; + } + + if (typeof node === "string") { + return node; + } + + switch (node.type) { + case "yaml": + case "toml": + return concat$5([node.raw, hardline$4]); + + case "css-root": + { + const nodes = printNodeSequence(path, options, print); + + if (nodes.parts.length) { + return concat$5([nodes, options.__isHTMLStyleAttribute ? "" : hardline$4]); + } + + return nodes; + } + + case "css-comment": + { + const isInlineComment = node.inline || node.raws.inline; + const text = options.originalText.slice(options.locStart(node), options.locEnd(node)); + return isInlineComment ? text.trimEnd() : text; + } + + case "css-rule": + { + return concat$5([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$5([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$2 : " ", "{", node.nodes.length > 0 ? indent$2(concat$5([hardline$4, printNodeSequence(path, options, print)])) : "", hardline$4, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]); + } + + case "css-decl": + { + const parentNode = path.getParentNode(); + return concat$5([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode$1(node) ? removeLines$1(path.call(print, "value")) : path.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$5([" {", indent$2(concat$5([softline$1, printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]); + } + + case "css-atrule": + { + const parentNode = path.getParentNode(); + const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";"; + + if (isLessParser$1(options)) { + if (node.mixin) { + return concat$5([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); + } + + if (node.function) { + return concat$5([node.name, concat$5([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); + } + + if (node.variable) { + return concat$5(["@", node.name, ": ", node.value ? concat$5([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$5(["{", indent$2(concat$5([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); + } + } + + return concat$5(["@", // If a Less file ends up being parsed with the SCSS parser, Less + // variable declarations will be parsed as at-rules with names ending + // with a colon, so keep the original case then. + isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$5([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$5([hardline$4, hardline$4]) : /^\s*\n/.test(node.raws.afterName) ? hardline$4 : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$2(concat$5([" ", path.call(print, "selector")])) : "", node.value ? group$1(concat$5([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$2 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$5([isSCSSControlDirectiveNode$1(node) ? "" : " ", "{", indent$2(concat$5([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); + } + // postcss-media-query-parser + + case "media-query-list": + { + const parts = []; + path.each(childPath => { + const node = childPath.getValue(); + + if (node.type === "media-query" && node.value === "") { + return; + } + + parts.push(childPath.call(print)); + }, "nodes"); + return group$1(indent$2(join$2(line$2, parts))); + } + + case "media-query": + { + return concat$5([join$2(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]); + } + + case "media-type": + { + return adjustNumbers(adjustStrings(node.value, options)); + } + + case "media-feature-expression": + { + if (!node.nodes) { + return node.value; + } + + return concat$5(["(", concat$5(path.map(print, "nodes")), ")"]); + } + + case "media-feature": + { + return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options)); + } + + case "media-colon": + { + return concat$5([node.value, " "]); + } + + case "media-value": + { + return adjustNumbers(adjustStrings(node.value, options)); + } + + case "media-keyword": + { + return adjustStrings(node.value, options); + } + + case "media-url": + { + return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options); + } + + case "media-unknown": + { + return node.value; + } + // postcss-selector-parser + + case "selector-root": + { + return group$1(concat$5([insideAtRuleNode$1(path, "custom-selector") ? concat$5([getAncestorNode$1(path, "css-atrule").customSelector, line$2]) : "", join$2(concat$5([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$2 : hardline$4]), path.map(print, "nodes"))])); + } + + case "selector-selector": + { + return group$1(indent$2(concat$5(path.map(print, "nodes")))); + } + + case "selector-comment": + { + return node.value; + } + + case "selector-string": + { + return adjustStrings(node.value, options); + } + + case "selector-tag": + { + const parentNode = path.getParentNode(); + const index = parentNode && parentNode.nodes.indexOf(node); + const prevNode = index && parentNode.nodes[index - 1]; + return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]); + } + + case "selector-id": + { + return concat$5(["#", node.value]); + } + + case "selector-class": + { + return concat$5([".", adjustNumbers(adjustStrings(node.value, options))]); + } + + case "selector-attribute": + { + return concat$5(["[", node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]); + } + + case "selector-combinator": + { + if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") { + const parentNode = path.getParentNode(); + const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$2; + return concat$5([leading, node.value, isLastNode$1(path, node) ? "" : " "]); + } + + const leading = node.value.trim().startsWith("(") ? line$2 : ""; + const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$2; + return concat$5([leading, value]); + } + + case "selector-universal": + { + return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]); + } + + case "selector-pseudo": + { + return concat$5([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$5(["(", join$2(", ", path.map(print, "nodes")), ")"]) : ""]); + } + + case "selector-nesting": + { + return node.value; + } + + case "selector-unknown": + { + const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property + + if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) { + return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options)); + } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js + + + const parentNode = path.getParentNode(); + + if (parentNode.raws && parentNode.raws.selector) { + const start = options.locStart(parentNode); + const end = start + parentNode.raws.selector.length; + return options.originalText.slice(start, end).trim(); + } + + return node.value; + } + // postcss-values-parser + + case "value-value": + case "value-root": + { + return path.call(print, "group"); + } + + case "value-comment": + { + return concat$5([node.inline ? "//" : "/*", // see replaceQuotesInInlineComments in loc.js + // value-* nodes don't have correct location data, so we have to rely on placeholder characters. + restoreQuotesInInlineComments$1(node.value), node.inline ? "" : "*/"]); + } + + case "value-comma_group": + { + const parentNode = path.getParentNode(); + const parentParentNode = path.getParentNode(1); + const declAncestorProp = getPropOfDeclNode$1(path); + const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template")); + const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); + const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode); + const printed = path.map(print, "groups"); + const parts = []; + const insideURLFunction = insideValueFunctionNode$1(path, "url"); + let insideSCSSInterpolationInString = false; + let didBreak = false; + + for (let i = 0; i < node.groups.length; ++i) { + parts.push(printed[i]); + const iPrevNode = node.groups[i - 1]; + const iNode = node.groups[i]; + const iNextNode = node.groups[i + 1]; + const iNextNextNode = node.groups[i + 2]; + + if (insideURLFunction) { + if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) { + parts.push(" "); + } + + continue; + } // Ignore after latest node (i.e. before semicolon) + + + if (!iNextNode) { + continue; + } // styled.div` background: var(--${one}); ` + + + if (!iPrevNode && iNode.value === "--" && iNextNode.type === "value-atword") { + continue; + } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`) + + + const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{"); + const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}"); + + if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) { + insideSCSSInterpolationInString = !insideSCSSInterpolationInString; + continue; + } + + if (insideSCSSInterpolationInString) { + continue; + } // Ignore colon (i.e. `:`) + + + if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) { + continue; + } // Ignore `@` in Less (i.e. `@@var;`) + + + if (iNode.type === "value-atword" && iNode.value === "") { + continue; + } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`) + + + if (iNode.value === "~") { + continue; + } // Ignore escape `\` + + + if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") { + continue; + } // Ignore escaped `/` + + + if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") { + continue; + } // Ignore `\` (i.e. `$variable: \@small;`) + + + if (iNode.value === "\\") { + continue; + } // Ignore `$$` (i.e. `background-color: $$(style)Color;`) + + + if (isPostcssSimpleVarNode$1(iNode, iNextNode)) { + continue; + } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`) + + + if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) { + continue; + } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`) + + + if (iNode.value === "--" && isHashNode$1(iNextNode)) { + continue; + } // Formatting math operations + + + const isMathOperator = isMathOperatorNode$1(iNode); + const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is + // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`) + // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`) + + if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) { + continue; + } // Print spaces before and after addition and subtraction math operators as is in `calc` function + // due to the fact that it is not valid syntax + // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`) + + + if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) { + continue; + } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`) + // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is. + + + const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode); + const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode); + const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign + + if (!(isMultiplicationNode$1(iNextNode) || isMultiplicationNode$1(iNode)) && !insideValueFunctionNode$1(path, "calc") && !isColorAdjusterNode && (isDivisionNode$1(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode$1(iNode) && !requireSpaceAfterOperator || isAdditionNode$1(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode$1(iNode) && !requireSpaceAfterOperator || isSubtractionNode$1(iNextNode) || isSubtractionNode$1(iNode)) && (hasEmptyRawBefore$1(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode$1(iPrevNode)))) { + continue; + } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`) + + + if (isInlineValueCommentNode$1(iNode)) { + parts.push(hardline$4); + continue; + } // Handle keywords in SCSS control directive + + + if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) { + parts.push(" "); + continue; + } // At-rule `namespace` should be in one line + + + if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") { + parts.push(" "); + continue; + } // Formatting `grid` property + + + if (isGridValue) { + if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) { + parts.push(hardline$4); + didBreak = true; + } else { + parts.push(" "); + } + + continue; + } // Add `space` before next math operation + // Note: `grip` property have `/` delimiter and it is not math operation, so + // `grid` property handles above + + + if (isNextMathOperator) { + parts.push(" "); + continue; + } // Be default all values go through `line` + + + parts.push(line$2); + } + + if (didBreak) { + parts.unshift(hardline$4); + } + + if (isControlDirective) { + return group$1(indent$2(concat$5(parts))); + } // Indent is not needed for import url when url is very long + // and node has two groups + // when type is value-comma_group + // example @import url("verylongurl") projection,tv + + + if (insideURLFunctionInImportAtRuleNode$1(path)) { + return group$1(fill$2(parts)); + } + + return group$1(indent$2(fill$2(parts))); + } + + case "value-paren_group": + { + const parentNode = path.getParentNode(); + + if (parentNode && isURLFunctionNode$1(parentNode) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) { + return concat$5([node.open ? path.call(print, "open") : "", join$2(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]); + } + + if (!node.open) { + const printed = path.map(print, "groups"); + const res = []; + + for (let i = 0; i < printed.length; i++) { + if (i !== 0) { + res.push(concat$5([",", line$2])); + } + + res.push(printed[i]); + } + + return group$1(indent$2(fill$2(res))); + } + + const isSCSSMapItem = isSCSSMapItemNode$1(path); + const lastItem = node.groups[node.groups.length - 1]; + const isLastItemComment = lastItem && lastItem.type === "value-comment"; + return group$1(concat$5([node.open ? path.call(print, "open") : "", indent$2(concat$5([softline$1, join$2(concat$5([",", line$2]), path.map(childPath => { + const node = childPath.getValue(); + const printed = print(childPath); // Key/Value pair in open paren already indented + + if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") { + printed.contents.contents.parts[1] = group$1(printed.contents.contents.parts[1]); + return group$1(dedent$1(printed)); + } + + return printed; + }, "groups"))])), ifBreak$1(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma(options) ? "," : ""), softline$1, node.close ? path.call(print, "close") : ""]), { + shouldBreak: isSCSSMapItem + }); + } + + case "value-func": + { + return concat$5([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]); + } + + case "value-paren": + { + return node.value; + } + + case "value-number": + { + return concat$5([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]); + } + + case "value-operator": + { + return node.value; + } + + case "value-word": + { + if (node.isColor && node.isHex || isWideKeywords$1(node.value)) { + return node.value.toLowerCase(); + } + + return node.value; + } + + case "value-colon": + { + return concat$5([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`) + insideValueFunctionNode$1(path, "url") ? "" : line$2]); + } + + case "value-comma": + { + return concat$5([node.value, " "]); + } + + case "value-string": + { + return printString$1(node.raws.quote + node.value + node.raws.quote, options); + } + + case "value-atword": + { + return concat$5(["@", node.value]); + } + + case "value-unicode-range": + { + return node.value; + } + + case "value-unknown": + { + return node.value; + } + + default: + /* istanbul ignore next */ + throw new Error("Unknown postcss type ".concat(JSON.stringify(node.type))); + } + } + + function printNodeSequence(path, options, print) { + const node = path.getValue(); + const parts = []; + let i = 0; + path.map(pathChild => { + const prevNode = node.nodes[i - 1]; + + if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") { + const childNode = pathChild.getValue(); + parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode))); + } else { + parts.push(pathChild.call(print)); + } + + if (i !== node.nodes.length - 1) { + if (node.nodes[i + 1].type === "css-comment" && !hasNewline$3(options.originalText, options.locStart(node.nodes[i + 1]), { + backwards: true + }) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml" || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") { + parts.push(" "); + } else { + parts.push(options.__isHTMLStyleAttribute ? line$2 : hardline$4); + + if (isNextLineEmpty$2(options.originalText, pathChild.getValue(), options.locEnd) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") { + parts.push(hardline$4); + } + } + } + + i++; + }, "nodes"); + return concat$5(parts); + } + + const STRING_REGEX$3 = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g; + const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g; + const STANDARD_UNIT_REGEX = /[a-zA-Z]+/g; + const WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g; + const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + "(".concat(WORD_PART_REGEX.source, ")?") + "(".concat(NUMBER_REGEX.source, ")") + "(".concat(STANDARD_UNIT_REGEX.source, ")?"), "g"); + + function adjustStrings(value, options) { + return value.replace(STRING_REGEX$3, match => printString$1(match, options)); + } + + function quoteAttributeValue(value, options) { + const quote = options.singleQuote ? "'" : '"'; + return value.includes('"') || value.includes("'") ? value : quote + value + quote; + } + + function adjustNumbers(value) { + return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match); + } + + function printCssNumber(rawNumber) { + return printNumber$1(rawNumber) // Remove trailing `.0`. + .replace(/\.0(?=$|e)/, ""); + } + + var printerPostcss = { + print: genericPrint, + embed: embed_1, + insertPragma: insertPragma$2, + hasPrettierIgnore: hasIgnoreComment$1, + massageAstNode: clean_1 + }; + + const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js + + var commonOptions = { + bracketSpacing: { + since: "0.0.0", + category: CATEGORY_COMMON, + type: "boolean", + default: true, + description: "Print spaces between brackets.", + oppositeDescription: "Do not print spaces between brackets." + }, + singleQuote: { + since: "0.0.0", + category: CATEGORY_COMMON, + type: "boolean", + default: false, + description: "Use single quotes instead of double quotes." + }, + proseWrap: { + since: "1.8.2", + category: CATEGORY_COMMON, + type: "choice", + default: [{ + since: "1.8.2", + value: true + }, { + since: "1.9.0", + value: "preserve" + }], + description: "How to wrap prose.", + choices: [{ + since: "1.9.0", + value: "always", + description: "Wrap prose if it exceeds the print width." + }, { + since: "1.9.0", + value: "never", + description: "Do not wrap prose." + }, { + since: "1.9.0", + value: "preserve", + description: "Wrap prose as-is." + }] + } + }; + + var options$2 = { + singleQuote: commonOptions.singleQuote + }; + + var createLanguage = function createLanguage(linguistData, override) { + const { + languageId + } = linguistData, + rest = _objectWithoutPropertiesLoose(linguistData, ["languageId"]); + + return Object.assign({ + linguistLanguageId: languageId + }, rest, {}, override(linguistData)); + }; + + var name$1 = "CSS"; + var type = "markup"; + var tmScope = "source.css"; + var aceMode = "css"; + var codemirrorMode = "css"; + var codemirrorMimeType = "text/css"; + var color = "#563d7c"; + var extensions = [ + ".css" + ]; + var languageId = 50; + var CSS = { + name: name$1, + type: type, + tmScope: tmScope, + aceMode: aceMode, + codemirrorMode: codemirrorMode, + codemirrorMimeType: codemirrorMimeType, + color: color, + extensions: extensions, + languageId: languageId + }; + + var CSS$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$1, + type: type, + tmScope: tmScope, + aceMode: aceMode, + codemirrorMode: codemirrorMode, + codemirrorMimeType: codemirrorMimeType, + color: color, + extensions: extensions, + languageId: languageId, + 'default': CSS + }); + + var name$2 = "PostCSS"; + var type$1 = "markup"; + var tmScope$1 = "source.postcss"; + var group$2 = "CSS"; + var extensions$1 = [ + ".pcss", + ".postcss" + ]; + var aceMode$1 = "text"; + var languageId$1 = 262764437; + var PostCSS = { + name: name$2, + type: type$1, + tmScope: tmScope$1, + group: group$2, + extensions: extensions$1, + aceMode: aceMode$1, + languageId: languageId$1 + }; + + var PostCSS$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$2, + type: type$1, + tmScope: tmScope$1, + group: group$2, + extensions: extensions$1, + aceMode: aceMode$1, + languageId: languageId$1, + 'default': PostCSS + }); + + var name$3 = "Less"; + var type$2 = "markup"; + var group$3 = "CSS"; + var extensions$2 = [ + ".less" + ]; + var tmScope$2 = "source.css.less"; + var aceMode$2 = "less"; + var codemirrorMode$1 = "css"; + var codemirrorMimeType$1 = "text/css"; + var languageId$2 = 198; + var Less = { + name: name$3, + type: type$2, + group: group$3, + extensions: extensions$2, + tmScope: tmScope$2, + aceMode: aceMode$2, + codemirrorMode: codemirrorMode$1, + codemirrorMimeType: codemirrorMimeType$1, + languageId: languageId$2 + }; + + var Less$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$3, + type: type$2, + group: group$3, + extensions: extensions$2, + tmScope: tmScope$2, + aceMode: aceMode$2, + codemirrorMode: codemirrorMode$1, + codemirrorMimeType: codemirrorMimeType$1, + languageId: languageId$2, + 'default': Less + }); + + var name$4 = "SCSS"; + var type$3 = "markup"; + var tmScope$3 = "source.css.scss"; + var group$4 = "CSS"; + var aceMode$3 = "scss"; + var codemirrorMode$2 = "css"; + var codemirrorMimeType$2 = "text/x-scss"; + var extensions$3 = [ + ".scss" + ]; + var languageId$3 = 329; + var SCSS = { + name: name$4, + type: type$3, + tmScope: tmScope$3, + group: group$4, + aceMode: aceMode$3, + codemirrorMode: codemirrorMode$2, + codemirrorMimeType: codemirrorMimeType$2, + extensions: extensions$3, + languageId: languageId$3 + }; + + var SCSS$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$4, + type: type$3, + tmScope: tmScope$3, + group: group$4, + aceMode: aceMode$3, + codemirrorMode: codemirrorMode$2, + codemirrorMimeType: codemirrorMimeType$2, + extensions: extensions$3, + languageId: languageId$3, + 'default': SCSS + }); + + var require$$0$2 = getCjsExportFromNamespace(CSS$1); + + var require$$1 = getCjsExportFromNamespace(PostCSS$1); + + var require$$2 = getCjsExportFromNamespace(Less$1); + + var require$$3 = getCjsExportFromNamespace(SCSS$1); + + const languages = [createLanguage(require$$0$2, () => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["css"] + })), createLanguage(require$$1, () => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["postcss"] + })), createLanguage(require$$2, () => ({ + since: "1.4.0", + parsers: ["less"], + vscodeLanguageIds: ["less"] + })), createLanguage(require$$3, () => ({ + since: "1.4.0", + parsers: ["scss"], + vscodeLanguageIds: ["scss"] + }))]; + const printers = { + postcss: printerPostcss + }; + var languageCss = { + languages, + options: options$2, + printers + }; + + function hasPragma$2(text) { + return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text); + } + + function insertPragma$3(text) { + return "# @format\n\n" + text; + } + + var pragma$2 = { + hasPragma: hasPragma$2, + insertPragma: insertPragma$3 + }; + + const { + concat: concat$6, + join: join$3, + hardline: hardline$5, + line: line$3, + softline: softline$2, + group: group$5, + indent: indent$3, + ifBreak: ifBreak$2 + } = document.builders; + const { + hasIgnoreComment: hasIgnoreComment$2 + } = util$1; + const { + isNextLineEmpty: isNextLineEmpty$3 + } = utilShared; + const { + insertPragma: insertPragma$4 + } = pragma$2; + + function genericPrint$1(path, options, print) { + const n = path.getValue(); + + if (!n) { + return ""; + } + + if (typeof n === "string") { + return n; + } + + switch (n.kind) { + case "Document": + { + const parts = []; + path.map((pathChild, index) => { + parts.push(concat$6([pathChild.call(print)])); + + if (index !== n.definitions.length - 1) { + parts.push(hardline$5); + + if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options.locEnd)) { + parts.push(hardline$5); + } + } + }, "definitions"); + return concat$6([concat$6(parts), hardline$5]); + } + + case "OperationDefinition": + { + const hasOperation = options.originalText[options.locStart(n)] !== "{"; + const hasName = !!n.name; + return concat$6([hasOperation ? n.operation : "", hasOperation && hasName ? concat$6([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]); + } + + case "FragmentDefinition": + { + return concat$6(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); + } + + case "SelectionSet": + { + return concat$6(["{", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$5, "}"]); + } + + case "Field": + { + return group$5(concat$6([n.alias ? concat$6([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")])); + } + + case "Name": + { + return n.value; + } + + case "StringValue": + { + if (n.block) { + return concat$6(['"""', hardline$5, join$3(hardline$5, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$5, '"""']); + } + + return concat$6(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']); + } + + case "IntValue": + case "FloatValue": + case "EnumValue": + { + return n.value; + } + + case "BooleanValue": + { + return n.value ? "true" : "false"; + } + + case "NullValue": + { + return "null"; + } + + case "Variable": + { + return concat$6(["$", path.call(print, "name")]); + } + + case "ListValue": + { + return group$5(concat$6(["[", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "values"))])), softline$2, "]"])); + } + + case "ObjectValue": + { + return group$5(concat$6(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "fields"))])), softline$2, ifBreak$2("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"])); + } + + case "ObjectField": + case "Argument": + { + return concat$6([path.call(print, "name"), ": ", path.call(print, "value")]); + } + + case "Directive": + { + return concat$6(["@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : ""]); + } + + case "NamedType": + { + return path.call(print, "name"); + } + + case "VariableDefinition": + { + return concat$6([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); + } + + case "TypeExtensionDefinition": + { + return concat$6(["extend ", path.call(print, "definition")]); + } + + case "ObjectTypeExtension": + case "ObjectTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$6([" implements ", concat$6(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]); + } + + case "FieldDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]); + } + + case "DirectiveDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", n.repeatable ? " repeatable" : "", concat$6([" on ", join$3(" | ", path.map(print, "locations"))])]); + } + + case "EnumTypeExtension": + case "EnumTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$5, "}"]) : ""]); + } + + case "EnumValueDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "InputValueDefinition": + { + return concat$6([path.call(print, "description"), n.description ? n.description.block ? hardline$5 : line$3 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); + } + + case "InputObjectTypeExtension": + case "InputObjectTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]); + } + + case "SchemaDefinition": + { + return concat$6(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$5, "}"]); + } + + case "OperationTypeDefinition": + { + return concat$6([path.call(print, "operation"), ": ", path.call(print, "type")]); + } + + case "InterfaceTypeExtension": + case "InterfaceTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]); + } + + case "FragmentSpread": + { + return concat$6(["...", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "InlineFragment": + { + return concat$6(["...", n.typeCondition ? concat$6([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); + } + + case "UnionTypeExtension": + case "UnionTypeDefinition": + { + return group$5(concat$6([path.call(print, "description"), n.description ? hardline$5 : "", group$5(concat$6([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$6([" =", ifBreak$2("", " "), indent$3(concat$6([ifBreak$2(concat$6([line$3, " "])), join$3(concat$6([line$3, "| "]), path.map(print, "types"))]))]) : ""]))])); + } + + case "ScalarTypeExtension": + case "ScalarTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "NonNullType": + { + return concat$6([path.call(print, "type"), "!"]); + } + + case "ListType": + { + return concat$6(["[", path.call(print, "type"), "]"]); + } + + default: + /* istanbul ignore next */ + throw new Error("unknown graphql type: " + JSON.stringify(n.kind)); + } + } + + function printDirectives(path, print, n) { + if (n.directives.length === 0) { + return ""; + } + + return concat$6([" ", group$5(indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", " "), softline$2]), path.map(print, "directives"))])))]); + } + + function printSequence(sequencePath, options, print) { + const count = sequencePath.getValue().length; + return sequencePath.map((path, i) => { + const printed = print(path); + + if (isNextLineEmpty$3(options.originalText, path.getValue(), options.locEnd) && i < count - 1) { + return concat$6([printed, hardline$5]); + } + + return printed; + }); + } + + function canAttachComment(node) { + return node.kind && node.kind !== "Comment"; + } + + function printComment$1(commentPath) { + const comment = commentPath.getValue(); + + if (comment.kind === "Comment") { + return "#" + comment.value.trimEnd(); + } + + throw new Error("Not a comment: " + JSON.stringify(comment)); + } + + function determineInterfaceSeparatorBetween(first, second, options) { + const textBetween = options.originalText.slice(first.loc.end, second.loc.start).replace(/#.*/g, "").trim(); + return textBetween === "," ? ", " : " & "; + } + + function printInterfaces(path, options, print) { + const node = path.getNode(); + const parts = []; + const { + interfaces + } = node; + const printed = path.map(node => print(node), "interfaces"); + + for (let index = 0; index < interfaces.length; index++) { + const interfaceNode = interfaces[index]; + + if (index > 0) { + parts.push(determineInterfaceSeparatorBetween(interfaces[index - 1], interfaceNode, options)); + } + + parts.push(printed[index]); + } + + return parts; + } + + function clean$1(node, newNode + /*, parent*/ + ) { + delete newNode.loc; + delete newNode.comments; + } + + var printerGraphql = { + print: genericPrint$1, + massageAstNode: clean$1, + hasPrettierIgnore: hasIgnoreComment$2, + insertPragma: insertPragma$4, + printComment: printComment$1, + canAttachComment + }; + + var options$3 = { + bracketSpacing: commonOptions.bracketSpacing + }; + + var name$5 = "GraphQL"; + var type$4 = "data"; + var extensions$4 = [ + ".graphql", + ".gql", + ".graphqls" + ]; + var tmScope$4 = "source.graphql"; + var aceMode$4 = "text"; + var languageId$4 = 139; + var GraphQL = { + name: name$5, + type: type$4, + extensions: extensions$4, + tmScope: tmScope$4, + aceMode: aceMode$4, + languageId: languageId$4 + }; + + var GraphQL$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$5, + type: type$4, + extensions: extensions$4, + tmScope: tmScope$4, + aceMode: aceMode$4, + languageId: languageId$4, + 'default': GraphQL + }); + + var require$$0$3 = getCjsExportFromNamespace(GraphQL$1); + + const languages$1 = [createLanguage(require$$0$3, () => ({ + since: "1.5.0", + parsers: ["graphql"], + vscodeLanguageIds: ["graphql"] + }))]; + const printers$1 = { + graphql: printerGraphql + }; + var languageGraphql = { + languages: languages$1, + options: options$3, + printers: printers$1 + }; + + var clean$2 = function clean(ast, newNode) { + delete newNode.loc; + delete newNode.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace + + if (ast.type === "TextNode") { + const trimmed = ast.chars.trim(); + + if (!trimmed) { + return null; + } + + newNode.chars = trimmed; + } + }; + + function isUppercase(string) { + return string.toUpperCase() === string; + } + + function isGlimmerComponent(node) { + return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes(".")); + } + + function isWhitespaceNode(node) { + return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars); + } + + function isNodeOfSomeType(node, types) { + return node && types.some(type => node.type === type); + } + + function isParentOfSomeType(path, types) { + const parentNode = path.getParentNode(0); + return isNodeOfSomeType(parentNode, types); + } + + function isPreviousNodeOfSomeType(path, types) { + const previousNode = getPreviousNode(path); + return isNodeOfSomeType(previousNode, types); + } + + function isNextNodeOfSomeType(path, types) { + const nextNode = getNextNode(path); + return isNodeOfSomeType(nextNode, types); + } + + function getSiblingNode(path, offset) { + const node = path.getValue(); + const parentNode = path.getParentNode(0) || {}; + const children = parentNode.children || parentNode.body || []; + const index = children.indexOf(node); + return index !== -1 && children[index + offset]; + } + + function getPreviousNode(path, lookBack = 1) { + return getSiblingNode(path, -lookBack); + } + + function getNextNode(path) { + return getSiblingNode(path, 1); + } + + function isPrettierIgnoreNode(node) { + return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore"; + } + + function hasPrettierIgnore(path) { + const node = path.getValue(); + const previousPreviousNode = getPreviousNode(path, 2); + return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode); + } + + var utils$3 = { + getNextNode, + getPreviousNode, + hasPrettierIgnore, + isGlimmerComponent, + isNextNodeOfSomeType, + isNodeOfSomeType, + isParentOfSomeType, + isPreviousNodeOfSomeType, + isWhitespaceNode + }; + + const { + concat: concat$7, + join: join$4, + softline: softline$3, + hardline: hardline$6, + line: line$4, + group: group$6, + indent: indent$4, + ifBreak: ifBreak$3 + } = document.builders; + const { + getNextNode: getNextNode$1, + getPreviousNode: getPreviousNode$1, + hasPrettierIgnore: hasPrettierIgnore$1, + isGlimmerComponent: isGlimmerComponent$1, + isNextNodeOfSomeType: isNextNodeOfSomeType$1, + isParentOfSomeType: isParentOfSomeType$1, + isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1, + isWhitespaceNode: isWhitespaceNode$1 + } = utils$3; // http://w3c.github.io/html/single-page.html#void-elements + + const voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]; // Formatter based on @glimmerjs/syntax's built-in test formatter: + // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts + + function print(path, options, print) { + const n = path.getValue(); + /* istanbul ignore if*/ + + if (!n) { + return ""; + } + + if (hasPrettierIgnore$1(path)) { + const startOffset = locationToOffset(options.originalText, n.loc.start.line - 1, n.loc.start.column); + const endOffset = locationToOffset(options.originalText, n.loc.end.line - 1, n.loc.end.column); + const ignoredText = options.originalText.slice(startOffset, endOffset); + return ignoredText; + } + + switch (n.type) { + case "Block": + case "Program": + case "Template": + { + return group$6(concat$7(path.map(print, "body"))); + } + + case "ElementNode": + { + const hasChildren = n.children.length > 0; + const hasNonWhitespaceChildren = n.children.some(n => !isWhitespaceNode$1(n)); + const isVoid = isGlimmerComponent$1(n) && (!hasChildren || !hasNonWhitespaceChildren) || voidTags.includes(n.tag); + const closeTagForNoBreak = isVoid ? concat$7([" />", softline$3]) : ">"; + const closeTagForBreak = isVoid ? "/>" : ">"; + + const printParams = (path, print) => indent$4(concat$7([n.attributes.length ? line$4 : "", join$4(line$4, path.map(print, "attributes")), n.modifiers.length ? line$4 : "", join$4(line$4, path.map(print, "modifiers")), n.comments.length ? line$4 : "", join$4(line$4, path.map(print, "comments"))])); + + const nextNode = getNextNode$1(path); + return concat$7([group$6(concat$7(["<", n.tag, printParams(path, print), n.blockParams.length ? " as |".concat(n.blockParams.join(" "), "|") : "", ifBreak$3(softline$3, ""), ifBreak$3(closeTagForBreak, closeTagForNoBreak)])), !isVoid ? group$6(concat$7([hasNonWhitespaceChildren ? indent$4(printChildren(path, options, print)) : "", ifBreak$3(hasChildren ? hardline$6 : "", ""), concat$7(["</", n.tag, ">"])])) : "", nextNode && nextNode.type === "ElementNode" ? hardline$6 : ""]); + } + + case "BlockStatement": + { + const pp = path.getParentNode(1); + const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if"; + const hasElseIf = n.inverse && n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if"; + const indentElse = hasElseIf ? a => a : indent$4; + const inverseElseStatement = (n.inverseStrip.open ? "{{~" : "{{") + "else" + (n.inverseStrip.close ? "~}}" : "}}"); + + if (n.inverse) { + return concat$7([isElseIf ? concat$7([n.openStrip.open ? "{{~else " : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]) : printOpenBlock(path, print, n.openStrip), indent$4(concat$7([hardline$6, path.call(print, "program")])), n.inverse && !hasElseIf ? concat$7([hardline$6, inverseElseStatement]) : "", n.inverse ? indentElse(concat$7([hardline$6, path.call(print, "inverse")])) : "", isElseIf ? "" : concat$7([hardline$6, printCloseBlock(path, print, n.closeStrip)])]); + } else if (isElseIf) { + return concat$7([concat$7([n.openStrip.open ? "{{~else" : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]), indent$4(concat$7([hardline$6, path.call(print, "program")]))]); + } + + const hasNonWhitespaceChildren = n.program.body.some(n => !isWhitespaceNode$1(n)); + return concat$7([printOpenBlock(path, print, n.openStrip), group$6(concat$7([indent$4(concat$7([softline$3, path.call(print, "program")])), hasNonWhitespaceChildren ? hardline$6 : softline$3, printCloseBlock(path, print, n.closeStrip)]))]); + } + + case "ElementModifierStatement": + { + return group$6(concat$7(["{{", printPathParams(path, print), softline$3, "}}"])); + } + + case "MustacheStatement": + { + const isEscaped = n.escaped === false; + const { + open: openStrip, + close: closeStrip + } = n.strip; + const opening = (isEscaped ? "{{{" : "{{") + (openStrip ? "~" : ""); + const closing = (closeStrip ? "~" : "") + (isEscaped ? "}}}" : "}}"); + const leading = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement", "ElementNode"]) ? [opening, indent$4(softline$3)] : [opening]; + return group$6(concat$7([...leading, printPathParams(path, print), softline$3, closing])); + } + + case "SubExpression": + { + const params = printParams(path, print); + const printedParams = params.length > 0 ? indent$4(concat$7([line$4, group$6(join$4(line$4, params))])) : ""; + return group$6(concat$7(["(", printPath(path, print), printedParams, softline$3, ")"])); + } + + case "AttrNode": + { + const isText = n.value.type === "TextNode"; + const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end columns are the + // same, there is no value for this AttrNode and it should be printed + // without the `=""`. Example: `<img data-test>` -> `<img data-test>` + + const isEmptyValue = isEmptyText && n.value.loc.start.column === n.value.loc.end.column; + + if (isEmptyValue) { + return concat$7([n.name]); + } + + const value = path.call(print, "value"); + const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value; + return concat$7([n.name, "=", quotedValue]); + } + + case "ConcatStatement": + { + return concat$7(['"', concat$7(path.map(partPath => print(partPath), "parts").filter(a => a !== "")), '"']); + } + + case "Hash": + { + return concat$7([join$4(line$4, path.map(print, "pairs"))]); + } + + case "HashPair": + { + return concat$7([n.key, "=", path.call(print, "value")]); + } + + case "TextNode": + { + const maxLineBreaksToPreserve = 2; + const isFirstElement = !getPreviousNode$1(path); + const isLastElement = !getNextNode$1(path); + const isWhitespaceOnly = !/\S/.test(n.chars); + const lineBreaksCount = countNewLines(n.chars); + const hasBlockParent = path.getParentNode(0).type === "Block"; + const hasElementParent = path.getParentNode(0).type === "ElementNode"; + const hasTemplateParent = path.getParentNode(0).type === "Template"; + let leadingLineBreaksCount = countLeadingNewLines(n.chars); + let trailingLineBreaksCount = countTrailingNewLines(n.chars); + + if ((isFirstElement || isLastElement) && isWhitespaceOnly && (hasBlockParent || hasElementParent || hasTemplateParent)) { + return ""; + } + + if (isWhitespaceOnly && lineBreaksCount) { + leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve); + trailingLineBreaksCount = 0; + } else { + if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) { + trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1); + } + + if (isPreviousNodeOfSomeType$1(path, ["ElementNode"]) || isPreviousNodeOfSomeType$1(path, ["BlockStatement"])) { + leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1); + } + } + + let leadingSpace = ""; + let trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present, + // when next to mustache statement. + + const inAttrNode = path.stack.includes("attributes"); + + if (inAttrNode) { + const parentNode = path.getParentNode(0); + const isConcat = parentNode.type === "ConcatStatement"; + + if (isConcat) { + const { + parts + } = parentNode; + const partIndex = parts.indexOf(n); + + if (partIndex > 0) { + const partType = parts[partIndex - 1].type; + const isMustache = partType === "MustacheStatement"; + + if (isMustache) { + leadingSpace = " "; + } + } + + if (partIndex < parts.length - 1) { + const partType = parts[partIndex + 1].type; + const isMustache = partType === "MustacheStatement"; + + if (isMustache) { + trailingSpace = " "; + } + } + } + } else { + if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) { + trailingSpace = " "; + } + + if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) { + leadingSpace = " "; + } + + if (isFirstElement) { + leadingLineBreaksCount = 0; + leadingSpace = ""; + } + + if (isLastElement) { + trailingLineBreaksCount = 0; + trailingSpace = ""; + } + } + + return concat$7([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^[\s ]+/g, leadingSpace).replace(/[\s ]+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)].filter(Boolean)); + } + + case "MustacheCommentStatement": + { + const dashes = n.value.includes("}}") ? "--" : ""; + return concat$7(["{{!", dashes, n.value, dashes, "}}"]); + } + + case "PathExpression": + { + return n.original; + } + + case "BooleanLiteral": + { + return String(n.value); + } + + case "CommentStatement": + { + return concat$7(["<!--", n.value, "-->"]); + } + + case "StringLiteral": + { + return printStringLiteral(n.value, options); + } + + case "NumberLiteral": + { + return String(n.value); + } + + case "UndefinedLiteral": + { + return "undefined"; + } + + case "NullLiteral": + { + return "null"; + } + + /* istanbul ignore next */ + + default: + throw new Error("unknown glimmer type: " + JSON.stringify(n.type)); + } + } + + function printChildren(path, options, print) { + return concat$7(path.map((childPath, childIndex) => { + const childNode = path.getValue(); + const isFirstNode = childIndex === 0; + const isLastNode = childIndex === path.getParentNode(0).children.length - 1; + const isLastNodeInMultiNodeList = isLastNode && !isFirstNode; + const isWhitespace = isWhitespaceNode$1(childNode); + + if (isWhitespace && isLastNodeInMultiNodeList) { + return print(childPath, options, print); + } else if (isFirstNode) { + return concat$7([softline$3, print(childPath, options, print)]); + } + + return print(childPath, options, print); + }, "children")); + } + /** + * Prints a string literal with the correct surrounding quotes based on + * `options.singleQuote` and the number of escaped quotes contained in + * the string literal. This function is the glimmer equivalent of `printString` + * in `common/util`, but has differences because of the way escaped characters + * are treated in hbs string literals. + * @param {string} stringLiteral - the string literal value + * @param {object} options - the prettier options object + */ + + + function printStringLiteral(stringLiteral, options) { + const double = { + quote: '"', + regex: /"/g + }; + const single = { + quote: "'", + regex: /'/g + }; + const preferred = options.singleQuote ? single : double; + const alternate = preferred === single ? double : single; + let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for + // enclosing the string, we might want to enclose with the alternate quote + // instead, to minimize the number of escaped quotes. + + if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) { + const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length; + const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length; + shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes; + } + + const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred; + const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, "\\".concat(enclosingQuote.quote)); + return concat$7([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]); + } + + function printPath(path, print) { + return path.call(print, "path"); + } + + function printParams(path, print) { + const node = path.getValue(); + let parts = []; + + if (node.params.length > 0) { + parts = parts.concat(path.map(print, "params")); + } + + if (node.hash && node.hash.pairs.length > 0) { + parts.push(path.call(print, "hash")); + } + + return parts; + } + + function printPathParams(path, print) { + const printedPath = printPath(path, print); + const printedParams = printParams(path, print); + const parts = [printedPath, ...printedParams]; + return indent$4(group$6(join$4(line$4, parts))); + } + + function printBlockParams(path) { + const block = path.getValue(); + + if (!block.program || !block.program.blockParams.length) { + return ""; + } + + return concat$7([" as |", block.program.blockParams.join(" "), "|"]); + } + + function printOpenBlock(path, print, { + open: isOpenStrip = false, + close: isCloseStrip = false + } = {}) { + return group$6(concat$7([isOpenStrip ? "{{~#" : "{{#", printPathParams(path, print), printBlockParams(path), softline$3, isCloseStrip ? "~}}" : "}}"])); + } + + function printCloseBlock(path, print, { + open: isOpenStrip = false, + close: isCloseStrip = false + } = {}) { + return concat$7([isOpenStrip ? "{{~/" : "{{/", path.call(print, "path"), isCloseStrip ? "~}}" : "}}"]); + } + + function countNewLines(string) { + /* istanbul ignore next */ + string = typeof string === "string" ? string : ""; + return string.split("\n").length - 1; + } + + function countLeadingNewLines(string) { + /* istanbul ignore next */ + string = typeof string === "string" ? string : ""; + const newLines = (string.match(/^([^\S\r\n]*[\r\n])+/g) || [])[0] || ""; + return countNewLines(newLines); + } + + function countTrailingNewLines(string) { + /* istanbul ignore next */ + string = typeof string === "string" ? string : ""; + const newLines = (string.match(/([\r\n][^\S\r\n]*)+$/g) || [])[0] || ""; + return countNewLines(newLines); + } + + function generateHardlines(number = 0, max = 0) { + return new Array(Math.min(number, max)).fill(hardline$6); + } + /* istanbul ignore next + https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/compiler/lib/location.ts#L5-L29 + */ + + + function locationToOffset(source, line, column) { + let seenLines = 0; + let seenChars = 0; // eslint-disable-next-line no-constant-condition + + while (true) { + if (seenChars === source.length) { + return null; + } + + let nextLine = source.indexOf("\n", seenChars); + + if (nextLine === -1) { + nextLine = source.length; + } + + if (seenLines === line) { + if (seenChars + column > nextLine) { + return null; + } + + return seenChars + column; + } else if (nextLine === -1) { + return null; + } + + seenLines += 1; + seenChars = nextLine + 1; + } + } + + var printerGlimmer = { + print, + massageAstNode: clean$2 + }; + + var name$6 = "Handlebars"; + var type$5 = "markup"; + var group$7 = "HTML"; + var aliases = [ + "hbs", + "htmlbars" + ]; + var extensions$5 = [ + ".handlebars", + ".hbs" + ]; + var tmScope$5 = "text.html.handlebars"; + var aceMode$5 = "handlebars"; + var languageId$5 = 155; + var Handlebars = { + name: name$6, + type: type$5, + group: group$7, + aliases: aliases, + extensions: extensions$5, + tmScope: tmScope$5, + aceMode: aceMode$5, + languageId: languageId$5 + }; + + var Handlebars$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$6, + type: type$5, + group: group$7, + aliases: aliases, + extensions: extensions$5, + tmScope: tmScope$5, + aceMode: aceMode$5, + languageId: languageId$5, + 'default': Handlebars + }); + + var require$$0$4 = getCjsExportFromNamespace(Handlebars$1); + + const languages$2 = [createLanguage(require$$0$4, () => ({ + since: null, + // unreleased + parsers: ["glimmer"], + vscodeLanguageIds: ["handlebars"] + }))]; + const printers$2 = { + glimmer: printerGlimmer + }; + var languageHandlebars = { + languages: languages$2, + printers: printers$2 + }; + + var clean$3 = function clean(ast, newNode) { + delete newNode.sourceSpan; + delete newNode.startSourceSpan; + delete newNode.endSourceSpan; + delete newNode.nameSpan; + delete newNode.valueSpan; + + if (ast.type === "text" || ast.type === "comment") { + return null; + } // may be formatted by multiparser + + + if (ast.type === "yaml" || ast.type === "toml") { + return null; + } + + if (ast.type === "attribute") { + delete newNode.value; + } + + if (ast.type === "docType") { + delete newNode.value; + } + }; + + var json = { + "CSS_DISPLAY_TAGS": { + "area": "none", + "base": "none", + "basefont": "none", + "datalist": "none", + "head": "none", + "link": "none", + "meta": "none", + "noembed": "none", + "noframes": "none", + "param": "none", + "rp": "none", + "script": "block", + "source": "block", + "style": "none", + "template": "inline", + "track": "block", + "title": "none", + "html": "block", + "body": "block", + "address": "block", + "blockquote": "block", + "center": "block", + "div": "block", + "figure": "block", + "figcaption": "block", + "footer": "block", + "form": "block", + "header": "block", + "hr": "block", + "legend": "block", + "listing": "block", + "main": "block", + "p": "block", + "plaintext": "block", + "pre": "block", + "xmp": "block", + "slot": "contents", + "ruby": "ruby", + "rt": "ruby-text", + "article": "block", + "aside": "block", + "h1": "block", + "h2": "block", + "h3": "block", + "h4": "block", + "h5": "block", + "h6": "block", + "hgroup": "block", + "nav": "block", + "section": "block", + "dir": "block", + "dd": "block", + "dl": "block", + "dt": "block", + "ol": "block", + "ul": "block", + "li": "list-item", + "table": "table", + "caption": "table-caption", + "colgroup": "table-column-group", + "col": "table-column", + "thead": "table-header-group", + "tbody": "table-row-group", + "tfoot": "table-footer-group", + "tr": "table-row", + "td": "table-cell", + "th": "table-cell", + "fieldset": "block", + "button": "inline-block", + "video": "inline-block", + "audio": "inline-block" + }, + "CSS_DISPLAY_DEFAULT": "inline", + "CSS_WHITE_SPACE_TAGS": { + "listing": "pre", + "plaintext": "pre", + "pre": "pre", + "xmp": "pre", + "nobr": "nowrap", + "table": "initial", + "textarea": "pre-wrap" + }, + "CSS_WHITE_SPACE_DEFAULT": "normal" + }; + + var index = [ + "a", + "abbr", + "acronym", + "address", + "applet", + "area", + "article", + "aside", + "audio", + "b", + "base", + "basefont", + "bdi", + "bdo", + "bgsound", + "big", + "blink", + "blockquote", + "body", + "br", + "button", + "canvas", + "caption", + "center", + "cite", + "code", + "col", + "colgroup", + "command", + "content", + "data", + "datalist", + "dd", + "del", + "details", + "dfn", + "dialog", + "dir", + "div", + "dl", + "dt", + "element", + "em", + "embed", + "fieldset", + "figcaption", + "figure", + "font", + "footer", + "form", + "frame", + "frameset", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hgroup", + "hr", + "html", + "i", + "iframe", + "image", + "img", + "input", + "ins", + "isindex", + "kbd", + "keygen", + "label", + "legend", + "li", + "link", + "listing", + "main", + "map", + "mark", + "marquee", + "math", + "menu", + "menuitem", + "meta", + "meter", + "multicol", + "nav", + "nextid", + "nobr", + "noembed", + "noframes", + "noscript", + "object", + "ol", + "optgroup", + "option", + "output", + "p", + "param", + "picture", + "plaintext", + "pre", + "progress", + "q", + "rb", + "rbc", + "rp", + "rt", + "rtc", + "ruby", + "s", + "samp", + "script", + "section", + "select", + "shadow", + "slot", + "small", + "source", + "spacer", + "span", + "strike", + "strong", + "style", + "sub", + "summary", + "sup", + "svg", + "table", + "tbody", + "td", + "template", + "textarea", + "tfoot", + "th", + "thead", + "time", + "title", + "tr", + "track", + "tt", + "u", + "ul", + "var", + "video", + "wbr", + "xmp" + ]; + + var htmlTagNames = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': index + }); + + var a = [ + "accesskey", + "charset", + "coords", + "download", + "href", + "hreflang", + "name", + "ping", + "referrerpolicy", + "rel", + "rev", + "shape", + "tabindex", + "target", + "type" + ]; + var abbr = [ + "title" + ]; + var applet = [ + "align", + "alt", + "archive", + "code", + "codebase", + "height", + "hspace", + "name", + "object", + "vspace", + "width" + ]; + var area = [ + "accesskey", + "alt", + "coords", + "download", + "href", + "hreflang", + "nohref", + "ping", + "referrerpolicy", + "rel", + "shape", + "tabindex", + "target", + "type" + ]; + var audio = [ + "autoplay", + "controls", + "crossorigin", + "loop", + "muted", + "preload", + "src" + ]; + var base = [ + "href", + "target" + ]; + var basefont = [ + "color", + "face", + "size" + ]; + var bdo = [ + "dir" + ]; + var blockquote = [ + "cite" + ]; + var body = [ + "alink", + "background", + "bgcolor", + "link", + "text", + "vlink" + ]; + var br = [ + "clear" + ]; + var button = [ + "accesskey", + "autofocus", + "disabled", + "form", + "formaction", + "formenctype", + "formmethod", + "formnovalidate", + "formtarget", + "name", + "tabindex", + "type", + "value" + ]; + var canvas = [ + "height", + "width" + ]; + var caption = [ + "align" + ]; + var col = [ + "align", + "char", + "charoff", + "span", + "valign", + "width" + ]; + var colgroup = [ + "align", + "char", + "charoff", + "span", + "valign", + "width" + ]; + var data = [ + "value" + ]; + var del = [ + "cite", + "datetime" + ]; + var details = [ + "open" + ]; + var dfn = [ + "title" + ]; + var dialog = [ + "open" + ]; + var dir = [ + "compact" + ]; + var div = [ + "align" + ]; + var dl = [ + "compact" + ]; + var embed$1 = [ + "height", + "src", + "type", + "width" + ]; + var fieldset = [ + "disabled", + "form", + "name" + ]; + var font = [ + "color", + "face", + "size" + ]; + var form = [ + "accept", + "accept-charset", + "action", + "autocomplete", + "enctype", + "method", + "name", + "novalidate", + "target" + ]; + var frame = [ + "frameborder", + "longdesc", + "marginheight", + "marginwidth", + "name", + "noresize", + "scrolling", + "src" + ]; + var frameset = [ + "cols", + "rows" + ]; + var h1 = [ + "align" + ]; + var h2 = [ + "align" + ]; + var h3 = [ + "align" + ]; + var h4 = [ + "align" + ]; + var h5 = [ + "align" + ]; + var h6 = [ + "align" + ]; + var head = [ + "profile" + ]; + var hr = [ + "align", + "noshade", + "size", + "width" + ]; + var html = [ + "manifest", + "version" + ]; + var iframe = [ + "align", + "allow", + "allowfullscreen", + "allowpaymentrequest", + "allowusermedia", + "frameborder", + "height", + "longdesc", + "marginheight", + "marginwidth", + "name", + "referrerpolicy", + "sandbox", + "scrolling", + "src", + "srcdoc", + "width" + ]; + var img = [ + "align", + "alt", + "border", + "crossorigin", + "decoding", + "height", + "hspace", + "ismap", + "longdesc", + "name", + "referrerpolicy", + "sizes", + "src", + "srcset", + "usemap", + "vspace", + "width" + ]; + var input = [ + "accept", + "accesskey", + "align", + "alt", + "autocomplete", + "autofocus", + "checked", + "dirname", + "disabled", + "form", + "formaction", + "formenctype", + "formmethod", + "formnovalidate", + "formtarget", + "height", + "ismap", + "list", + "max", + "maxlength", + "min", + "minlength", + "multiple", + "name", + "pattern", + "placeholder", + "readonly", + "required", + "size", + "src", + "step", + "tabindex", + "title", + "type", + "usemap", + "value", + "width" + ]; + var ins = [ + "cite", + "datetime" + ]; + var isindex = [ + "prompt" + ]; + var label = [ + "accesskey", + "for", + "form" + ]; + var legend = [ + "accesskey", + "align" + ]; + var li = [ + "type", + "value" + ]; + var link$3 = [ + "as", + "charset", + "color", + "crossorigin", + "href", + "hreflang", + "imagesizes", + "imagesrcset", + "integrity", + "media", + "nonce", + "referrerpolicy", + "rel", + "rev", + "sizes", + "target", + "title", + "type" + ]; + var map = [ + "name" + ]; + var menu = [ + "compact" + ]; + var meta = [ + "charset", + "content", + "http-equiv", + "name", + "scheme" + ]; + var meter = [ + "high", + "low", + "max", + "min", + "optimum", + "value" + ]; + var object = [ + "align", + "archive", + "border", + "classid", + "codebase", + "codetype", + "data", + "declare", + "form", + "height", + "hspace", + "name", + "standby", + "tabindex", + "type", + "typemustmatch", + "usemap", + "vspace", + "width" + ]; + var ol = [ + "compact", + "reversed", + "start", + "type" + ]; + var optgroup = [ + "disabled", + "label" + ]; + var option = [ + "disabled", + "label", + "selected", + "value" + ]; + var output = [ + "for", + "form", + "name" + ]; + var p = [ + "align" + ]; + var param = [ + "name", + "type", + "value", + "valuetype" + ]; + var pre = [ + "width" + ]; + var progress = [ + "max", + "value" + ]; + var q = [ + "cite" + ]; + var script = [ + "async", + "charset", + "crossorigin", + "defer", + "integrity", + "language", + "nomodule", + "nonce", + "referrerpolicy", + "src", + "type" + ]; + var select = [ + "autocomplete", + "autofocus", + "disabled", + "form", + "multiple", + "name", + "required", + "size", + "tabindex" + ]; + var slot = [ + "name" + ]; + var source$1 = [ + "media", + "sizes", + "src", + "srcset", + "type" + ]; + var style = [ + "media", + "nonce", + "title", + "type" + ]; + var table = [ + "align", + "bgcolor", + "border", + "cellpadding", + "cellspacing", + "frame", + "rules", + "summary", + "width" + ]; + var tbody = [ + "align", + "char", + "charoff", + "valign" + ]; + var td = [ + "abbr", + "align", + "axis", + "bgcolor", + "char", + "charoff", + "colspan", + "headers", + "height", + "nowrap", + "rowspan", + "scope", + "valign", + "width" + ]; + var textarea = [ + "accesskey", + "autocomplete", + "autofocus", + "cols", + "dirname", + "disabled", + "form", + "maxlength", + "minlength", + "name", + "placeholder", + "readonly", + "required", + "rows", + "tabindex", + "wrap" + ]; + var tfoot = [ + "align", + "char", + "charoff", + "valign" + ]; + var th = [ + "abbr", + "align", + "axis", + "bgcolor", + "char", + "charoff", + "colspan", + "headers", + "height", + "nowrap", + "rowspan", + "scope", + "valign", + "width" + ]; + var thead = [ + "align", + "char", + "charoff", + "valign" + ]; + var time = [ + "datetime" + ]; + var tr = [ + "align", + "bgcolor", + "char", + "charoff", + "valign" + ]; + var track = [ + "default", + "kind", + "label", + "src", + "srclang" + ]; + var ul = [ + "compact", + "type" + ]; + var video = [ + "autoplay", + "controls", + "crossorigin", + "height", + "loop", + "muted", + "playsinline", + "poster", + "preload", + "src", + "width" + ]; + var index$1 = { + "*": [ + "accesskey", + "autocapitalize", + "autofocus", + "class", + "contenteditable", + "dir", + "draggable", + "enterkeyhint", + "hidden", + "id", + "inputmode", + "is", + "itemid", + "itemprop", + "itemref", + "itemscope", + "itemtype", + "lang", + "nonce", + "slot", + "spellcheck", + "style", + "tabindex", + "title", + "translate" + ], + a: a, + abbr: abbr, + applet: applet, + area: area, + audio: audio, + base: base, + basefont: basefont, + bdo: bdo, + blockquote: blockquote, + body: body, + br: br, + button: button, + canvas: canvas, + caption: caption, + col: col, + colgroup: colgroup, + data: data, + del: del, + details: details, + dfn: dfn, + dialog: dialog, + dir: dir, + div: div, + dl: dl, + embed: embed$1, + fieldset: fieldset, + font: font, + form: form, + frame: frame, + frameset: frameset, + h1: h1, + h2: h2, + h3: h3, + h4: h4, + h5: h5, + h6: h6, + head: head, + hr: hr, + html: html, + iframe: iframe, + img: img, + input: input, + ins: ins, + isindex: isindex, + label: label, + legend: legend, + li: li, + link: link$3, + map: map, + menu: menu, + meta: meta, + meter: meter, + object: object, + ol: ol, + optgroup: optgroup, + option: option, + output: output, + p: p, + param: param, + pre: pre, + progress: progress, + q: q, + script: script, + select: select, + slot: slot, + source: source$1, + style: style, + table: table, + tbody: tbody, + td: td, + textarea: textarea, + tfoot: tfoot, + th: th, + thead: thead, + time: time, + tr: tr, + track: track, + ul: ul, + video: video + }; + + var htmlElementAttributes = /*#__PURE__*/Object.freeze({ + __proto__: null, + a: a, + abbr: abbr, + applet: applet, + area: area, + audio: audio, + base: base, + basefont: basefont, + bdo: bdo, + blockquote: blockquote, + body: body, + br: br, + button: button, + canvas: canvas, + caption: caption, + col: col, + colgroup: colgroup, + data: data, + del: del, + details: details, + dfn: dfn, + dialog: dialog, + dir: dir, + div: div, + dl: dl, + embed: embed$1, + fieldset: fieldset, + font: font, + form: form, + frame: frame, + frameset: frameset, + h1: h1, + h2: h2, + h3: h3, + h4: h4, + h5: h5, + h6: h6, + head: head, + hr: hr, + html: html, + iframe: iframe, + img: img, + input: input, + ins: ins, + isindex: isindex, + label: label, + legend: legend, + li: li, + link: link$3, + map: map, + menu: menu, + meta: meta, + meter: meter, + object: object, + ol: ol, + optgroup: optgroup, + option: option, + output: output, + p: p, + param: param, + pre: pre, + progress: progress, + q: q, + script: script, + select: select, + slot: slot, + source: source$1, + style: style, + table: table, + tbody: tbody, + td: td, + textarea: textarea, + tfoot: tfoot, + th: th, + thead: thead, + time: time, + tr: tr, + track: track, + ul: ul, + video: video, + 'default': index$1 + }); + + var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames); + + var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes); + + const { + CSS_DISPLAY_TAGS, + CSS_DISPLAY_DEFAULT, + CSS_WHITE_SPACE_TAGS, + CSS_WHITE_SPACE_DEFAULT + } = json; + const HTML_TAGS = arrayToMap(htmlTagNames$1); + const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap); + + function arrayToMap(array) { + const map = Object.create(null); + + for (const value of array) { + map[value] = true; + } + + return map; + } + + function mapObject(object, fn) { + const newObject = Object.create(null); + + for (const key of Object.keys(object)) { + newObject[key] = fn(object[key], key); + } + + return newObject; + } + + function shouldPreserveContent(node, options) { + if (!node.endSourceSpan) { + return false; + } + + if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") { + return true; + } // unterminated node in ie conditional comment + // e.g. <!--[if lt IE 9]><html><![endif]--> + + + if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) { + return true; + } // incomplete html in ie conditional comment + // e.g. <!--[if lt IE 9]></div><![endif]--> + + + if (node.type === "ieConditionalComment" && !node.complete) { + return true; + } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block + // custom blocks can be written in other languages so we should preserve them to not break the code + + + if (options.parser === "vue" && node.type === "element" && node.parent.type === "root" && !["template", "style", "script", // vue parser can be used for vue dom template as well, so we should still format top-level <html> + "html"].includes(node.fullName)) { + return true; + } // TODO: handle non-text children in <pre> + + + if (isPreLikeNode(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) { + return true; + } + + return false; + } + + function hasPrettierIgnore$2(node) { + if (node.type === "attribute") { + return false; + } + + if (!node.parent) { + return false; + } + + if (typeof node.index !== "number" || node.index === 0) { + return false; + } + + const prevNode = node.parent.children[node.index - 1]; + return isPrettierIgnore(prevNode); + } + + function isPrettierIgnore(node) { + return node.type === "comment" && node.value.trim() === "prettier-ignore"; + } + + function getPrettierIgnoreAttributeCommentData(value) { + const match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/); + + if (!match) { + return false; + } + + if (!match[1]) { + return true; + } + + return match[1].split(/\s+/); + } + /** there's no opening/closing tag or it's considered not breakable */ + + + function isTextLikeNode(node) { + return node.type === "text" || node.type === "comment"; + } + + function isScriptLikeTag(node) { + return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style")); + } + + function isFrontMatterNode(node) { + return node.type === "yaml" || node.type === "toml"; + } + + function canHaveInterpolation(node) { + return node.children && !isScriptLikeTag(node); + } + + function isWhitespaceSensitiveNode(node) { + return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node); + } + + function isIndentationSensitiveNode(node) { + return getNodeCssStyleWhiteSpace(node).startsWith("pre"); + } + + function isLeadingSpaceSensitiveNode(node) { + const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode(); + + if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) { + return node.type === "interpolation"; + } + + return isLeadingSpaceSensitive; + + function _isLeadingSpaceSensitiveNode() { + if (isFrontMatterNode(node)) { + return false; + } + + if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) { + return true; + } + + if (!node.parent || node.parent.cssDisplay === "none") { + return false; + } + + if (isPreLikeNode(node.parent)) { + return true; + } + + if (!node.prev && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) { + return false; + } + + if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) { + return false; + } + + return true; + } + } + + function isTrailingSpaceSensitiveNode(node) { + if (isFrontMatterNode(node)) { + return false; + } + + if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) { + return true; + } + + if (!node.parent || node.parent.cssDisplay === "none") { + return false; + } + + if (isPreLikeNode(node.parent)) { + return true; + } + + if (!node.next && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) { + return false; + } + + if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) { + return false; + } + + return true; + } + + function isDanglingSpaceSensitiveNode(node) { + return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node); + } + + function forceNextEmptyLine(node) { + return isFrontMatterNode(node) || node.next && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line; + } + /** firstChild leadingSpaces and lastChild trailingSpaces */ + + + function forceBreakContent(node) { + return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild)); + } + /** spaces between children */ + + + function forceBreakChildren(node) { + return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell"); + } + + function preferHardlineAsLeadingSpaces(node) { + return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node); + } + + function preferHardlineAsTrailingSpaces(node) { + return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node); + } + + function hasSurroundingLineBreak(node) { + return hasLeadingLineBreak(node) && hasTrailingLineBreak(node); + } + + function hasLeadingLineBreak(node) { + return node.hasLeadingSpaces && (node.prev ? node.prev.sourceSpan.end.line < node.sourceSpan.start.line : node.parent.type === "root" || node.parent.startSourceSpan.end.line < node.sourceSpan.start.line); + } + + function hasTrailingLineBreak(node) { + return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan && node.parent.endSourceSpan.start.line > node.sourceSpan.end.line); + } + + function preferHardlineAsSurroundingSpaces(node) { + switch (node.type) { + case "ieConditionalComment": + case "comment": + case "directive": + return true; + + case "element": + return ["script", "select"].includes(node.name); + } + + return false; + } + + function getLastDescendant(node) { + return node.lastChild ? getLastDescendant(node.lastChild) : node; + } + + function hasNonTextChild(node) { + return node.children && node.children.some(child => child.type !== "text"); + } + + function inferScriptParser(node) { + if (node.name === "script" && !node.attrMap.src) { + if (!node.attrMap.lang && !node.attrMap.type || node.attrMap.type === "module" || node.attrMap.type === "text/javascript" || node.attrMap.type === "text/babel" || node.attrMap.type === "application/javascript" || node.attrMap.lang === "jsx") { + return "babel"; + } + + if (node.attrMap.type === "application/x-typescript" || node.attrMap.lang === "ts" || node.attrMap.lang === "tsx") { + return "typescript"; + } + + if (node.attrMap.type === "text/markdown") { + return "markdown"; + } + + if (node.attrMap.type.endsWith("json") || node.attrMap.type.endsWith("importmap")) { + return "json"; + } + + if (node.attrMap.type === "text/x-handlebars-template") { + return "glimmer"; + } + } + + if (node.name === "style") { + if (!node.attrMap.lang || node.attrMap.lang === "postcss" || node.attrMap.lang === "css") { + return "css"; + } + + if (node.attrMap.lang === "scss") { + return "scss"; + } + + if (node.attrMap.lang === "less") { + return "less"; + } + } + + return null; + } + + function isBlockLikeCssDisplay(cssDisplay) { + return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table"); + } + + function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) { + return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block"; + } + + function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) { + return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block"; + } + + function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) { + return !isBlockLikeCssDisplay(cssDisplay); + } + + function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) { + return !isBlockLikeCssDisplay(cssDisplay); + } + + function isDanglingSpaceSensitiveCssDisplay(cssDisplay) { + return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block"; + } + + function isPreLikeNode(node) { + return getNodeCssStyleWhiteSpace(node).startsWith("pre"); + } + + function countParents(path, predicate = () => true) { + let counter = 0; + + for (let i = path.stack.length - 1; i >= 0; i--) { + const value = path.stack[i]; + + if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) { + counter++; + } + } + + return counter; + } + + function hasParent(node, fn) { + let current = node; + + while (current) { + if (fn(current)) { + return true; + } + + current = current.parent; + } + + return false; + } + + function getNodeCssStyleDisplay(node, options) { + if (node.prev && node.prev.type === "comment") { + // <!-- display: block --> + const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/); + + if (match) { + return match[1]; + } + } + + let isInSvgForeignObject = false; + + if (node.type === "element" && node.namespace === "svg") { + if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) { + isInSvgForeignObject = true; + } else { + return node.name === "svg" ? "inline-block" : "block"; + } + } + + switch (options.htmlWhitespaceSensitivity) { + case "strict": + return "inline"; + + case "ignore": + return "block"; + + default: + return node.type === "element" && (!node.namespace || isInSvgForeignObject || isUnknownNamespace(node)) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT; + } + } + + function isUnknownNamespace(node) { + return node.type === "element" && !node.hasExplicitNamespace && !["html", "svg"].includes(node.namespace); + } + + function getNodeCssStyleWhiteSpace(node) { + return node.type === "element" && (!node.namespace || isUnknownNamespace(node)) && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT; + } + + function getMinIndentation(text) { + let minIndentation = Infinity; + + for (const lineText of text.split("\n")) { + if (lineText.length === 0) { + continue; + } + + if (/\S/.test(lineText[0])) { + return 0; + } + + const indentation = lineText.match(/^\s*/)[0].length; + + if (lineText.length === indentation) { + continue; + } + + if (indentation < minIndentation) { + minIndentation = indentation; + } + } + + return minIndentation === Infinity ? 0 : minIndentation; + } + + function dedentString(text, minIndent = getMinIndentation(text)) { + return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n"); + } + + function normalizeParts(parts) { + const newParts = []; + const restParts = parts.slice(); + + while (restParts.length !== 0) { + const part = restParts.shift(); + + if (!part) { + continue; + } + + if (part.type === "concat") { + restParts.unshift(...part.parts); + continue; + } + + if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") { + newParts.push(newParts.pop() + part); + continue; + } + + newParts.push(part); + } + + return newParts; + } + + function identity(x) { + return x; + } + + function shouldNotPrintClosingTag(node, options) { + return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$2(node) || shouldPreserveContent(node.parent, options)); + } + + function countChars(text, char) { + let counter = 0; + + for (let i = 0; i < text.length; i++) { + if (text[i] === char) { + counter++; + } + } + + return counter; + } + + function unescapeQuoteEntities(text) { + return text.replace(/'/g, "'").replace(/"/g, '"'); + } + + var utils$4 = { + HTML_ELEMENT_ATTRIBUTES, + HTML_TAGS, + canHaveInterpolation, + countChars, + countParents, + dedentString, + forceBreakChildren, + forceBreakContent, + forceNextEmptyLine, + getLastDescendant, + getNodeCssStyleDisplay, + getNodeCssStyleWhiteSpace, + getPrettierIgnoreAttributeCommentData, + hasPrettierIgnore: hasPrettierIgnore$2, + identity, + inferScriptParser, + isDanglingSpaceSensitiveNode, + isFrontMatterNode, + isIndentationSensitiveNode, + isLeadingSpaceSensitiveNode, + isPreLikeNode, + isScriptLikeTag, + isTextLikeNode, + isTrailingSpaceSensitiveNode, + isWhitespaceSensitiveNode, + isUnknownNamespace, + normalizeParts, + preferHardlineAsLeadingSpaces, + preferHardlineAsTrailingSpaces, + shouldNotPrintClosingTag, + shouldPreserveContent, + unescapeQuoteEntities + }; + + const { + canHaveInterpolation: canHaveInterpolation$1, + getNodeCssStyleDisplay: getNodeCssStyleDisplay$1, + isDanglingSpaceSensitiveNode: isDanglingSpaceSensitiveNode$1, + isIndentationSensitiveNode: isIndentationSensitiveNode$1, + isLeadingSpaceSensitiveNode: isLeadingSpaceSensitiveNode$1, + isTrailingSpaceSensitiveNode: isTrailingSpaceSensitiveNode$1, + isWhitespaceSensitiveNode: isWhitespaceSensitiveNode$1 + } = utils$4; + const PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText]; + + function preprocess(ast, options) { + for (const fn of PREPROCESS_PIPELINE) { + ast = fn(ast, options); + } + + return ast; + } + + function removeIgnorableFirstLf(ast + /*, options */ + ) { + return ast.map(node => { + if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") { + const [text, ...rest] = node.children; + return node.clone({ + children: text.value.length === 1 ? rest : [text.clone({ + value: text.value.slice(1) + }), ...rest] + }); + } + + return node; + }); + } + + function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast + /*, options */ + ) { + /** + * <!--[if ...]><!--><target><!--<![endif]--> + */ + const isTarget = node => node.type === "element" && node.prev && node.prev.type === "ieConditionalStartComment" && node.prev.sourceSpan.end.offset === node.startSourceSpan.start.offset && node.firstChild && node.firstChild.type === "ieConditionalEndComment" && node.firstChild.sourceSpan.start.offset === node.startSourceSpan.end.offset; + + return ast.map(node => { + if (node.children) { + const isTargetResults = node.children.map(isTarget); + + if (isTargetResults.some(Boolean)) { + const newChildren = []; + + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + + if (isTargetResults[i + 1]) { + // ieConditionalStartComment + continue; + } + + if (isTargetResults[i]) { + const ieConditionalStartComment = child.prev; + const ieConditionalEndComment = child.firstChild; + const ParseSourceSpan = child.sourceSpan.constructor; + const startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end); + const sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end); + newChildren.push(child.clone({ + condition: ieConditionalStartComment.condition, + sourceSpan, + startSourceSpan, + children: child.children.slice(1) + })); + continue; + } + + newChildren.push(child); + } + + return node.clone({ + children: newChildren + }); + } + } + + return node; + }); + } + + function mergeNodeIntoText(ast, shouldMerge, getValue) { + return ast.map(node => { + if (node.children) { + const shouldMergeResults = node.children.map(shouldMerge); + + if (shouldMergeResults.some(Boolean)) { + const newChildren = []; + + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + + if (child.type !== "text" && !shouldMergeResults[i]) { + newChildren.push(child); + continue; + } + + const newChild = child.type === "text" ? child : child.clone({ + type: "text", + value: getValue(child) + }); + + if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") { + newChildren.push(newChild); + continue; + } + + const lastChild = newChildren.pop(); + const ParseSourceSpan = lastChild.sourceSpan.constructor; + newChildren.push(lastChild.clone({ + value: lastChild.value + newChild.value, + sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end) + })); + } + + return node.clone({ + children: newChildren + }); + } + } + + return node; + }); + } + + function mergeCdataIntoText(ast + /*, options */ + ) { + return mergeNodeIntoText(ast, node => node.type === "cdata", node => "<![CDATA[".concat(node.value, "]]>")); + } + + function mergeSimpleElementIntoText(ast + /*, options */ + ) { + const isSimpleElement = node => node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && // \xA0: non-breaking whitespace + !/[^\S\xA0]/.test(node.children[0].value) && !node.firstChild.hasLeadingSpaces && !node.firstChild.hasTrailingSpaces && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces && node.prev && node.prev.type === "text" && node.next && node.next.type === "text"; + + return ast.map(node => { + if (node.children) { + const isSimpleElementResults = node.children.map(isSimpleElement); + + if (isSimpleElementResults.some(Boolean)) { + const newChildren = []; + + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + + if (isSimpleElementResults[i]) { + const lastChild = newChildren.pop(); + const nextChild = node.children[++i]; + const ParseSourceSpan = node.sourceSpan.constructor; + const { + isTrailingSpaceSensitive, + hasTrailingSpaces + } = nextChild; + newChildren.push(lastChild.clone({ + value: lastChild.value + "<".concat(child.rawName, ">") + child.firstChild.value + "</".concat(child.rawName, ">") + nextChild.value, + sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end), + isTrailingSpaceSensitive, + hasTrailingSpaces + })); + } else { + newChildren.push(child); + } + } + + return node.clone({ + children: newChildren + }); + } + } + + return node; + }); + } + + function extractInterpolation(ast, options) { + if (options.parser === "html") { + return ast; + } + + const interpolationRegex = /\{\{([\s\S]+?)\}\}/g; + return ast.map(node => { + if (!canHaveInterpolation$1(node)) { + return node; + } + + const newChildren = []; + + for (const child of node.children) { + if (child.type !== "text") { + newChildren.push(child); + continue; + } + + const ParseSourceSpan = child.sourceSpan.constructor; + let startSourceSpan = child.sourceSpan.start; + let endSourceSpan = null; + const components = child.value.split(interpolationRegex); + + for (let i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) { + const value = components[i]; + + if (i % 2 === 0) { + endSourceSpan = startSourceSpan.moveBy(value.length); + + if (value.length !== 0) { + newChildren.push({ + type: "text", + value, + sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan) + }); + } + + continue; + } + + endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}` + + newChildren.push({ + type: "interpolation", + sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan), + children: value.length === 0 ? [] : [{ + type: "text", + value, + sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2)) + }] + }); + } + } + + return node.clone({ + children: newChildren + }); + }); + } + /** + * - add `hasLeadingSpaces` field + * - add `hasTrailingSpaces` field + * - add `hasDanglingSpaces` field for parent nodes + * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes + * - remove insensitive whitespaces + */ + + + function extractWhitespaces(ast + /*, options*/ + ) { + const TYPE_WHITESPACE = "whitespace"; + return ast.map(node => { + if (!node.children) { + return node; + } + + if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && node.children[0].value.trim().length === 0) { + return node.clone({ + children: [], + hasDanglingSpaces: node.children.length !== 0 + }); + } + + const isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node); + const isIndentationSensitive = isIndentationSensitiveNode$1(node); + return node.clone({ + isWhitespaceSensitive, + isIndentationSensitive, + children: node.children // extract whitespace nodes + .reduce((newChildren, child) => { + if (child.type !== "text" || isWhitespaceSensitive) { + return newChildren.concat(child); + } + + const localChildren = []; + const [, leadingSpaces, text, trailingSpaces] = child.value.match(/^(\s*)([\s\S]*?)(\s*)$/); + + if (leadingSpaces) { + localChildren.push({ + type: TYPE_WHITESPACE + }); + } + + const ParseSourceSpan = child.sourceSpan.constructor; + + if (text) { + localChildren.push({ + type: "text", + value: text, + sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingSpaces.length), child.sourceSpan.end.moveBy(-trailingSpaces.length)) + }); + } + + if (trailingSpaces) { + localChildren.push({ + type: TYPE_WHITESPACE + }); + } + + return newChildren.concat(localChildren); + }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes + .reduce((newChildren, child, i, children) => { + if (child.type === TYPE_WHITESPACE) { + return newChildren; + } + + const hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE; + const hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE; + return newChildren.concat(Object.assign({}, child, { + hasLeadingSpaces, + hasTrailingSpaces + })); + }, []) + }); + }); + } + + function addIsSelfClosing(ast + /*, options */ + ) { + return ast.map(node => Object.assign(node, { + isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing + node.startSourceSpan === node.endSourceSpan) + })); + } + + function addHasHtmComponentClosingTag(ast, options) { + return ast.map(node => node.type !== "element" ? node : Object.assign(node, { + hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset)) + })); + } + + function addCssDisplay(ast, options) { + return ast.map(node => Object.assign(node, { + cssDisplay: getNodeCssStyleDisplay$1(node, options) + })); + } + /** + * - add `isLeadingSpaceSensitive` field + * - add `isTrailingSpaceSensitive` field + * - add `isDanglingSpaceSensitive` field for parent nodes + */ + + + function addIsSpaceSensitive(ast + /*, options */ + ) { + return ast.map(node => { + if (!node.children) { + return node; + } + + if (node.children.length === 0) { + return node.clone({ + isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node) + }); + } + + return node.clone({ + children: node.children.map(child => { + return Object.assign({}, child, { + isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child), + isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child) + }); + }).map((child, index, children) => Object.assign({}, child, { + isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive, + isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive + })) + }); + }); + } + + var preprocess_1 = preprocess; + + function hasPragma$3(text) { + return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text); + } + + function insertPragma$5(text) { + return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, ""); + } + + var pragma$3 = { + hasPragma: hasPragma$3, + insertPragma: insertPragma$5 + }; + + const { + builders: { + concat: concat$8, + group: group$8 + } + } = document; + /** + * v-for="... in ..." + * v-for="... of ..." + * v-for="(..., ...) in ..." + * v-for="(..., ...) of ..." + */ + + function printVueFor(value, textToDoc) { + const { + left, + operator, + right + } = parseVueFor(value); + return concat$8([group$8(textToDoc("function _(".concat(left, ") {}"), { + parser: "babel", + __isVueForBindingLeft: true + })), " ", operator, " ", textToDoc(right, { + parser: "__js_expression" + })]); + } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387 + + + function parseVueFor(value) { + const forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/; + const forIteratorRE = /,([^,}\]]*)(?:,([^,}\]]*))?$/; + const stripParensRE = /^\(|\)$/g; + const inMatch = value.match(forAliasRE); + + if (!inMatch) { + return; + } + + const res = {}; + res.for = inMatch[3].trim(); + const alias = inMatch[1].trim().replace(stripParensRE, ""); + const iteratorMatch = alias.match(forIteratorRE); + + if (iteratorMatch) { + res.alias = alias.replace(forIteratorRE, ""); + res.iterator1 = iteratorMatch[1].trim(); + + if (iteratorMatch[2]) { + res.iterator2 = iteratorMatch[2].trim(); + } + } else { + res.alias = alias; + } + + return { + left: "".concat([res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")), + operator: inMatch[2], + right: res.for + }; + } + + function printVueSlotScope(value, textToDoc) { + return textToDoc("function _(".concat(value, ") {}"), { + parser: "babel", + __isVueSlotScope: true + }); + } + + function isVueEventBindingExpression(eventBindingValue) { + // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4 + // arrow function or anonymous function + const fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b]) + + const simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/helpers.js#L104 + + const value = eventBindingValue.trim(); + return fnExpRE.test(value) || simplePathRE.test(value); + } + + var syntaxVue = { + isVueEventBindingExpression, + printVueFor, + printVueSlotScope + }; + + const integerRegex = /^\d+$/; + + function deepUnique(array) { + return array.sort().filter((element, index) => { + return JSON.stringify(element) !== JSON.stringify(array[index - 1]); + }); + } + + var parse$2 = string => { + return deepUnique(string.split(',').map(part => { + const result = {}; + part.trim().split(/\s+/).forEach((element, index) => { + if (index === 0) { + result.url = element; + return; + } + + const value = element.slice(0, element.length - 1); + const postfix = element[element.length - 1]; + const integerValue = parseInt(value, 10); + const floatValue = parseFloat(value); + + if (postfix === 'w' && integerRegex.test(value)) { + result.width = integerValue; + } else if (postfix === 'h' && integerRegex.test(value)) { + result.height = integerValue; + } else if (postfix === 'x' && !Number.isNaN(floatValue)) { + result.density = floatValue; + } else { + throw new Error("Invalid srcset descriptor: ".concat(element)); + } + }); + return result; + })); + }; + + var stringify = array => { + return [...new Set(array.map(element => { + if (!element.url) { + throw new Error('URL is required'); + } + + const result = [element.url]; + + if (element.width) { + result.push("".concat(element.width, "w")); + } + + if (element.height) { + result.push("".concat(element.height, "h")); + } + + if (element.density) { + result.push("".concat(element.density, "x")); + } + + return result.join(' '); + }))].join(', '); + }; + + var srcset = { + parse: parse$2, + stringify: stringify + }; + + const { + builders: { + concat: concat$9, + ifBreak: ifBreak$4, + join: join$5, + line: line$5 + } + } = document; + const parseSrcset = srcset.parse; + + function printImgSrcset(value) { + const srcset = parseSrcset(value); + const hasW = srcset.some(src => src.width); + const hasH = srcset.some(src => src.height); + const hasX = srcset.some(src => src.density); + + if (hasW + hasH + hasX > 1) { + throw new Error("Mixed descriptor in srcset is not supported"); + } + + const key = hasW ? "width" : hasH ? "height" : "density"; + const unit = hasW ? "w" : hasH ? "h" : "x"; + + const getMax = values => Math.max(...values); + + const urls = srcset.map(src => src.url); + const maxUrlLength = getMax(urls.map(url => url.length)); + const descriptors = srcset.map(src => src[key]).map(descriptor => descriptor ? descriptor.toString() : ""); + const descriptorLeftLengths = descriptors.map(descriptor => { + const index = descriptor.indexOf("."); + return index === -1 ? descriptor.length : index; + }); + const maxDescriptorLeftLength = getMax(descriptorLeftLengths); + return join$5(concat$9([",", line$5]), urls.map((url, index) => { + const parts = [url]; + const descriptor = descriptors[index]; + + if (descriptor) { + const urlPadding = maxUrlLength - url.length + 1; + const descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index]; + const alignment = " ".repeat(urlPadding + descriptorPadding); + parts.push(ifBreak$4(alignment, " "), descriptor + unit); + } + + return concat$9(parts); + })); + } + + function printClassNames(value) { + return value.trim().split(/\s+/).join(" "); + } + + var syntaxAttribute = { + printImgSrcset, + printClassNames + }; + + const { + builders, + utils: { + stripTrailingHardline: stripTrailingHardline$1, + mapDoc: mapDoc$2 + } + } = document; + const { + breakParent: breakParent$2, + dedentToRoot: dedentToRoot$1, + fill: fill$3, + group: group$9, + hardline: hardline$7, + ifBreak: ifBreak$5, + indent: indent$5, + join: join$6, + line: line$6, + literalline: literalline$2, + markAsRoot: markAsRoot$2, + softline: softline$4 + } = builders; + const { + countChars: countChars$1, + countParents: countParents$1, + dedentString: dedentString$1, + forceBreakChildren: forceBreakChildren$1, + forceBreakContent: forceBreakContent$1, + forceNextEmptyLine: forceNextEmptyLine$1, + getLastDescendant: getLastDescendant$1, + getPrettierIgnoreAttributeCommentData: getPrettierIgnoreAttributeCommentData$1, + hasPrettierIgnore: hasPrettierIgnore$3, + inferScriptParser: inferScriptParser$1, + isScriptLikeTag: isScriptLikeTag$1, + isTextLikeNode: isTextLikeNode$1, + normalizeParts: normalizeParts$1, + preferHardlineAsLeadingSpaces: preferHardlineAsLeadingSpaces$1, + shouldNotPrintClosingTag: shouldNotPrintClosingTag$1, + shouldPreserveContent: shouldPreserveContent$1, + unescapeQuoteEntities: unescapeQuoteEntities$1 + } = utils$4; + const { + replaceEndOfLineWith: replaceEndOfLineWith$1 + } = util$1; + const { + insertPragma: insertPragma$6 + } = pragma$3; + const { + printVueFor: printVueFor$1, + printVueSlotScope: printVueSlotScope$1, + isVueEventBindingExpression: isVueEventBindingExpression$1 + } = syntaxVue; + const { + printImgSrcset: printImgSrcset$1, + printClassNames: printClassNames$1 + } = syntaxAttribute; + + function concat$a(parts) { + const newParts = normalizeParts$1(parts); + return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts); + } + + function embed$2(path, print, textToDoc, options) { + const node = path.getValue(); + + switch (node.type) { + case "text": + { + if (isScriptLikeTag$1(node.parent)) { + const parser = inferScriptParser$1(node.parent); + + if (parser) { + const value = parser === "markdown" ? dedentString$1(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value; + return builders.concat([concat$a([breakParent$2, printOpeningTagPrefix(node, options), stripTrailingHardline$1(textToDoc(value, { + parser + })), printClosingTagSuffix(node, options)])]); + } + } else if (node.parent.type === "interpolation") { + return concat$a([indent$5(concat$a([line$6, textToDoc(node.value, Object.assign({ + __isInHtmlInterpolation: true + }, options.parser === "angular" ? { + parser: "__ng_interpolation", + trailingComma: "none" + } : options.parser === "vue" ? { + parser: "__vue_expression" + } : { + parser: "__js_expression" + }))])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$6]); + } + + break; + } + + case "attribute": + { + if (!node.value) { + break; + } // lit-html: html`<my-element obj=${obj}></my-element>` + + + if (/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) { + return concat$a([node.rawName, "=", node.value]); + } // lwc: html`<my-element data-for={value}></my-element>` + + + if (options.parser === "lwc") { + const interpolationRegex = /^\{[\s\S]*\}$/; + + if (interpolationRegex.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) { + return concat$a([node.rawName, "=", node.value]); + } + } + + const embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, (code, opts) => // strictly prefer single quote to avoid unnecessary html entity escape + textToDoc(code, Object.assign({ + __isInHtmlAttribute: true + }, opts)), options); + + if (embeddedAttributeValueDoc) { + return concat$a([node.rawName, '="', group$9(mapDoc$2(embeddedAttributeValueDoc, doc => typeof doc === "string" ? doc.replace(/"/g, """) : doc)), '"']); + } + + break; + } + + case "yaml": + return markAsRoot$2(concat$a(["---", hardline$7, node.value.trim().length === 0 ? "" : textToDoc(node.value, { + parser: "yaml" + }), "---"])); + } + } + + function genericPrint$2(path, options, print) { + const node = path.getValue(); + + switch (node.type) { + case "root": + if (options.__onHtmlRoot) { + options.__onHtmlRoot(node); + } // use original concat to not break stripTrailingHardline + + + return builders.concat([group$9(printChildren$1(path, options, print)), hardline$7]); + + case "element": + case "ieConditionalComment": + { + /** + * do not break: + * + * <div>{{ + * ~ + * interpolation + * }}</div> + * ~ + * + * exception: break if the opening tag breaks + * + * <div + * long + * ~ + * >{{ + * interpolation + * }}</div + * ~ + * > + */ + const shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces; + const attrGroupId = Symbol("element-attr-group-id"); + return concat$a([group$9(concat$a([group$9(printOpeningTag(path, options, print), { + id: attrGroupId + }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$6 : "" : concat$a([forceBreakContent$1(node) ? breakParent$2 : "", (childrenDoc => shouldHugContent ? ifBreak$5(indent$5(childrenDoc), childrenDoc, { + groupId: attrGroupId + }) : isScriptLikeTag$1(node) && node.parent.type === "root" && options.parser === "vue" && !options.vueIndentScriptAndStyle ? childrenDoc : indent$5(childrenDoc))(concat$a([shouldHugContent ? ifBreak$5(softline$4, "", { + groupId: attrGroupId + }) : node.firstChild.hasLeadingSpaces && node.firstChild.isLeadingSpaceSensitive ? line$6 : node.firstChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive ? dedentToRoot$1(softline$4) : softline$4, printChildren$1(path, options, print)])), (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " : "" : shouldHugContent ? ifBreak$5(softline$4, "", { + groupId: attrGroupId + }) : node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? line$6 : (node.lastChild.type === "comment" || node.lastChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive) && new RegExp("\\n\\s{".concat(options.tabWidth * countParents$1(path, n => n.parent && n.parent.type !== "root"), "}$")).test(node.lastChild.value) ? + /** + * <div> + * <pre> + * something + * </pre> + * ~ + * </div> + */ + "" : softline$4])])), printClosingTag(node, options)]); + } + + case "ieConditionalStartComment": + case "ieConditionalEndComment": + return concat$a([printOpeningTagStart(node), printClosingTagEnd(node)]); + + case "interpolation": + return concat$a([printOpeningTagStart(node, options), concat$a(path.map(print, "children")), printClosingTagEnd(node, options)]); + + case "text": + { + if (node.parent.type === "interpolation") { + // replace the trailing literalline with hardline for better readability + const trailingNewlineRegex = /\n[^\S\n]*?$/; + const hasTrailingNewline = trailingNewlineRegex.test(node.value); + const value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value; + return concat$a([concat$a(replaceEndOfLineWith$1(value, literalline$2)), hasTrailingNewline ? hardline$7 : ""]); + } + + return fill$3(normalizeParts$1([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options)))); + } + + case "docType": + return concat$a([group$9(concat$a([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]); + + case "comment": + { + return concat$a([printOpeningTagPrefix(node, options), concat$a(replaceEndOfLineWith$1(options.originalText.slice(options.locStart(node), options.locEnd(node)), literalline$2)), printClosingTagSuffix(node, options)]); + } + + case "attribute": + { + if (node.value === null) { + return node.rawName; + } + + const value = unescapeQuoteEntities$1(node.value); + const singleQuoteCount = countChars$1(value, "'"); + const doubleQuoteCount = countChars$1(value, '"'); + const quote = singleQuoteCount < doubleQuoteCount ? "'" : '"'; + return concat$a([node.rawName, concat$a(["=", quote, concat$a(replaceEndOfLineWith$1(quote === '"' ? value.replace(/"/g, """) : value.replace(/'/g, "'"), literalline$2)), quote])]); + } + + case "yaml": + case "toml": + return concat$a(replaceEndOfLineWith$1(node.raw, literalline$2)); + + default: + throw new Error("Unexpected node type ".concat(node.type)); + } + } + + function printChildren$1(path, options, print) { + const node = path.getValue(); + + if (forceBreakChildren$1(node)) { + return concat$a([breakParent$2, concat$a(path.map(childPath => { + const childNode = childPath.getValue(); + const prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode); + return concat$a([!prevBetweenLine ? "" : concat$a([prevBetweenLine, forceNextEmptyLine$1(childNode.prev) ? hardline$7 : ""]), printChild(childPath)]); + }, "children"))]); + } + + const groupIds = node.children.map(() => Symbol("")); + return concat$a(path.map((childPath, childIndex) => { + const childNode = childPath.getValue(); + + if (isTextLikeNode$1(childNode)) { + if (childNode.prev && isTextLikeNode$1(childNode.prev)) { + const prevBetweenLine = printBetweenLine(childNode.prev, childNode); + + if (prevBetweenLine) { + if (forceNextEmptyLine$1(childNode.prev)) { + return concat$a([hardline$7, hardline$7, printChild(childPath)]); + } + + return concat$a([prevBetweenLine, printChild(childPath)]); + } + } + + return printChild(childPath); + } + + const prevParts = []; + const leadingParts = []; + const trailingParts = []; + const nextParts = []; + const prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : ""; + const nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : ""; + + if (prevBetweenLine) { + if (forceNextEmptyLine$1(childNode.prev)) { + prevParts.push(hardline$7, hardline$7); + } else if (prevBetweenLine === hardline$7) { + prevParts.push(hardline$7); + } else { + if (isTextLikeNode$1(childNode.prev)) { + leadingParts.push(prevBetweenLine); + } else { + leadingParts.push(ifBreak$5("", softline$4, { + groupId: groupIds[childIndex - 1] + })); + } + } + } + + if (nextBetweenLine) { + if (forceNextEmptyLine$1(childNode)) { + if (isTextLikeNode$1(childNode.next)) { + nextParts.push(hardline$7, hardline$7); + } + } else if (nextBetweenLine === hardline$7) { + if (isTextLikeNode$1(childNode.next)) { + nextParts.push(hardline$7); + } + } else { + trailingParts.push(nextBetweenLine); + } + } + + return concat$a([].concat(prevParts, group$9(concat$a([concat$a(leadingParts), group$9(concat$a([printChild(childPath), concat$a(trailingParts)]), { + id: groupIds[childIndex] + })])), nextParts)); + }, "children")); + + function printChild(childPath) { + const child = childPath.getValue(); + + if (hasPrettierIgnore$3(child)) { + return concat$a([].concat(printOpeningTagPrefix(child, options), replaceEndOfLineWith$1(options.originalText.slice(options.locStart(child) + (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) ? printOpeningTagStartMarker(child).length : 0), options.locEnd(child) - (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) ? printClosingTagEndMarker(child, options).length : 0)), literalline$2), printClosingTagSuffix(child, options))); + } + + if (shouldPreserveContent$1(child, options)) { + return concat$a([].concat(printOpeningTagPrefix(child, options), group$9(printOpeningTag(childPath, options, print)), replaceEndOfLineWith$1(options.originalText.slice(child.startSourceSpan.end.offset + (child.firstChild && needsToBorrowParentOpeningTagEndMarker(child.firstChild) ? -printOpeningTagEndMarker(child).length : 0), child.endSourceSpan.start.offset + (child.lastChild && needsToBorrowParentClosingTagStartMarker(child.lastChild) ? printClosingTagStartMarker(child, options).length : needsToBorrowLastChildClosingTagEndMarker(child) ? -printClosingTagEndMarker(child.lastChild, options).length : 0)), literalline$2), printClosingTag(child, options), printClosingTagSuffix(child, options))); + } + + return print(childPath); + } + + function printBetweenLine(prevNode, nextNode) { + return isTextLikeNode$1(prevNode) && isTextLikeNode$1(nextNode) ? prevNode.isTrailingSpaceSensitive ? prevNode.hasTrailingSpaces ? preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$7 : line$6 : "" : preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$7 : softline$4 : needsToBorrowNextOpeningTagStartMarker(prevNode) && (hasPrettierIgnore$3(nextNode) || + /** + * 123<a + * ~ + * ><b> + */ + nextNode.firstChild || + /** + * 123<!-- + * ~ + * --> + */ + nextNode.isSelfClosing || + /** + * 123<span + * ~ + * attr + */ + nextNode.type === "element" && nextNode.attrs.length !== 0) || + /** + * <img + * src="long" + * ~ + * />123 + */ + prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces$1(nextNode) || + /** + * Want to write us a letter? Use our<a + * ><b><a>mailing address</a></b></a + * ~ + * >. + */ + needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$7 : nextNode.hasLeadingSpaces ? line$6 : softline$4; + } + } + + function printOpeningTag(path, options, print) { + const node = path.getValue(); + const forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0; + return concat$a([printOpeningTagStart(node, options), !node.attrs || node.attrs.length === 0 ? node.isSelfClosing ? + /** + * <br /> + * ^ + */ + " " : "" : concat$a([indent$5(concat$a([forceNotToBreakAttrContent ? " " : line$6, join$6(line$6, (ignoreAttributeData => { + const hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? () => ignoreAttributeData : Array.isArray(ignoreAttributeData) ? attr => ignoreAttributeData.includes(attr.rawName) : () => false; + return path.map(attrPath => { + const attr = attrPath.getValue(); + return hasPrettierIgnoreAttribute(attr) ? concat$a(replaceEndOfLineWith$1(options.originalText.slice(options.locStart(attr), options.locEnd(attr)), literalline$2)) : print(attrPath); + }, "attrs"); + })(node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData$1(node.prev.value)))])), + /** + * 123<a + * attr + * ~ + * >456 + */ + node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) || + /** + * <span + * >123<meta + * ~ + * /></span> + */ + node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) ? node.isSelfClosing ? " " : "" : node.isSelfClosing ? forceNotToBreakAttrContent ? " " : line$6 : forceNotToBreakAttrContent ? "" : softline$4]), node.isSelfClosing ? "" : printOpeningTagEnd(node)]); + } + + function printOpeningTagStart(node, options) { + return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$a([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]); + } + + function printOpeningTagEnd(node) { + return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node); + } + + function printClosingTag(node, options) { + return concat$a([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]); + } + + function printClosingTagStart(node, options) { + return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$a([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]); + } + + function printClosingTagEnd(node, options) { + return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$a([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]); + } + + function needsToBorrowNextOpeningTagStartMarker(node) { + /** + * 123<p + * ^^ + * > + */ + return node.next && !isTextLikeNode$1(node.next) && isTextLikeNode$1(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces; + } + + function needsToBorrowParentOpeningTagEndMarker(node) { + /** + * <p + * >123 + * ^ + * + * <p + * ><a + * ^ + */ + return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces; + } + + function needsToBorrowPrevClosingTagEndMarker(node) { + /** + * <p></p + * >123 + * ^ + * + * <p></p + * ><a + * ^ + */ + return node.prev && !isTextLikeNode$1(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces; + } + + function needsToBorrowLastChildClosingTagEndMarker(node) { + /** + * <p + * ><a></a + * ></p + * ^ + * > + */ + return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode$1(getLastDescendant$1(node.lastChild)); + } + + function needsToBorrowParentClosingTagStartMarker(node) { + /** + * <p> + * 123</p + * ^^^ + * > + * + * 123</b + * ></a + * ^^^ + * > + */ + return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode$1(getLastDescendant$1(node)); + } + + function printOpeningTagPrefix(node, options) { + return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : ""; + } + + function printClosingTagPrefix(node, options) { + return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : ""; + } + + function printClosingTagSuffix(node, options) { + return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : ""; + } + + function printOpeningTagStartMarker(node) { + switch (node.type) { + case "ieConditionalComment": + case "ieConditionalStartComment": + return "<!--[if ".concat(node.condition); + + case "ieConditionalEndComment": + return "<!--<!"; + + case "interpolation": + return "{{"; + + case "docType": + return "<!DOCTYPE"; + + case "element": + if (node.condition) { + return "<!--[if ".concat(node.condition, "]><!--><").concat(node.rawName); + } + + // fall through + + default: + return "<".concat(node.rawName); + } + } + + function printOpeningTagEndMarker(node) { + assert(!node.isSelfClosing); + + switch (node.type) { + case "ieConditionalComment": + return "]>"; + + case "element": + if (node.condition) { + return "><!--<![endif]-->"; + } + + // fall through + + default: + return ">"; + } + } + + function printClosingTagStartMarker(node, options) { + assert(!node.isSelfClosing); + + if (shouldNotPrintClosingTag$1(node, options)) { + return ""; + } + + switch (node.type) { + case "ieConditionalComment": + return "<!"; + + case "element": + if (node.hasHtmComponentClosingTag) { + return "<//"; + } + + // fall through + + default: + return "</".concat(node.rawName); + } + } + + function printClosingTagEndMarker(node, options) { + if (shouldNotPrintClosingTag$1(node, options)) { + return ""; + } + + switch (node.type) { + case "ieConditionalComment": + case "ieConditionalEndComment": + return "[endif]-->"; + + case "ieConditionalStartComment": + return "]><!-->"; + + case "interpolation": + return "}}"; + + case "element": + if (node.isSelfClosing) { + return "/>"; + } + + // fall through + + default: + return ">"; + } + } + + function getTextValueParts(node, value = node.value) { + return node.parent.isWhitespaceSensitive ? node.parent.isIndentationSensitive ? replaceEndOfLineWith$1(value, literalline$2) : replaceEndOfLineWith$1(dedentString$1(value.replace(/^\s*?\n|\n\s*?$/g, "")), hardline$7) : // https://infra.spec.whatwg.org/#ascii-whitespace + join$6(line$6, value.split(/[\t\n\f\r ]+/)).parts; + } + + function printEmbeddedAttributeValue(node, originalTextToDoc, options) { + const isKeyMatched = patterns => new RegExp(patterns.join("|")).test(node.fullName); + + const getValue = () => unescapeQuoteEntities$1(node.value); + + let shouldHug = false; + + const __onHtmlBindingRoot = (root, options) => { + const rootNode = root.type === "NGRoot" ? root.node.type === "NGMicrosyntax" && root.node.body.length === 1 && root.node.body[0].type === "NGMicrosyntaxExpression" ? root.node.body[0].expression : root.node : root.type === "JsExpressionRoot" ? root.node : root; + + if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression" || options.parser === "__vue_expression" && (rootNode.type === "TemplateLiteral" || rootNode.type === "StringLiteral"))) { + shouldHug = true; + } + }; + + const printHug = doc => group$9(doc); + + const printExpand = (doc, canHaveTrailingWhitespace = true) => group$9(concat$a([indent$5(concat$a([softline$4, doc])), canHaveTrailingWhitespace ? softline$4 : ""])); + + const printMaybeHug = doc => shouldHug ? printHug(doc) : printExpand(doc); + + const textToDoc = (code, opts) => originalTextToDoc(code, Object.assign({ + __onHtmlBindingRoot + }, opts)); + + if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) { + return printExpand(printImgSrcset$1(getValue())); + } + + if (node.fullName === "class" && !options.parentParser) { + const value = getValue(); + + if (!value.includes("{{")) { + return printClassNames$1(value); + } + } + + if (node.fullName === "style" && !options.parentParser) { + const value = getValue(); + + if (!value.includes("{{")) { + return printExpand(textToDoc(value, { + parser: "css", + __isHTMLStyleAttribute: true + })); + } + } + + if (options.parser === "vue") { + if (node.fullName === "v-for") { + return printVueFor$1(getValue(), textToDoc); + } + + if (node.fullName === "slot-scope") { + return printVueSlotScope$1(getValue(), textToDoc); + } + /** + * @click="jsStatement" + * @click="jsExpression" + * v-on:click="jsStatement" + * v-on:click="jsExpression" + */ + + + const vueEventBindingPatterns = ["^@", "^v-on:"]; + /** + * :class="vueExpression" + * v-bind:id="vueExpression" + */ + + const vueExpressionBindingPatterns = ["^:", "^v-bind:"]; + /** + * v-if="jsExpression" + */ + + const jsExpressionBindingPatterns = ["^v-"]; + + if (isKeyMatched(vueEventBindingPatterns)) { + const value = getValue(); + return printMaybeHug(isVueEventBindingExpression$1(value) ? textToDoc(value, { + parser: "__js_expression" + }) : stripTrailingHardline$1(textToDoc(value, { + parser: "__vue_event_binding" + }))); + } + + if (isKeyMatched(vueExpressionBindingPatterns)) { + return printMaybeHug(textToDoc(getValue(), { + parser: "__vue_expression" + })); + } + + if (isKeyMatched(jsExpressionBindingPatterns)) { + return printMaybeHug(textToDoc(getValue(), { + parser: "__js_expression" + })); + } + } + + if (options.parser === "angular") { + const ngTextToDoc = (code, opts) => // angular does not allow trailing comma + textToDoc(code, Object.assign({}, opts, { + trailingComma: "none" + })); + /** + * *directive="angularDirective" + */ + + + const ngDirectiveBindingPatterns = ["^\\*"]; + /** + * (click)="angularStatement" + * on-click="angularStatement" + */ + + const ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"]; + /** + * [target]="angularExpression" + * bind-target="angularExpression" + * [(target)]="angularExpression" + * bindon-target="angularExpression" + */ + + const ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-", // Unofficial rudimentary support for some of the most used directives of AngularJS 1.x + "^ng-(if|show|hide|class|style)$"]; + /** + * i18n="longDescription" + * i18n-attr="longDescription" + */ + + const ngI18nPatterns = ["^i18n(-.+)?$"]; + + if (isKeyMatched(ngStatementBindingPatterns)) { + return printMaybeHug(ngTextToDoc(getValue(), { + parser: "__ng_action" + })); + } + + if (isKeyMatched(ngExpressionBindingPatterns)) { + return printMaybeHug(ngTextToDoc(getValue(), { + parser: "__ng_binding" + })); + } + + if (isKeyMatched(ngI18nPatterns)) { + const value = getValue().trim(); + return printExpand(fill$3(getTextValueParts(node, value)), !value.includes("@@")); + } + + if (isKeyMatched(ngDirectiveBindingPatterns)) { + return printMaybeHug(ngTextToDoc(getValue(), { + parser: "__ng_directive" + })); + } + + const interpolationRegex = /\{\{([\s\S]+?)\}\}/g; + const value = getValue(); + + if (interpolationRegex.test(value)) { + const parts = []; + value.split(interpolationRegex).forEach((part, index) => { + if (index % 2 === 0) { + parts.push(concat$a(replaceEndOfLineWith$1(part, literalline$2))); + } else { + try { + parts.push(group$9(concat$a(["{{", indent$5(concat$a([line$6, ngTextToDoc(part, { + parser: "__ng_interpolation", + __isInHtmlInterpolation: true // to avoid unexpected `}}` + + })])), line$6, "}}"]))); + } catch (e) { + parts.push("{{", concat$a(replaceEndOfLineWith$1(part, literalline$2)), "}}"); + } + } + }); + return group$9(concat$a(parts)); + } + } + + return null; + } + + var printerHtml = { + preprocess: preprocess_1, + print: genericPrint$2, + insertPragma: insertPragma$6, + massageAstNode: clean$3, + embed: embed$2 + }; + + const CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js + + var options$4 = { + htmlWhitespaceSensitivity: { + since: "1.15.0", + category: CATEGORY_HTML, + type: "choice", + default: "css", + description: "How to handle whitespaces in HTML.", + choices: [{ + value: "css", + description: "Respect the default value of CSS display property." + }, { + value: "strict", + description: "Whitespaces are considered sensitive." + }, { + value: "ignore", + description: "Whitespaces are considered insensitive." + }] + }, + vueIndentScriptAndStyle: { + since: "1.19.0", + category: CATEGORY_HTML, + type: "boolean", + default: false, + description: "Indent script and style tags in Vue files." + } + }; + + var name$7 = "HTML"; + var type$6 = "markup"; + var tmScope$6 = "text.html.basic"; + var aceMode$6 = "html"; + var codemirrorMode$3 = "htmlmixed"; + var codemirrorMimeType$3 = "text/html"; + var color$1 = "#e34c26"; + var aliases$1 = [ + "xhtml" + ]; + var extensions$6 = [ + ".html", + ".htm", + ".html.hl", + ".inc", + ".st", + ".xht", + ".xhtml" + ]; + var languageId$6 = 146; + var HTML = { + name: name$7, + type: type$6, + tmScope: tmScope$6, + aceMode: aceMode$6, + codemirrorMode: codemirrorMode$3, + codemirrorMimeType: codemirrorMimeType$3, + color: color$1, + aliases: aliases$1, + extensions: extensions$6, + languageId: languageId$6 + }; + + var HTML$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$7, + type: type$6, + tmScope: tmScope$6, + aceMode: aceMode$6, + codemirrorMode: codemirrorMode$3, + codemirrorMimeType: codemirrorMimeType$3, + color: color$1, + aliases: aliases$1, + extensions: extensions$6, + languageId: languageId$6, + 'default': HTML + }); + + var name$8 = "Vue"; + var type$7 = "markup"; + var color$2 = "#2c3e50"; + var extensions$7 = [ + ".vue" + ]; + var tmScope$7 = "text.html.vue"; + var aceMode$7 = "html"; + var languageId$7 = 391; + var Vue = { + name: name$8, + type: type$7, + color: color$2, + extensions: extensions$7, + tmScope: tmScope$7, + aceMode: aceMode$7, + languageId: languageId$7 + }; + + var Vue$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$8, + type: type$7, + color: color$2, + extensions: extensions$7, + tmScope: tmScope$7, + aceMode: aceMode$7, + languageId: languageId$7, + 'default': Vue + }); + + var require$$0$5 = getCjsExportFromNamespace(HTML$1); + + var require$$1$1 = getCjsExportFromNamespace(Vue$1); + + const languages$3 = [createLanguage(require$$0$5, () => ({ + name: "Angular", + since: "1.15.0", + parsers: ["angular"], + vscodeLanguageIds: ["html"], + extensions: [".component.html"], + filenames: [] + })), createLanguage(require$$0$5, data => ({ + since: "1.15.0", + parsers: ["html"], + vscodeLanguageIds: ["html"], + extensions: data.extensions.concat([".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML + ]) + })), createLanguage(require$$0$5, () => ({ + name: "Lightning Web Components", + since: "1.17.0", + parsers: ["lwc"], + vscodeLanguageIds: ["html"], + extensions: [], + filenames: [] + })), createLanguage(require$$1$1, () => ({ + since: "1.10.0", + parsers: ["vue"], + vscodeLanguageIds: ["vue"] + }))]; + const printers$3 = { + html: printerHtml + }; + var languageHtml = { + languages: languages$3, + printers: printers$3, + options: options$4 + }; + + const { + addLeadingComment: addLeadingComment$3, + addTrailingComment: addTrailingComment$3, + addDanglingComment: addDanglingComment$3, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$2 + } = utilShared; + + function handleOwnLineComment(comment, text, options, ast, isLastComment) { + const { + precedingNode, + enclosingNode, + followingNode + } = comment; + return handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleMemberExpressionComments(enclosingNode, followingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleImportSpecifierComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) || handleAssignmentPatternComments(enclosingNode, comment) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleLabeledStatementComments(enclosingNode, comment); + } + + function handleEndOfLineComment(comment, text, options, ast, isLastComment) { + const { + precedingNode, + enclosingNode, + followingNode + } = comment; + return handleClosureTypeCastComments(followingNode, comment) || handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) || handleImportSpecifierComments(enclosingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleTypeAliasComments(enclosingNode, followingNode, comment) || handleVariableDeclaratorComments(enclosingNode, followingNode, comment); + } + + function handleRemainingComment(comment, text, options, ast, isLastComment) { + const { + precedingNode, + enclosingNode, + followingNode + } = comment; + + if (handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment, options) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleCommentAfterArrowParams(text, enclosingNode, comment, options) || handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) || handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) || handleBreakAndContinueStatementComments(enclosingNode, comment) || handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options)) { + return true; + } + + return false; + } + + function addBlockStatementFirstComment(node, comment) { + const body = node.body.filter(n => n.type !== "EmptyStatement"); + + if (body.length === 0) { + addDanglingComment$3(node, comment); + } else { + addLeadingComment$3(body[0], comment); + } + } + + function addBlockOrNotComment(node, comment) { + if (node.type === "BlockStatement") { + addBlockStatementFirstComment(node, comment); + } else { + addLeadingComment$3(node, comment); + } + } + + function handleClosureTypeCastComments(followingNode, comment) { + if (followingNode && isTypeCastComment(comment)) { + addLeadingComment$3(followingNode, comment); + return true; + } + + return false; + } // There are often comments before the else clause of if statements like + // + // if (1) { ... } + // // comment + // else { ... } + // + // They are being attached as leading comments of the BlockExpression which + // is not well printed. What we want is to instead move the comment inside + // of the block and make it leadingComment of the first element of the block + // or dangling comment of the block if there is nothing inside + // + // if (1) { ... } + // else { + // // comment + // ... + // } + + + function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) { + if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) { + return false; + } // We unfortunately have no way using the AST or location of nodes to know + // if the comment is positioned before the condition parenthesis: + // if (a /* comment */) {} + // The only workaround I found is to look at the next character to see if + // it is a ). + + + const nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd); + + if (nextCharacter === ")") { + addTrailingComment$3(precedingNode, comment); + return true; + } // Comments before `else`: + // - treat as trailing comments of the consequent, if it's a BlockStatement + // - treat as a dangling comment otherwise + + + if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) { + if (precedingNode.type === "BlockStatement") { + addTrailingComment$3(precedingNode, comment); + } else { + addDanglingComment$3(enclosingNode, comment); + } + + return true; + } + + if (followingNode.type === "BlockStatement") { + addBlockStatementFirstComment(followingNode, comment); + return true; + } + + if (followingNode.type === "IfStatement") { + addBlockOrNotComment(followingNode.consequent, comment); + return true; + } // For comments positioned after the condition parenthesis in an if statement + // before the consequent without brackets on, such as + // if (a) /* comment */ true, + // we look at the next character to see if the following node + // is the consequent for the if statement + + + if (enclosingNode.consequent === followingNode) { + addLeadingComment$3(followingNode, comment); + return true; + } + + return false; + } + + function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) { + if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) { + return false; + } // We unfortunately have no way using the AST or location of nodes to know + // if the comment is positioned before the condition parenthesis: + // while (a /* comment */) {} + // The only workaround I found is to look at the next character to see if + // it is a ). + + + const nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd); + + if (nextCharacter === ")") { + addTrailingComment$3(precedingNode, comment); + return true; + } + + if (followingNode.type === "BlockStatement") { + addBlockStatementFirstComment(followingNode, comment); + return true; + } + + return false; + } // Same as IfStatement but for TryStatement + + + function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) { + if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) { + return false; + } + + if (enclosingNode.type === "CatchClause" && precedingNode) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + if (followingNode.type === "BlockStatement") { + addBlockStatementFirstComment(followingNode, comment); + return true; + } + + if (followingNode.type === "TryStatement") { + addBlockOrNotComment(followingNode.finalizer, comment); + return true; + } + + if (followingNode.type === "CatchClause") { + addBlockOrNotComment(followingNode.body, comment); + return true; + } + + return false; + } + + function handleMemberExpressionComments(enclosingNode, followingNode, comment) { + if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) { + const isSameLineAsPrecedingNode = precedingNode && !util$1.hasNewlineInRange(text, options.locEnd(precedingNode), options.locStart(comment)); + + if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && enclosingNode.type === "ConditionalExpression" && followingNode) { + addLeadingComment$3(followingNode, comment); + return true; + } + + return false; + } + + function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) { + if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") { + addTrailingComment$3(enclosingNode.value.left, comment); + return true; + } + + return false; + } + + function handleClassComments(enclosingNode, precedingNode, followingNode, comment) { + if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression") && enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) { + if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) { + addLeadingComment$3(enclosingNode, comment); + } else { + addTrailingComment$3(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment); + } + + return true; + } + + return false; + } + + function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) { + // This is only needed for estree parsers (flow, typescript) to attach + // after a method name: + // obj = { fn /*comment*/() {} }; + if (enclosingNode && precedingNode && ( // "MethodDefinition" is handled in getCommentChildNodes + enclosingNode.type === "Property" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "TSAbstractMethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) }; + // comment should be attached to value instead of key + util$1.getNextNonSpaceNonCommentCharacter(text, precedingNode, options.locEnd) !== ":") { + addTrailingComment$3(precedingNode, comment); + return true; + } // Print comments between decorators and class methods as a trailing comment + // on the decorator node instead of the method node + + + if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "MethodDefinition")) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + return false; + } + + function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) { + if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== "(") { + return false; + } + + if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + return false; + } + + function handleCommentAfterArrowParams(text, enclosingNode, comment, options) { + if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) { + return false; + } + + const index = getNextNonSpaceNonCommentCharacterIndex$2(text, comment, options.locEnd); + + if (text.slice(index, index + 2) === "=>") { + addDanglingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleCommentInEmptyParens(text, enclosingNode, comment, options) { + if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== ")") { + return false; + } // Only add dangling comments to fix the case when no params are present, + // i.e. a function without any argument. + + + if (enclosingNode && (isRealFunctionLikeNode(enclosingNode) && // `params` vs `parameters` - see https://github.com/babel/babel/issues/9231 + (enclosingNode.params || enclosingNode.parameters).length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) { + addDanglingComment$3(enclosingNode, comment); + return true; + } + + if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) { + addDanglingComment$3(enclosingNode.value, comment); + return true; + } + + return false; + } + + function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) { + // Flow function type definitions + if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") { + addTrailingComment$3(precedingNode, comment); + return true; + } // Real functions and TypeScript function type definitions + + + if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && isRealFunctionLikeNode(enclosingNode) && util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ")") { + addTrailingComment$3(precedingNode, comment); + return true; + } + + if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") { + const functionParamRightParenIndex = (() => { + if ((enclosingNode.params || enclosingNode.parameters).length !== 0) { + return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(util$1.getLast(enclosingNode.params || enclosingNode.parameters))); + } + + const functionParamLeftParenIndex = util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(enclosingNode.id)); + return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1); + })(); + + if (options.locStart(comment) > functionParamRightParenIndex) { + addBlockStatementFirstComment(followingNode, comment); + return true; + } + } + + return false; + } + + function handleImportSpecifierComments(enclosingNode, comment) { + if (enclosingNode && enclosingNode.type === "ImportSpecifier") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleLabeledStatementComments(enclosingNode, comment) { + if (enclosingNode && enclosingNode.type === "LabeledStatement") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleBreakAndContinueStatementComments(enclosingNode, comment) { + if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) { + addTrailingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleCallExpressionComments(precedingNode, enclosingNode, comment) { + if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) { + addLeadingComment$3(enclosingNode.arguments[0], comment); + return true; + } + + return false; + } + + function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) { + if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) { + if (util$1.isNodeIgnoreComment(comment)) { + followingNode.prettierIgnore = true; + comment.unignore = true; + } + + if (precedingNode) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + return false; + } + + if (followingNode && (followingNode.type === "UnionTypeAnnotation" || followingNode.type === "TSUnionType") && util$1.isNodeIgnoreComment(comment)) { + followingNode.types[0].prettierIgnore = true; + comment.unignore = true; + } + + return false; + } + + function handlePropertyComments(enclosingNode, comment) { + if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleOnlyComments(enclosingNode, ast, comment, isLastComment) { + // With Flow the enclosingNode is undefined so use the AST instead. + if (ast && ast.body && ast.body.length === 0) { + if (isLastComment) { + addDanglingComment$3(ast, comment); + } else { + addLeadingComment$3(ast, comment); + } + + return true; + } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) { + if (isLastComment) { + addDanglingComment$3(enclosingNode, comment); + } else { + addLeadingComment$3(enclosingNode, comment); + } + + return true; + } + + return false; + } + + function handleForComments(enclosingNode, precedingNode, comment) { + if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) { + if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && util$1.hasNewline(text, options.locEnd(comment))) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + return false; + } + + function handleAssignmentPatternComments(enclosingNode, comment) { + if (enclosingNode && enclosingNode.type === "AssignmentPattern") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleTypeAliasComments(enclosingNode, followingNode, comment) { + if (enclosingNode && enclosingNode.type === "TypeAlias") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) { + if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression" || isBlockComment(comment))) { + addLeadingComment$3(followingNode, comment); + return true; + } + + return false; + } + + function handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options) { + if (!followingNode && enclosingNode && (enclosingNode.type === "TSMethodSignature" || enclosingNode.type === "TSDeclareFunction" || enclosingNode.type === "TSAbstractMethodDefinition") && util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ";") { + addTrailingComment$3(enclosingNode, comment); + return true; + } + + return false; + } + + function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) { + if (!enclosingNode || enclosingNode.type !== "TSMappedType") { + return false; + } + + if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) { + addLeadingComment$3(followingNode.name, comment); + return true; + } + + if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) { + addTrailingComment$3(precedingNode.constraint, comment); + return true; + } + + return false; + } + + function isBlockComment(comment) { + return comment.type === "Block" || comment.type === "CommentBlock"; + } + + function hasLeadingComment(node, fn = () => true) { + if (node.leadingComments) { + return node.leadingComments.some(fn); + } + + if (node.comments) { + return node.comments.some(comment => comment.leading && fn(comment)); + } + + return false; + } + + function isRealFunctionLikeNode(node) { + return node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration" || node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "TSDeclareFunction" || node.type === "TSCallSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSMethodSignature" || node.type === "TSConstructorType" || node.type === "TSFunctionType" || node.type === "TSDeclareMethod"; + } + + function getGapRegex(enclosingNode) { + if (enclosingNode && enclosingNode.type !== "BinaryExpression" && enclosingNode.type !== "LogicalExpression") { + // Support degenerate single-element unions and intersections. + // E.g.: `type A = /* 1 */ & B` + return /^[\s(&|]*$/; + } + } + + function getCommentChildNodes(node, options) { + // Prevent attaching comments to FunctionExpression in this case: + // class Foo { + // bar() // comment + // { + // baz(); + // } + // } + if ((options.parser === "typescript" || options.parser === "flow") && node.type === "MethodDefinition" && node.value && node.value.type === "FunctionExpression" && node.value.params.length === 0 && !node.value.returnType && (!node.value.typeParameters || node.value.typeParameters.length === 0) && node.value.body) { + return [...(node.decorators || []), node.key, node.value.body]; + } + } + + function isTypeCastComment(comment) { + return isBlockComment(comment) && comment.value[0] === "*" && // TypeScript expects the type to be enclosed in curly brackets, however + // Closure Compiler accepts types in parens and even without any delimiters at all. + // That's why we just search for "@type". + /@type\b/.test(comment.value); + } + + var comments$1 = { + handleOwnLineComment, + handleEndOfLineComment, + handleRemainingComment, + hasLeadingComment, + isBlockComment, + isTypeCastComment, + getGapRegex, + getCommentChildNodes + }; + + const { + isBlockComment: isBlockComment$1, + hasLeadingComment: hasLeadingComment$1 + } = comments$1; + const { + builders: { + indent: indent$6, + join: join$7, + line: line$7, + hardline: hardline$8, + softline: softline$5, + literalline: literalline$3, + concat: concat$b, + group: group$a, + dedentToRoot: dedentToRoot$2 + }, + utils: { + mapDoc: mapDoc$3, + stripTrailingHardline: stripTrailingHardline$2 + } + } = document; + + function embed$3(path, print, textToDoc, options) { + const node = path.getValue(); + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + + switch (node.type) { + case "TemplateLiteral": + { + const isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(isIt => isIt(path)); + + if (isCss) { + // Get full template literal with expressions replaced by placeholders + const rawQuasis = node.quasis.map(q => q.value.raw); + let placeholderID = 0; + const text = rawQuasis.reduce((prevVal, currVal, idx) => { + return idx === 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal; + }, ""); + const doc = textToDoc(text, { + parser: "scss" + }); + return transformCssDoc(doc, path, print); + } + /* + * react-relay and graphql-tag + * graphql`...` + * graphql.experimental`...` + * gql`...` + * + * This intentionally excludes Relay Classic tags, as Prettier does not + * support Relay Classic formatting. + */ + + + if (isGraphQL(path)) { + const expressionDocs = node.expressions ? path.map(print, "expressions") : []; + const numQuasis = node.quasis.length; + + if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") { + return "``"; + } + + const parts = []; + + for (let i = 0; i < numQuasis; i++) { + const templateElement = node.quasis[i]; + const isFirst = i === 0; + const isLast = i === numQuasis - 1; + const text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence + // (which would make the `cooked` value be `null` or `undefined`) + + if (typeof text !== "string") { + return null; + } + + const lines = text.split("\n"); + const numLines = lines.length; + const expressionDoc = expressionDocs[i]; + const startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === ""; + const endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === ""; + const commentsAndWhitespaceOnly = lines.every(line => /^\s*(?:#[^\r\n]*)?$/.test(line)); // Bail out if an interpolation occurs within a comment. + + if (!isLast && /#[^\r\n]*$/.test(lines[numLines - 1])) { + return null; + } + + let doc = null; + + if (commentsAndWhitespaceOnly) { + doc = printGraphqlComments(lines); + } else { + doc = stripTrailingHardline$2(textToDoc(text, { + parser: "graphql" + })); + } + + if (doc) { + doc = escapeTemplateCharacters(doc, false); + + if (!isFirst && startsWithBlankLine) { + parts.push(""); + } + + parts.push(doc); + + if (!isLast && endsWithBlankLine) { + parts.push(""); + } + } else if (!isFirst && !isLast && startsWithBlankLine) { + parts.push(""); + } + + if (expressionDoc) { + parts.push(concat$b(["${", expressionDoc, "}"])); + } + } + + return concat$b(["`", indent$6(concat$b([hardline$8, join$7(hardline$8, parts)])), hardline$8, "`"]); + } + + const htmlParser = isHtml(path) ? "html" : isAngularComponentTemplate(path) ? "angular" : undefined; + + if (htmlParser) { + return printHtmlTemplateLiteral(path, print, textToDoc, htmlParser, options); + } + + break; + } + + case "TemplateElement": + { + /** + * md`...` + * markdown`...` + */ + if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) { + const text = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`"); + const indentation = getIndentation(text); + const hasIndent = indentation !== ""; + return concat$b([hasIndent ? indent$6(concat$b([softline$5, printMarkdown(text.replace(new RegExp("^".concat(indentation), "gm"), ""))])) : concat$b([literalline$3, dedentToRoot$2(printMarkdown(text))]), softline$5]); + } + + break; + } + } + + function printMarkdown(text) { + const doc = textToDoc(text, { + parser: "markdown", + __inJsTemplate: true + }); + return stripTrailingHardline$2(escapeTemplateCharacters(doc, true)); + } + } + + function getIndentation(str) { + const firstMatchedIndent = str.match(/^([^\S\n]*)\S/m); + return firstMatchedIndent === null ? "" : firstMatchedIndent[1]; + } + + function uncook(cookedValue) { + return cookedValue.replace(/([\\`]|\$\{)/g, "\\$1"); + } + + function escapeTemplateCharacters(doc, raw) { + return mapDoc$3(doc, currentDoc => { + if (!currentDoc.parts) { + return currentDoc; + } + + const parts = []; + currentDoc.parts.forEach(part => { + if (typeof part === "string") { + parts.push(raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part)); + } else { + parts.push(part); + } + }); + return Object.assign({}, currentDoc, { + parts + }); + }); + } + + function transformCssDoc(quasisDoc, path, print) { + const parentNode = path.getValue(); + const isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim(); + + if (isEmpty) { + return "``"; + } + + const expressionDocs = parentNode.expressions ? path.map(print, "expressions") : []; + const newDoc = replacePlaceholders(quasisDoc, expressionDocs); + /* istanbul ignore if */ + + if (!newDoc) { + throw new Error("Couldn't insert all the expressions"); + } + + return concat$b(["`", indent$6(concat$b([hardline$8, stripTrailingHardline$2(newDoc)])), softline$5, "`"]); + } // Search all the placeholders in the quasisDoc tree + // and replace them with the expression docs one by one + // returns a new doc with all the placeholders replaced, + // or null if it couldn't replace any expression + + + function replacePlaceholders(quasisDoc, expressionDocs) { + if (!expressionDocs || !expressionDocs.length) { + return quasisDoc; + } + + const expressions = expressionDocs.slice(); + let replaceCounter = 0; + const newDoc = mapDoc$3(quasisDoc, doc => { + if (!doc || !doc.parts || !doc.parts.length) { + return doc; + } + + let { + parts + } = doc; + const atIndex = parts.indexOf("@"); + const placeholderIndex = atIndex + 1; + + if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) { + // If placeholder is split, join it + const at = parts[atIndex]; + const placeholder = parts[placeholderIndex]; + const rest = parts.slice(placeholderIndex + 1); + parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest); + } + + const atPlaceholderIndex = parts.findIndex(part => typeof part === "string" && part.startsWith("@prettier-placeholder")); + + if (atPlaceholderIndex > -1) { + const placeholder = parts[atPlaceholderIndex]; + const rest = parts.slice(atPlaceholderIndex + 1); + const placeholderMatch = placeholder.match(/@prettier-placeholder-(.+)-id([\s\S]*)/); + const placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like: + // animation: linear ${time}s ease-out; + + const suffix = placeholderMatch[2]; + const expression = expressions[placeholderID]; + replaceCounter++; + parts = parts.slice(0, atPlaceholderIndex).concat(["${", expression, "}" + suffix]).concat(rest); + } + + return Object.assign({}, doc, { + parts + }); + }); + return expressions.length === replaceCounter ? newDoc : null; + } + + function printGraphqlComments(lines) { + const parts = []; + let seenComment = false; + lines.map(textLine => textLine.trim()).forEach((textLine, i, array) => { + // Lines are either whitespace only, or a comment (with potential whitespace + // around it). Drop whitespace-only lines. + if (textLine === "") { + return; + } + + if (array[i - 1] === "" && seenComment) { + // If a non-first comment is preceded by a blank (whitespace only) line, + // add in a blank line. + parts.push(concat$b([hardline$8, textLine])); + } else { + parts.push(textLine); + } + + seenComment = true; + }); // If `lines` was whitespace only, return `null`. + + return parts.length === 0 ? null : join$7(hardline$8, parts); + } + /** + * Template literal in these contexts: + * <style jsx>{`div{color:red}`}</style> + * css`` + * css.global`` + * css.resolve`` + */ + + + function isStyledJsx(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(attribute => attribute.name.name === "jsx") || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "Identifier" && parent.tag.name === "css" || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "MemberExpression" && parent.tag.object.name === "css" && (parent.tag.property.name === "global" || parent.tag.property.name === "resolve"); + } + /** + * Angular Components can have: + * - Inline HTML template + * - Inline CSS styles + * + * ...which are both within template literals somewhere + * inside of the Component decorator factory. + * + * E.g. + * @Component({ + * template: `<div>...</div>`, + * styles: [`h1 { color: blue; }`] + * }) + */ + + + function isAngularComponentStyles(path) { + return path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "ArrayExpression" && name === "elements", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "styles" && name === "value", ...angularComponentObjectExpressionPredicates); + } + + function isAngularComponentTemplate(path) { + return path.match(node => node.type === "TemplateLiteral", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "template" && name === "value", ...angularComponentObjectExpressionPredicates); + } + + const angularComponentObjectExpressionPredicates = [(node, name) => node.type === "ObjectExpression" && name === "properties", (node, name) => node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments", (node, name) => node.type === "Decorator" && name === "expression"]; + /** + * styled-components template literals + */ + + function isStyledComponents(path) { + const parent = path.getParentNode(); + + if (!parent || parent.type !== "TaggedTemplateExpression") { + return false; + } + + const { + tag + } = parent; + + switch (tag.type) { + case "MemberExpression": + return (// styled.foo`` + isStyledIdentifier(tag.object) || // Component.extend`` + isStyledExtend(tag) + ); + + case "CallExpression": + return (// styled(Component)`` + isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})`` + isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})`` + isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})`` + tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee)) + ); + + case "Identifier": + // css`` + return tag.name === "css"; + + default: + return false; + } + } + /** + * JSX element with CSS prop + */ + + + function isCssProp(path) { + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css"; + } + + function isStyledIdentifier(node) { + return node.type === "Identifier" && node.name === "styled"; + } + + function isStyledExtend(node) { + return /^[A-Z]/.test(node.object.name) && node.property.name === "extend"; + } + /* + * react-relay and graphql-tag + * graphql`...` + * graphql.experimental`...` + * gql`...` + * GraphQL comment block + * + * This intentionally excludes Relay Classic tags, as Prettier does not + * support Relay Classic formatting. + */ + + + function isGraphQL(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + return hasLanguageComment(node, "GraphQL") || parent && (parent.type === "TaggedTemplateExpression" && (parent.tag.type === "MemberExpression" && parent.tag.object.name === "graphql" && parent.tag.property.name === "experimental" || parent.tag.type === "Identifier" && (parent.tag.name === "gql" || parent.tag.name === "graphql")) || parent.type === "CallExpression" && parent.callee.type === "Identifier" && parent.callee.name === "graphql"); + } + + function hasLanguageComment(node, languageName) { + // This checks for a leading comment that is exactly `/* GraphQL */` + // In order to be in line with other implementations of this comment tag + // we will not trim the comment value and we will expect exactly one space on + // either side of the GraphQL string + // Also see ./clean.js + return hasLeadingComment$1(node, comment => isBlockComment$1(comment) && comment.value === " ".concat(languageName, " ")); + } + /** + * - html`...` + * - HTML comment block + */ + + + function isHtml(path) { + return hasLanguageComment(path.getValue(), "HTML") || path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi"); + } // The counter is needed to distinguish nested embeds. + + + let htmlTemplateLiteralCounter = 0; + + function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) { + const node = path.getValue(); + const counter = htmlTemplateLiteralCounter; + htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0; + + const composePlaceholder = index => "PRETTIER_HTML_PLACEHOLDER_".concat(index, "_").concat(counter, "_IN_JS"); + + const text = node.quasis.map((quasi, index, quasis) => index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index)).join(""); + const expressionDocs = path.map(print, "expressions"); + + if (expressionDocs.length === 0 && text.trim().length === 0) { + return "``"; + } + + const placeholderRegex = new RegExp(composePlaceholder("(\\d+)"), "g"); + let topLevelCount = 0; + const contentDoc = mapDoc$3(stripTrailingHardline$2(textToDoc(text, { + parser, + + __onHtmlRoot(root) { + topLevelCount = root.children.length; + } + + })), doc => { + if (typeof doc !== "string") { + return doc; + } + + const parts = []; + const components = doc.split(placeholderRegex); + + for (let i = 0; i < components.length; i++) { + let component = components[i]; + + if (i % 2 === 0) { + if (component) { + component = uncook(component); + + if (options.embeddedInHtml) { + component = component.replace(/<\/(script)\b/gi, "<\\/$1"); + } + + parts.push(component); + } + + continue; + } + + const placeholderIndex = +component; + parts.push(concat$b(["${", group$a(expressionDocs[placeholderIndex]), "}"])); + } + + return concat$b(parts); + }); + const leadingWhitespace = /^\s/.test(text) ? " " : ""; + const trailingWhitespace = /\s$/.test(text) ? " " : ""; + const linebreak = options.htmlWhitespaceSensitivity === "ignore" ? hardline$8 : leadingWhitespace && trailingWhitespace ? line$7 : null; + + if (linebreak) { + return group$a(concat$b(["`", indent$6(concat$b([linebreak, group$a(contentDoc)])), linebreak, "`"])); + } + + return group$a(concat$b(["`", leadingWhitespace, topLevelCount > 1 ? indent$6(group$a(contentDoc)) : group$a(contentDoc), trailingWhitespace, "`"])); + } + + var embed_1$1 = embed$3; + + function clean$4(ast, newObj, parent) { + ["range", "raw", "comments", "leadingComments", "trailingComments", "innerComments", "extra", "start", "end", "flags", "errors"].forEach(name => { + delete newObj[name]; + }); + + if (ast.loc && ast.loc.source === null) { + delete newObj.loc.source; + } + + if (ast.type === "BigIntLiteral") { + newObj.value = newObj.value.toLowerCase(); + } // We remove extra `;` and add them when needed + + + if (ast.type === "EmptyStatement") { + return null; + } // We move text around, including whitespaces and add {" "} + + + if (ast.type === "JSXText") { + return null; + } + + if (ast.type === "JSXExpressionContainer" && ast.expression.type === "Literal" && ast.expression.value === " ") { + return null; + } // (TypeScript) Ignore `static` in `constructor(static p) {}` + // and `export` in `constructor(export p) {}` + + + if (ast.type === "TSParameterProperty" && ast.accessibility === null && !ast.readonly) { + return { + type: "Identifier", + name: ast.parameter.name, + typeAnnotation: newObj.parameter.typeAnnotation, + decorators: newObj.decorators + }; + } // (TypeScript) ignore empty `specifiers` array + + + if (ast.type === "TSNamespaceExportDeclaration" && ast.specifiers && ast.specifiers.length === 0) { + delete newObj.specifiers; + } // We convert <div></div> to <div /> + + + if (ast.type === "JSXOpeningElement") { + delete newObj.selfClosing; + } + + if (ast.type === "JSXElement") { + delete newObj.closingElement; + } // We change {'key': value} into {key: value} + + + if ((ast.type === "Property" || ast.type === "ObjectProperty" || ast.type === "MethodDefinition" || ast.type === "ClassProperty" || ast.type === "TSPropertySignature" || ast.type === "ObjectTypeProperty") && typeof ast.key === "object" && ast.key && (ast.key.type === "Literal" || ast.key.type === "StringLiteral" || ast.key.type === "Identifier")) { + delete newObj.key; + } + + if (ast.type === "OptionalMemberExpression" && ast.optional === false) { + newObj.type = "MemberExpression"; + delete newObj.optional; + } // Remove raw and cooked values from TemplateElement when it's CSS + // styled-jsx + + + if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(attr => attr.name.name === "jsx")) { + const templateLiterals = newObj.children.filter(child => child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral").map(container => container.expression); + const quasis = templateLiterals.reduce((quasis, templateLiteral) => quasis.concat(templateLiteral.quasis), []); + quasis.forEach(q => delete q.value); + } // CSS template literals in css prop + + + if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") { + newObj.value.expression.quasis.forEach(q => delete q.value); + } // Angular Components: Inline HTML template and Inline CSS styles + + + const expression = ast.expression || ast.callee; + + if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) { + const astProps = ast.expression.arguments[0].properties; + newObj.expression.arguments[0].properties.forEach((prop, index) => { + let templateLiteral = null; + + switch (astProps[index].key.name) { + case "styles": + if (prop.value.type === "ArrayExpression") { + templateLiteral = prop.value.elements[0]; + } + + break; + + case "template": + if (prop.value.type === "TemplateLiteral") { + templateLiteral = prop.value; + } + + break; + } + + if (templateLiteral) { + templateLiteral.quasis.forEach(q => delete q.value); + } + }); + } // styled-components, graphql, markdown + + + if (ast.type === "TaggedTemplateExpression" && (ast.tag.type === "MemberExpression" || ast.tag.type === "Identifier" && (ast.tag.name === "gql" || ast.tag.name === "graphql" || ast.tag.name === "css" || ast.tag.name === "md" || ast.tag.name === "markdown" || ast.tag.name === "html") || ast.tag.type === "CallExpression")) { + newObj.quasi.quasis.forEach(quasi => delete quasi.value); + } + + if (ast.type === "TemplateLiteral") { + // This checks for a leading comment that is exactly `/* GraphQL */` + // In order to be in line with other implementations of this comment tag + // we will not trim the comment value and we will expect exactly one space on + // either side of the GraphQL string + // Also see ./embed.js + const hasLanguageComment = ast.leadingComments && ast.leadingComments.some(comment => comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(languageName => comment.value === " ".concat(languageName, " "))); + + if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") { + newObj.quasis.forEach(quasi => delete quasi.value); + } + } + } + + var clean_1$1 = clean$4; + + const { + getLast: getLast$2, + hasNewline: hasNewline$4, + hasNewlineInRange: hasNewlineInRange$2, + hasIgnoreComment: hasIgnoreComment$3, + hasNodeIgnoreComment: hasNodeIgnoreComment$1, + skipWhitespace: skipWhitespace$2 + } = util$1; + const isIdentifierName = utils$1.keyword.isIdentifierNameES5; // We match any whitespace except line terminators because + // Flow annotation comments cannot be split across lines. For example: + // + // (this /* + // : any */).foo = 5; + // + // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so + // removing the newline would create a type annotation that the user did not intend + // to create. + + const NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)"; + const FLOW_SHORTHAND_ANNOTATION = new RegExp("^".concat(NON_LINE_TERMINATING_WHITE_SPACE, "*:")); + const FLOW_ANNOTATION = new RegExp("^".concat(NON_LINE_TERMINATING_WHITE_SPACE, "*::")); + + function hasFlowShorthandAnnotationComment(node) { + // https://flow.org/en/docs/types/comments/ + // Syntax example: const r = new (window.Request /*: Class<Request> */)(""); + return node.extra && node.extra.parenthesized && node.trailingComments && node.trailingComments[0].value.match(FLOW_SHORTHAND_ANNOTATION); + } + + function hasFlowAnnotationComment(comments) { + return comments && comments[0].value.match(FLOW_ANNOTATION); + } + + function hasNode(node, fn) { + if (!node || typeof node !== "object") { + return false; + } + + if (Array.isArray(node)) { + return node.some(value => hasNode(value, fn)); + } + + const result = fn(node); + return typeof result === "boolean" ? result : Object.keys(node).some(key => hasNode(node[key], fn)); + } + + function hasNakedLeftSide(node) { + return node.type === "AssignmentExpression" || node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression" || node.type === "ConditionalExpression" || node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "BindExpression" || node.type === "UpdateExpression" && !node.prefix || node.type === "TSAsExpression" || node.type === "TSNonNullExpression"; + } + + function getLeftSide(node) { + if (node.expressions) { + return node.expressions[0]; + } + + return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression; + } + + function getLeftSidePathName(path, node) { + if (node.expressions) { + return ["expressions", 0]; + } + + if (node.left) { + return ["left"]; + } + + if (node.test) { + return ["test"]; + } + + if (node.object) { + return ["object"]; + } + + if (node.callee) { + return ["callee"]; + } + + if (node.tag) { + return ["tag"]; + } + + if (node.argument) { + return ["argument"]; + } + + if (node.expression) { + return ["expression"]; + } + + throw new Error("Unexpected node has no left side", node); + } + + const exportDeclarationTypes = new Set(["ExportDefaultDeclaration", "ExportDefaultSpecifier", "DeclareExportDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration"]); + + function isExportDeclaration(node) { + return node && exportDeclarationTypes.has(node.type); + } + + function getParentExportDeclaration(path) { + const parentNode = path.getParentNode(); + + if (path.getName() === "declaration" && isExportDeclaration(parentNode)) { + return parentNode; + } + + return null; + } + + function isLiteral(node) { + return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText"; + } + + function isNumericLiteral(node) { + return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number"; + } + + function isStringLiteral(node) { + return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string"; + } + + function isObjectType(n) { + return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral"; + } + + function isFunctionOrArrowExpression(node) { + return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression"; + } + + function isFunctionOrArrowExpressionWithBody(node) { + return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement"; + } + + function isTemplateLiteral(node) { + return node.type === "TemplateLiteral"; + } // `inject` is used in AngularJS 1.x, `async` in Angular 2+ + // example: https://docs.angularjs.org/guide/unit-testing#using-beforeall- + + + function isAngularTestWrapper(node) { + return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync"); + } + + function isJSXNode(node) { + return node.type === "JSXElement" || node.type === "JSXFragment"; + } + + function isTheOnlyJSXElementInMarkdown(options, path) { + if (options.parentParser !== "markdown" && options.parentParser !== "mdx") { + return false; + } + + const node = path.getNode(); + + if (!node.expression || !isJSXNode(node.expression)) { + return false; + } + + const parent = path.getParentNode(); + return parent.type === "Program" && parent.body.length === 1; + } // Detect an expression node representing `{" "}` + + + function isJSXWhitespaceExpression(node) { + return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments; + } + + function isMemberExpressionChain(node) { + if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") { + return false; + } + + if (node.object.type === "Identifier") { + return true; + } + + return isMemberExpressionChain(node.object); + } + + function isGetterOrSetter(node) { + return node.kind === "get" || node.kind === "set"; + } + + function sameLocStart(nodeA, nodeB, options) { + return options.locStart(nodeA) === options.locStart(nodeB); + } // TODO: This is a bad hack and we need a better way to distinguish between + // arrow functions and otherwise + + + function isFunctionNotation(node, options) { + return isGetterOrSetter(node) || sameLocStart(node, node.value, options); + } // Hack to differentiate between the following two which have the same ast + // type T = { method: () => void }; + // type T = { method(): void }; + + + function isObjectTypePropertyAFunction(node, options) { + return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options); + } // Hack to differentiate between the following two which have the same ast + // declare function f(a): void; + // var f: (a) => void; + + + function isTypeAnnotationAFunction(node, options) { + return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options); + } + + const binaryishNodeTypes = new Set(["BinaryExpression", "LogicalExpression", "NGPipeExpression"]); + + function isBinaryish(node) { + return binaryishNodeTypes.has(node.type); + } + + function isMemberish(node) { + return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object; + } + + function isSimpleFlowType(node) { + const flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"]; + return node && flowTypeAnnotations.includes(node.type) && !(node.type === "GenericTypeAnnotation" && node.typeParameters); + } + + const unitTestRe = /^(skip|[fx]?(it|describe|test))$/; + + function isSkipOrOnlyBlock(node) { + return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && node.callee.object.type === "Identifier" && node.callee.property.type === "Identifier" && unitTestRe.test(node.callee.object.name) && (node.callee.property.name === "only" || node.callee.property.name === "skip"); + } + + function isUnitTestSetUp(n) { + const unitTestSetUpRe = /^(before|after)(Each|All)$/; + return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1; + } // eg; `describe("some string", (done) => {})` + + + function isTestCall(n, parent) { + if (n.type !== "CallExpression") { + return false; + } + + if (n.arguments.length === 1) { + if (isAngularTestWrapper(n) && parent && isTestCall(parent)) { + return isFunctionOrArrowExpression(n.arguments[0]); + } + + if (isUnitTestSetUp(n)) { + return isAngularTestWrapper(n.arguments[0]); + } + } else if (n.arguments.length === 2 || n.arguments.length === 3) { + if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) { + // it("name", () => { ... }, 2500) + if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) { + return false; + } + + return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]); + } + } + + return false; + } + + function hasLeadingComment$2(node) { + return node.comments && node.comments.some(comment => comment.leading); + } + + function hasTrailingComment(node) { + return node.comments && node.comments.some(comment => comment.trailing); + } + + function isCallOrOptionalCallExpression(node) { + return node.type === "CallExpression" || node.type === "OptionalCallExpression"; + } + + function hasDanglingComments(node) { + return node.comments && node.comments.some(comment => !comment.leading && !comment.trailing); + } + /** identify if an angular expression seems to have side effects */ + + + function hasNgSideEffect(path) { + return hasNode(path.getValue(), node => { + switch (node.type) { + case undefined: + return false; + + case "CallExpression": + case "OptionalCallExpression": + case "AssignmentExpression": + return true; + } + }); + } + + function isNgForOf(node, index, parentNode) { + return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null; + } + /** @param node {import("estree").TemplateLiteral} */ + + + function isSimpleTemplateLiteral(node) { + if (node.expressions.length === 0) { + return false; + } + + return node.expressions.every(expr => { + // Disallow comments since printDocToString can't print them here + if (expr.comments) { + return false; + } // Allow `x` and `this` + + + if (expr.type === "Identifier" || expr.type === "ThisExpression") { + return true; + } // Allow `a.b.c`, `a.b[c]`, and `this.x.y` + + + if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") { + let head = expr; + + while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") { + if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") { + return false; + } + + head = head.object; + + if (head.comments) { + return false; + } + } + + if (head.type === "Identifier" || head.type === "ThisExpression") { + return true; + } + + return false; + } + + return false; + }); + } + + function getFlowVariance(path) { + if (!path.variance) { + return null; + } // Babel 7.0 currently uses variance node type, and flow should + // follow suit soon: + // https://github.com/babel/babel/issues/4722 + + + const variance = path.variance.kind || path.variance; + + switch (variance) { + case "plus": + return "+"; + + case "minus": + return "-"; + + default: + /* istanbul ignore next */ + return variance; + } + } + + function classPropMayCauseASIProblems(path) { + const node = path.getNode(); + + if (node.type !== "ClassProperty") { + return false; + } + + const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today + // so isn't properly tested yet. + + if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) { + return true; + } + } + + function classChildNeedsASIProtection(node) { + if (!node) { + return; + } + + if (node.static || node.accessibility // TypeScript + ) { + return false; + } + + if (!node.computed) { + const name = node.key && node.key.name; + + if (name === "in" || name === "instanceof") { + return true; + } + } + + switch (node.type) { + case "ClassProperty": + case "TSAbstractClassProperty": + return node.computed; + + case "MethodDefinition": // Flow + + case "TSAbstractMethodDefinition": // TypeScript + + case "ClassMethod": + case "ClassPrivateMethod": + { + // Babel + const isAsync = node.value ? node.value.async : node.async; + const isGenerator = node.value ? node.value.generator : node.generator; + + if (isAsync || node.kind === "get" || node.kind === "set") { + return false; + } + + if (node.computed || isGenerator) { + return true; + } + + return false; + } + + case "TSIndexSignature": + return true; + + default: + /* istanbul ignore next */ + return false; + } + } + + function getTypeScriptMappedTypeModifier(tokenNode, keyword) { + if (tokenNode === "+") { + return "+" + keyword; + } else if (tokenNode === "-") { + return "-" + keyword; + } + + return keyword; + } + + function hasNewlineBetweenOrAfterDecorators(node, options) { + return hasNewlineInRange$2(options.originalText, options.locStart(node.decorators[0]), options.locEnd(getLast$2(node.decorators))) || hasNewline$4(options.originalText, options.locEnd(getLast$2(node.decorators))); + } // Only space, newline, carriage return, and tab are treated as whitespace + // inside JSX. + + + const jsxWhitespaceChars = " \n\r\t"; + const matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)"); + const containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters, + // or it contains whitespace without a new line. + + function isMeaningfulJSXText(node) { + return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node))); + } + + function hasJsxIgnoreComment(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + + if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) { + return false; + } // Lookup the previous sibling, ignoring any empty JSXText elements + + + const index = parent.children.indexOf(node); + let prevSibling = null; + + for (let i = index; i > 0; i--) { + const candidate = parent.children[i - 1]; + + if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) { + continue; + } + + prevSibling = candidate; + break; + } + + return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find(comment => comment.value.trim() === "prettier-ignore"); + } + + function isEmptyJSXElement(node) { + if (node.children.length === 0) { + return true; + } + + if (node.children.length > 1) { + return false; + } // if there is one text child and does not contain any meaningful text + // we can treat the element as empty. + + + const child = node.children[0]; + return isLiteral(child) && !isMeaningfulJSXText(child); + } + + function hasPrettierIgnore$4(path) { + return hasIgnoreComment$3(path) || hasJsxIgnoreComment(path); + } + + function isLastStatement(path) { + const parent = path.getParentNode(); + + if (!parent) { + return true; + } + + const node = path.getValue(); + const body = (parent.body || parent.consequent).filter(stmt => stmt.type !== "EmptyStatement"); + return body && body[body.length - 1] === node; + } + + function isFlowAnnotationComment(text, typeAnnotation, options) { + const start = options.locStart(typeAnnotation); + const end = skipWhitespace$2(text, options.locEnd(typeAnnotation)); + return text.slice(start, start + 2) === "/*" && text.slice(end, end + 2) === "*/"; + } + + function hasLeadingOwnLineComment(text, node, options) { + if (isJSXNode(node)) { + return hasNodeIgnoreComment$1(node); + } + + const res = node.comments && node.comments.some(comment => comment.leading && hasNewline$4(text, options.locEnd(comment))); + return res; + } // This recurses the return argument, looking for the first token + // (the leftmost leaf node) and, if it (or its parents) has any + // leadingComments, returns true (so it can be wrapped in parens). + + + function returnArgumentHasLeadingComment(options, argument) { + if (hasLeadingOwnLineComment(options.originalText, argument, options)) { + return true; + } + + if (hasNakedLeftSide(argument)) { + let leftMost = argument; + let newLeftMost; + + while (newLeftMost = getLeftSide(leftMost)) { + leftMost = newLeftMost; + + if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) { + return true; + } + } + } + + return false; + } + + function isStringPropSafeToCoerceToIdentifier(node, options) { + return isStringLiteral(node.key) && isIdentifierName(node.key.value) && options.parser !== "json" && // With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones. + // See https://github.com/microsoft/TypeScript/pull/20075 + !((options.parser === "typescript" || options.parser === "babel-ts") && node.type === "ClassProperty"); + } + + function isJestEachTemplateLiteral(node, parentNode) { + /** + * describe.each`table`(name, fn) + * describe.only.each`table`(name, fn) + * describe.skip.each`table`(name, fn) + * test.each`table`(name, fn) + * test.only.each`table`(name, fn) + * test.skip.each`table`(name, fn) + * + * Ref: https://github.com/facebook/jest/pull/6102 + */ + const jestEachTriggerRegex = /^[xf]?(describe|it|test)$/; + return parentNode.type === "TaggedTemplateExpression" && parentNode.quasi === node && parentNode.tag.type === "MemberExpression" && parentNode.tag.property.type === "Identifier" && parentNode.tag.property.name === "each" && (parentNode.tag.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.name) || parentNode.tag.object.type === "MemberExpression" && parentNode.tag.object.property.type === "Identifier" && (parentNode.tag.object.property.name === "only" || parentNode.tag.object.property.name === "skip") && parentNode.tag.object.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.object.name)); + } + + function templateLiteralHasNewLines(template) { + return template.quasis.some(quasi => quasi.value.raw.includes("\n")); + } + + function isTemplateOnItsOwnLine(n, text, options) { + return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$4(text, options.locStart(n), { + backwards: true + }); + } + + function needsHardlineAfterDanglingComment(node) { + if (!node.comments) { + return false; + } + + const lastDanglingComment = getLast$2(node.comments.filter(comment => !comment.leading && !comment.trailing)); + return lastDanglingComment && !comments$1.isBlockComment(lastDanglingComment); + } // If we have nested conditional expressions, we want to print them in JSX mode + // if there's at least one JSXElement somewhere in the tree. + // + // A conditional expression chain like this should be printed in normal mode, + // because there aren't JSXElements anywhere in it: + // + // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown"; + // + // But a conditional expression chain like this should be printed in JSX mode, + // because there is a JSXElement in the last ConditionalExpression: + // + // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>; + // + // This type of ConditionalExpression chain is structured like this in the AST: + // + // ConditionalExpression { + // test: ..., + // consequent: ..., + // alternate: ConditionalExpression { + // test: ..., + // consequent: ..., + // alternate: ConditionalExpression { + // test: ..., + // consequent: ..., + // alternate: ..., + // } + // } + // } + // + // We want to traverse over that shape and convert it into a flat structure so + // that we can find if there's a JSXElement somewhere inside. + + + function getConditionalChainContents(node) { + // Given this code: + // + // // Using a ConditionalExpression as the consequent is uncommon, but should + // // be handled. + // A ? B : C ? D : E ? F ? G : H : I + // + // which has this AST: + // + // ConditionalExpression { + // test: Identifier(A), + // consequent: Identifier(B), + // alternate: ConditionalExpression { + // test: Identifier(C), + // consequent: Identifier(D), + // alternate: ConditionalExpression { + // test: Identifier(E), + // consequent: ConditionalExpression { + // test: Identifier(F), + // consequent: Identifier(G), + // alternate: Identifier(H), + // }, + // alternate: Identifier(I), + // } + // } + // } + // + // we should return this Array: + // + // [ + // Identifier(A), + // Identifier(B), + // Identifier(C), + // Identifier(D), + // Identifier(E), + // Identifier(F), + // Identifier(G), + // Identifier(H), + // Identifier(I) + // ]; + // + // This loses the information about whether each node was the test, + // consequent, or alternate, but we don't care about that here- we are only + // flattening this structure to find if there's any JSXElements inside. + const nonConditionalExpressions = []; + + function recurse(node) { + if (node.type === "ConditionalExpression") { + recurse(node.test); + recurse(node.consequent); + recurse(node.alternate); + } else { + nonConditionalExpressions.push(node); + } + } + + recurse(node); + return nonConditionalExpressions; + } + + function conditionalExpressionChainContainsJSX(node) { + return Boolean(getConditionalChainContents(node).find(isJSXNode)); + } // Logic to check for args with multiple anonymous functions. For instance, + // the following call should be split on multiple lines for readability: + // source.pipe(map((x) => x + x), filter((x) => x % 2 === 0)) + + + function isFunctionCompositionArgs(args) { + if (args.length <= 1) { + return false; + } + + let count = 0; + + for (const arg of args) { + if (isFunctionOrArrowExpression(arg)) { + count += 1; + + if (count > 1) { + return true; + } + } else if (isCallOrOptionalCallExpression(arg)) { + for (const childArg of arg.arguments) { + if (isFunctionOrArrowExpression(childArg)) { + return true; + } + } + } + } + + return false; + } // Logic to determine if a call is a “long curried function callâ€. + // See https://github.com/prettier/prettier/issues/1420. + // + // `connect(a, b, c)(d)` + // In the above call expression, the second call is the parent node and the + // first call is the current node. + + + function isLongCurriedCallExpression(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0; + } + /** + * @param {import('estree').Node} node + * @param {number} depth + * @returns {boolean} + */ + + + function isSimpleCallArgument(node, depth) { + if (depth >= 2) { + return false; + } + + const isChildSimple = child => isSimpleCallArgument(child, depth + 1); + + const regexpPattern = node.type === "Literal" && node.regex && node.regex.pattern || node.type === "RegExpLiteral" && node.pattern; + + if (regexpPattern && regexpPattern.length > 5) { + return false; + } + + if (node.type === "Literal" || node.type === "BooleanLiteral" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "StringLiteral" || node.type === "Identifier" || node.type === "ThisExpression" || node.type === "Super" || node.type === "BigIntLiteral" || node.type === "PrivateName" || node.type === "ArgumentPlaceholder" || node.type === "RegExpLiteral" || node.type === "Import") { + return true; + } + + if (node.type === "TemplateLiteral") { + return node.expressions.every(isChildSimple); + } + + if (node.type === "ObjectExpression") { + return node.properties.every(p => !p.computed && (p.shorthand || p.value && isChildSimple(p.value))); + } + + if (node.type === "ArrayExpression") { + return node.elements.every(x => x == null || isChildSimple(x)); + } + + if (node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "NewExpression") { + return isSimpleCallArgument(node.callee, depth) && node.arguments.every(isChildSimple); + } + + if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") { + return isSimpleCallArgument(node.object, depth) && isSimpleCallArgument(node.property, depth); + } + + if (node.type === "UnaryExpression" && (node.operator === "!" || node.operator === "-")) { + return isSimpleCallArgument(node.argument, depth); + } + + if (node.type === "TSNonNullExpression") { + return isSimpleCallArgument(node.expression, depth); + } + + return false; + } + + function rawText(node) { + return node.extra ? node.extra.raw : node.raw; + } + + function identity$1(x) { + return x; + } + + function isTSXFile(options) { + return options.filepath && /\.tsx$/i.test(options.filepath); + } + + var utils$5 = { + classChildNeedsASIProtection, + classPropMayCauseASIProblems, + conditionalExpressionChainContainsJSX, + getFlowVariance, + getLeftSidePathName, + getParentExportDeclaration, + getTypeScriptMappedTypeModifier, + hasDanglingComments, + hasFlowAnnotationComment, + hasFlowShorthandAnnotationComment, + hasLeadingComment: hasLeadingComment$2, + hasLeadingOwnLineComment, + hasNakedLeftSide, + hasNewlineBetweenOrAfterDecorators, + hasNgSideEffect, + hasNode, + hasPrettierIgnore: hasPrettierIgnore$4, + hasTrailingComment, + identity: identity$1, + isBinaryish, + isCallOrOptionalCallExpression, + isEmptyJSXElement, + isExportDeclaration, + isFlowAnnotationComment, + isFunctionCompositionArgs, + isFunctionNotation, + isFunctionOrArrowExpression, + isGetterOrSetter, + isJestEachTemplateLiteral, + isJSXNode, + isJSXWhitespaceExpression, + isLastStatement, + isLiteral, + isLongCurriedCallExpression, + isSimpleCallArgument, + isMeaningfulJSXText, + isMemberExpressionChain, + isMemberish, + isNgForOf, + isNumericLiteral, + isObjectType, + isObjectTypePropertyAFunction, + isSimpleFlowType, + isSimpleTemplateLiteral, + isStringLiteral, + isStringPropSafeToCoerceToIdentifier, + isTemplateOnItsOwnLine, + isTestCall, + isTheOnlyJSXElementInMarkdown, + isTSXFile, + isTypeAnnotationAFunction, + matchJsxWhitespaceRegex, + needsHardlineAfterDanglingComment, + rawText, + returnArgumentHasLeadingComment + }; + + const { + getLeftSidePathName: getLeftSidePathName$1, + hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$1, + hasNakedLeftSide: hasNakedLeftSide$1, + hasNode: hasNode$1 + } = utils$5; + + function needsParens(path, options) { + const parent = path.getParentNode(); + + if (!parent) { + return false; + } + + const name = path.getName(); + const node = path.getNode(); // If the value of this path is some child of a Node and not a Node + // itself, then it doesn't need parentheses. Only Node objects (in + // fact, only Expression nodes) need parentheses. + + if (path.getValue() !== node) { + return false; + } // to avoid unexpected `}}` in HTML interpolations + + + if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) { + return true; + } // Only statements don't need parentheses. + + + if (isStatement(node)) { + return false; + } + + if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow + // parser. The Flow parser turns Flow comments into type annotation nodes in its + // AST, which we handle separately. + options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path.getValue())) { + return true; + } // Identifiers never need parentheses. + + + if (node.type === "Identifier") { + // ...unless those identifiers are embed placeholders. They might be substituted by complex + // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS): + // let tpl = html`<script> f((${expr}) / 2); </script>`; + // If the inner JS formatter removes the parens, the expression might change its meaning: + // f((a + b) / 2) vs f(a + b / 2) + if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) { + return true; + } + + return false; + } + + if (parent.type === "ParenthesizedExpression") { + return false; + } // Add parens around the extends clause of a class. It is needed for almost + // all expressions. + + + if ((parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node && (node.type === "ArrowFunctionExpression" || node.type === "AssignmentExpression" || node.type === "AwaitExpression" || node.type === "BinaryExpression" || node.type === "ConditionalExpression" || node.type === "LogicalExpression" || node.type === "NewExpression" || node.type === "ObjectExpression" || node.type === "ParenthesizedExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "UnaryExpression" || node.type === "UpdateExpression" || node.type === "YieldExpression")) { + return true; + } + + if (parent.type === "ExportDefaultDeclaration") { + return (// `export default function` or `export default class` can't be followed by + // anything after. So an expression like `export default (function(){}).toString()` + // needs to be followed by a parentheses + shouldWrapFunctionForExportDefault(path, options) || // `export default (foo, bar)` also needs parentheses + node.type === "SequenceExpression" + ); + } + + if (parent.type === "Decorator" && parent.expression === node) { + let hasCallExpression = false; + let hasMemberExpression = false; + let current = node; + + while (current) { + switch (current.type) { + case "MemberExpression": + hasMemberExpression = true; + current = current.object; + break; + + case "CallExpression": + if ( + /** @(x().y) */ + hasMemberExpression || + /** @(x().y()) */ + hasCallExpression) { + return true; + } + + hasCallExpression = true; + current = current.callee; + break; + + case "Identifier": + return false; + + default: + return true; + } + } + + return true; + } + + if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway + util$1.startsWithNoLookaheadToken(node, + /* forbidFunctionClassAndDoExpr */ + false) || parent.type === "ExpressionStatement" && util$1.startsWithNoLookaheadToken(node, + /* forbidFunctionClassAndDoExpr */ + true)) { + return true; + } + + switch (node.type) { + case "SpreadElement": + case "SpreadProperty": + return parent.type === "MemberExpression" && name === "object" && parent.object === node; + + case "UpdateExpression": + if (parent.type === "UnaryExpression") { + return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-"); + } + + // else fallthrough + + case "UnaryExpression": + switch (parent.type) { + case "UnaryExpression": + return node.operator === parent.operator && (node.operator === "+" || node.operator === "-"); + + case "BindExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "TaggedTemplateExpression": + return true; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "BinaryExpression": + return parent.operator === "**" && name === "left"; + + case "TSNonNullExpression": + return true; + + default: + return false; + } + + case "BinaryExpression": + { + if (parent.type === "UpdateExpression") { + return true; + } + + const isLeftOfAForStatement = node => { + let i = 0; + + while (node) { + const parent = path.getParentNode(i++); + + if (!parent) { + return false; + } + + if (parent.type === "ForStatement" && parent.init === node) { + return true; + } + + node = parent; + } + + return false; + }; + + if (node.operator === "in" && isLeftOfAForStatement(node)) { + return true; + } + } + // fallthrough + + case "TSTypeAssertion": + case "TSAsExpression": + case "LogicalExpression": + switch (parent.type) { + case "ConditionalExpression": + return node.type === "TSAsExpression"; + + case "CallExpression": + case "NewExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "ClassExpression": + case "ClassDeclaration": + return name === "superClass" && parent.superClass === node; + + case "TSTypeAssertion": + case "TaggedTemplateExpression": + case "UnaryExpression": + case "JSXSpreadAttribute": + case "SpreadElement": + case "SpreadProperty": + case "BindExpression": + case "AwaitExpression": + case "TSAsExpression": + case "TSNonNullExpression": + case "UpdateExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "AssignmentExpression": + return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression"); + + case "LogicalExpression": + if (node.type === "LogicalExpression") { + return parent.operator !== node.operator; + } + + // else fallthrough + + case "BinaryExpression": + { + if (!node.operator && node.type !== "TSTypeAssertion") { + return true; + } + + const po = parent.operator; + const pp = util$1.getPrecedence(po); + const no = node.operator; + const np = util$1.getPrecedence(no); + + if (pp > np) { + return true; + } + + if (pp === np && name === "right") { + assert.strictEqual(parent.right, node); + return true; + } + + if (pp === np && !util$1.shouldFlatten(po, no)) { + return true; + } + + if (pp < np && no === "%") { + return po === "+" || po === "-"; + } // Add parenthesis when working with bitwise operators + // It's not strictly needed but helps with code understanding + + + if (util$1.isBitwiseOperator(po)) { + return true; + } + + return false; + } + + default: + return false; + } + + case "SequenceExpression": + switch (parent.type) { + case "ReturnStatement": + return false; + + case "ForStatement": + // Although parentheses wouldn't hurt around sequence + // expressions in the head of for loops, traditional style + // dictates that e.g. i++, j++ should not be wrapped with + // parentheses. + return false; + + case "ExpressionStatement": + return name !== "expression"; + + case "ArrowFunctionExpression": + // We do need parentheses, but SequenceExpressions are handled + // specially when printing bodies of arrow functions. + return name !== "body"; + + default: + // Otherwise err on the side of overparenthesization, adding + // explicit exceptions above if this proves overzealous. + return true; + } + + case "YieldExpression": + if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") { + return true; + } + + // else fallthrough + + case "AwaitExpression": + switch (parent.type) { + case "TaggedTemplateExpression": + case "UnaryExpression": + case "BinaryExpression": + case "LogicalExpression": + case "SpreadElement": + case "SpreadProperty": + case "TSAsExpression": + case "TSNonNullExpression": + case "BindExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "ConditionalExpression": + return parent.test === node; + + default: + return false; + } + + case "TSJSDocFunctionType": + case "TSConditionalType": + if (parent.type === "TSConditionalType" && node === parent.extendsType) { + return true; + } + + // fallthrough + + case "TSFunctionType": + case "TSConstructorType": + if (parent.type === "TSConditionalType" && node === parent.checkType) { + return true; + } + + // fallthrough + + case "TSUnionType": + case "TSIntersectionType": + if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") { + return true; + } + + // fallthrough + + case "TSTypeOperator": + case "TSInferType": + return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || parent.type === "TSIndexedAccessType" && node === parent.objectType || parent.type === "TSTypeOperator" || parent.type === "TSTypeAnnotation" && /^TSJSDoc/.test(path.getParentNode(1).type); + + case "ArrayTypeAnnotation": + return parent.type === "NullableTypeAnnotation"; + + case "IntersectionTypeAnnotation": + case "UnionTypeAnnotation": + return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation"; + + case "NullableTypeAnnotation": + return parent.type === "ArrayTypeAnnotation"; + + case "FunctionTypeAnnotation": + { + const ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent; + return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses + // are really needed, but since ??T doesn't make sense this check + // will almost never be true. + ancestor.type === "NullableTypeAnnotation"; + } + + case "StringLiteral": + case "NumericLiteral": + case "Literal": + if (typeof node.value === "string" && parent.type === "ExpressionStatement" && ( // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2 + // See corresponding workaround in printer.js case: "Literal" + options.parser !== "typescript" && !parent.directive || options.parser === "typescript" && options.originalText.charAt(options.locStart(node) - 1) === "(")) { + // To avoid becoming a directive + const grandParent = path.getParentNode(1); + return grandParent.type === "Program" || grandParent.type === "BlockStatement"; + } + + return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node; + + case "AssignmentExpression": + { + const grandParent = path.getParentNode(1); + + if (parent.type === "ArrowFunctionExpression" && parent.body === node) { + return true; + } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) { + return false; + } else if (parent.type === "TSPropertySignature" && parent.name === node) { + return false; + } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) { + return false; + } else if (parent.type === "ExpressionStatement") { + return node.left.type === "ObjectPattern"; + } else if (parent.type === "TSPropertySignature" && parent.key === node) { + return false; + } else if (parent.type === "AssignmentExpression") { + return false; + } else if (parent.type === "SequenceExpression" && grandParent && grandParent.type === "ForStatement" && (grandParent.init === parent || grandParent.update === parent)) { + return false; + } else if (parent.type === "Property" && parent.value === node) { + return false; + } else if (parent.type === "NGChainedExpression") { + return false; + } + + return true; + } + + case "ConditionalExpression": + switch (parent.type) { + case "TaggedTemplateExpression": + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + case "BinaryExpression": + case "LogicalExpression": + case "NGPipeExpression": + case "ExportDefaultDeclaration": + case "AwaitExpression": + case "JSXSpreadAttribute": + case "TSTypeAssertion": + case "TypeCastExpression": + case "TSAsExpression": + case "TSNonNullExpression": + return true; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "ConditionalExpression": + return name === "test" && parent.test === node; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + default: + return false; + } + + case "FunctionExpression": + switch (parent.type) { + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses. + // Is necessary if it is `expression` of `ExpressionStatement`. + return name === "callee"; + + case "TaggedTemplateExpression": + return true; + // This is basically a kind of IIFE. + + default: + return false; + } + + case "ArrowFunctionExpression": + switch (parent.type) { + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "TSAsExpression": + case "BindExpression": + case "TaggedTemplateExpression": + case "UnaryExpression": + case "LogicalExpression": + case "BinaryExpression": + case "AwaitExpression": + case "TSTypeAssertion": + return true; + + case "ConditionalExpression": + return name === "test"; + + default: + return false; + } + + case "ClassExpression": + switch (parent.type) { + case "NewExpression": + return name === "callee" && parent.callee === node; + + default: + return false; + } + + case "OptionalMemberExpression": + case "OptionalCallExpression": + if (parent.type === "MemberExpression" && name === "object" || (parent.type === "CallExpression" || parent.type === "NewExpression") && name === "callee") { + return true; + } + + // fallthrough + + case "CallExpression": + case "MemberExpression": + case "TaggedTemplateExpression": + case "TSNonNullExpression": + if ((parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee") { + let object = node; + + while (object) { + switch (object.type) { + case "CallExpression": + case "OptionalCallExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + case "BindExpression": + object = object.object; + break; + // tagged templates are basically member expressions from a grammar perspective + // see https://tc39.github.io/ecma262/#prod-MemberExpression + + case "TaggedTemplateExpression": + object = object.tag; + break; + + case "TSNonNullExpression": + object = object.expression; + break; + + default: + return false; + } + } + } + + return false; + + case "BindExpression": + return (parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && name === "object"; + + case "NGPipeExpression": + if (parent.type === "NGRoot" || parent.type === "NGMicrosyntaxExpression" || parent.type === "ObjectProperty" || parent.type === "ArrayExpression" || (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.arguments[name] === node || parent.type === "NGPipeExpression" && name === "right" || parent.type === "MemberExpression" && name === "property" || parent.type === "AssignmentExpression") { + return false; + } + + return true; + + case "JSXFragment": + case "JSXElement": + return name === "callee" || parent.type !== "ArrayExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "AssignmentExpression" && parent.type !== "AssignmentPattern" && parent.type !== "BinaryExpression" && parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "ConditionalExpression" && parent.type !== "ExpressionStatement" && parent.type !== "JsExpressionRoot" && parent.type !== "JSXAttribute" && parent.type !== "JSXElement" && parent.type !== "JSXExpressionContainer" && parent.type !== "JSXFragment" && parent.type !== "LogicalExpression" && parent.type !== "ObjectProperty" && parent.type !== "OptionalCallExpression" && parent.type !== "Property" && parent.type !== "ReturnStatement" && parent.type !== "ThrowStatement" && parent.type !== "TypeCastExpression" && parent.type !== "VariableDeclarator" && parent.type !== "YieldExpression"; + + case "TypeAnnotation": + return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node); + } + + return false; + } + + function isStatement(node) { + return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "EnumDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "IfStatement" || node.type === "ImportDeclaration" || node.type === "InterfaceDeclaration" || node.type === "LabeledStatement" || node.type === "MethodDefinition" || node.type === "ReturnStatement" || node.type === "SwitchStatement" || node.type === "ThrowStatement" || node.type === "TryStatement" || node.type === "TSDeclareFunction" || node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSModuleDeclaration" || node.type === "TSNamespaceExportDeclaration" || node.type === "TypeAlias" || node.type === "VariableDeclaration" || node.type === "WhileStatement" || node.type === "WithStatement"; + } + + function includesFunctionTypeInObjectType(node) { + return hasNode$1(node, n1 => n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, n2 => n2.type === "FunctionTypeAnnotation" || undefined) || undefined); + } + + function endsWithRightBracket(node) { + switch (node.type) { + case "ObjectExpression": + return true; + + default: + return false; + } + } + + function isFollowedByRightBracket(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + const name = path.getName(); + + switch (parent.type) { + case "NGPipeExpression": + if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) { + return path.callParent(isFollowedByRightBracket); + } + + break; + + case "ObjectProperty": + if (name === "value") { + const parentParent = path.getParentNode(1); + return parentParent.properties[parentParent.properties.length - 1] === parent; + } + + break; + + case "BinaryExpression": + case "LogicalExpression": + if (name === "right") { + return path.callParent(isFollowedByRightBracket); + } + + break; + + case "ConditionalExpression": + if (name === "alternate") { + return path.callParent(isFollowedByRightBracket); + } + + break; + + case "UnaryExpression": + if (parent.prefix) { + return path.callParent(isFollowedByRightBracket); + } + + break; + } + + return false; + } + + function shouldWrapFunctionForExportDefault(path, options) { + const node = path.getValue(); + const parent = path.getParentNode(); + + if (node.type === "FunctionExpression" || node.type === "ClassExpression") { + return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped + // (e.g. `export default (function() {})();`) + // in this case we don't need to add extra parens + !needsParens(path, options); + } + + if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) { + return false; + } + + return path.call(childPath => shouldWrapFunctionForExportDefault(childPath, options), ...getLeftSidePathName$1(path, node)); + } + + var needsParens_1 = needsParens; + + const { + builders: { + concat: concat$c, + join: join$8, + line: line$8 + } + } = document; + + function printHtmlBinding(path, options, print) { + const node = path.getValue(); + + if (options.__onHtmlBindingRoot && path.getName() === null) { + options.__onHtmlBindingRoot(node, options); + } + + if (node.type !== "File") { + return; + } + + if (options.__isVueForBindingLeft) { + return path.call(functionDeclarationPath => { + const { + params + } = functionDeclarationPath.getValue(); + return concat$c([params.length > 1 ? "(" : "", join$8(concat$c([",", line$8]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]); + }, "program", "body", 0); + } + + if (options.__isVueSlotScope) { + return path.call(functionDeclarationPath => join$8(concat$c([",", line$8]), functionDeclarationPath.map(print, "params")), "program", "body", 0); + } + } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression() + + + function isVueEventBindingExpression$2(node) { + switch (node.type) { + case "MemberExpression": + switch (node.property.type) { + case "Identifier": + case "NumericLiteral": + case "StringLiteral": + return isVueEventBindingExpression$2(node.object); + } + + return false; + + case "Identifier": + return true; + + default: + return false; + } + } + + var htmlBinding = { + isVueEventBindingExpression: isVueEventBindingExpression$2, + printHtmlBinding + }; + + function preprocess$1(ast, options) { + switch (options.parser) { + case "json": + case "json5": + case "json-stringify": + case "__js_expression": + case "__vue_expression": + return Object.assign({}, ast, { + type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot", + node: ast, + comments: [], + rootMarker: options.rootMarker + }); + + default: + return ast; + } + } + + var preprocess_1$1 = preprocess$1; + + const { + shouldFlatten: shouldFlatten$1, + getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$1, + hasNewline: hasNewline$5, + hasNewlineInRange: hasNewlineInRange$3, + getLast: getLast$3, + getStringWidth: getStringWidth$3, + printString: printString$2, + printNumber: printNumber$2, + hasIgnoreComment: hasIgnoreComment$4, + hasNodeIgnoreComment: hasNodeIgnoreComment$2, + getPenultimate: getPenultimate$1, + startsWithNoLookaheadToken: startsWithNoLookaheadToken$1, + getIndentSize: getIndentSize$2, + getPreferredQuote: getPreferredQuote$1 + } = util$1; + const { + isNextLineEmpty: isNextLineEmpty$4, + isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$2, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$3 + } = utilShared; + const { + insertPragma: insertPragma$7 + } = pragma; + const { + printHtmlBinding: printHtmlBinding$1, + isVueEventBindingExpression: isVueEventBindingExpression$3 + } = htmlBinding; + const { + classChildNeedsASIProtection: classChildNeedsASIProtection$1, + classPropMayCauseASIProblems: classPropMayCauseASIProblems$1, + conditionalExpressionChainContainsJSX: conditionalExpressionChainContainsJSX$1, + getFlowVariance: getFlowVariance$1, + getLeftSidePathName: getLeftSidePathName$2, + getParentExportDeclaration: getParentExportDeclaration$1, + getTypeScriptMappedTypeModifier: getTypeScriptMappedTypeModifier$1, + hasDanglingComments: hasDanglingComments$1, + hasFlowAnnotationComment: hasFlowAnnotationComment$1, + hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$2, + hasLeadingComment: hasLeadingComment$3, + hasLeadingOwnLineComment: hasLeadingOwnLineComment$1, + hasNakedLeftSide: hasNakedLeftSide$2, + hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators$1, + hasNgSideEffect: hasNgSideEffect$1, + hasPrettierIgnore: hasPrettierIgnore$5, + hasTrailingComment: hasTrailingComment$1, + identity: identity$2, + isBinaryish: isBinaryish$1, + isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$1, + isEmptyJSXElement: isEmptyJSXElement$1, + isExportDeclaration: isExportDeclaration$1, + isFlowAnnotationComment: isFlowAnnotationComment$1, + isFunctionCompositionArgs: isFunctionCompositionArgs$1, + isFunctionNotation: isFunctionNotation$1, + isFunctionOrArrowExpression: isFunctionOrArrowExpression$1, + isGetterOrSetter: isGetterOrSetter$1, + isJestEachTemplateLiteral: isJestEachTemplateLiteral$1, + isJSXNode: isJSXNode$1, + isJSXWhitespaceExpression: isJSXWhitespaceExpression$1, + isLastStatement: isLastStatement$1, + isLiteral: isLiteral$1, + isLongCurriedCallExpression: isLongCurriedCallExpression$1, + isMeaningfulJSXText: isMeaningfulJSXText$1, + isMemberExpressionChain: isMemberExpressionChain$1, + isMemberish: isMemberish$1, + isNgForOf: isNgForOf$1, + isNumericLiteral: isNumericLiteral$1, + isObjectType: isObjectType$1, + isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$1, + isSimpleCallArgument: isSimpleCallArgument$1, + isSimpleFlowType: isSimpleFlowType$1, + isSimpleTemplateLiteral: isSimpleTemplateLiteral$1, + isStringLiteral: isStringLiteral$1, + isStringPropSafeToCoerceToIdentifier: isStringPropSafeToCoerceToIdentifier$1, + isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1, + isTestCall: isTestCall$1, + isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$1, + isTSXFile: isTSXFile$1, + isTypeAnnotationAFunction: isTypeAnnotationAFunction$1, + matchJsxWhitespaceRegex: matchJsxWhitespaceRegex$1, + needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1, + rawText: rawText$1, + returnArgumentHasLeadingComment: returnArgumentHasLeadingComment$1 + } = utils$5; + const needsQuoteProps = new WeakMap(); + const { + builders: { + concat: concat$d, + join: join$9, + line: line$9, + hardline: hardline$9, + softline: softline$6, + literalline: literalline$4, + group: group$b, + indent: indent$7, + align: align$1, + conditionalGroup: conditionalGroup$1, + fill: fill$4, + ifBreak: ifBreak$6, + breakParent: breakParent$3, + lineSuffixBoundary: lineSuffixBoundary$1, + addAlignmentToDoc: addAlignmentToDoc$2, + dedent: dedent$2 + }, + utils: { + willBreak: willBreak$1, + isLineNext: isLineNext$1, + isEmpty: isEmpty$1, + removeLines: removeLines$2 + }, + printer: { + printDocToString: printDocToString$2 + } + } = document; + let uid = 0; + + function shouldPrintComma$1(options, level) { + level = level || "es5"; + + switch (options.trailingComma) { + case "all": + if (level === "all") { + return true; + } + + // fallthrough + + case "es5": + if (level === "es5") { + return true; + } + + // fallthrough + + case "none": + default: + return false; + } + } + + function genericPrint$3(path, options, printPath, args) { + const node = path.getValue(); + let needsParens = false; + const linesWithoutParens = printPathNoParens(path, options, printPath, args); + + if (!node || isEmpty$1(linesWithoutParens)) { + return linesWithoutParens; + } + + const parentExportDecl = getParentExportDeclaration$1(path); + const decorators = []; + + if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition" || node.type === "TSDeclareMethod") ; else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator + // was written before the export, the export will be responsible + // for printing the decorators. + !(parentExportDecl && options.locStart(parentExportDecl, { + ignoreDecorators: true + }) > options.locStart(node.decorators[0]))) { + const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$1(node, options); + const separator = shouldBreak ? hardline$9 : line$9; + path.each(decoratorPath => { + let decorator = decoratorPath.getValue(); + + if (decorator.expression) { + decorator = decorator.expression; + } else { + decorator = decorator.callee; + } + + decorators.push(printPath(decoratorPath), separator); + }, "decorators"); + + if (parentExportDecl) { + decorators.unshift(hardline$9); + } + } else if (isExportDeclaration$1(node) && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0 && // Only print decorators here if they were written before the export, + // otherwise they are printed by the node.declaration + options.locStart(node, { + ignoreDecorators: true + }) > options.locStart(node.declaration.decorators[0])) { + // Export declarations are responsible for printing any decorators + // that logically apply to node.declaration. + path.each(decoratorPath => { + const decorator = decoratorPath.getValue(); + const prefix = decorator.type === "Decorator" ? "" : "@"; + decorators.push(prefix, printPath(decoratorPath), hardline$9); + }, "declaration", "decorators"); + } else { + // Nodes with decorators can't have parentheses, so we can avoid + // computing pathNeedsParens() except in this case. + needsParens = needsParens_1(path, options); + } + + const parts = []; + + if (needsParens) { + parts.unshift("("); + } + + parts.push(linesWithoutParens); + + if (needsParens) { + const node = path.getValue(); + + if (hasFlowShorthandAnnotationComment$2(node)) { + parts.push(" /*"); + parts.push(node.trailingComments[0].value.trimStart()); + parts.push("*/"); + node.trailingComments[0].printed = true; + } + + parts.push(")"); + } + + if (decorators.length > 0) { + return group$b(concat$d(decorators.concat(parts))); + } + + return concat$d(parts); + } + + function printDecorators(path, options, print) { + const node = path.getValue(); + return group$b(concat$d([join$9(line$9, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$9 : line$9])); + } + /** + * The following is the shared logic for + * ternary operators, namely ConditionalExpression + * and TSConditionalType + * @typedef {Object} OperatorOptions + * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`. + * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression. + * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode. + * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType". + * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent". + * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate". + * @property {string[]} testNodePropertyNames - The properties at which the test nodes can be found on the main node, eg "test". + * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node. + * @param {Options} options - Prettier options + * @param {Function} print - Print function to call recursively + * @param {OperatorOptions} operatorOptions + * @returns Doc + */ + + + function printTernaryOperator(path, options, print, operatorOptions) { + const node = path.getValue(); + const consequentNode = node[operatorOptions.consequentNodePropertyName]; + const alternateNode = node[operatorOptions.alternateNodePropertyName]; + const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode". + // See tests/jsx/conditional-expression.js for more info. + + let jsxMode = false; + const parent = path.getParentNode(); + const isParentTest = parent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.some(prop => parent[prop] === node); + let forceNoIndent = parent.type === operatorOptions.conditionalNodeType && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost + // ConditionalExpression parent. We'll use these to determine if we should + // print in JSX mode. + + let currentParent; + let previousParent; + let i = 0; + + do { + previousParent = currentParent || node; + currentParent = path.getParentNode(i); + i++; + } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.every(prop => currentParent[prop] !== previousParent)); + + const firstNonConditionalParent = currentParent || parent; + const lastConditionalParent = previousParent; + + if (operatorOptions.shouldCheckJsx && (isJSXNode$1(node[operatorOptions.testNodePropertyNames[0]]) || isJSXNode$1(consequentNode) || isJSXNode$1(alternateNode) || conditionalExpressionChainContainsJSX$1(lastConditionalParent))) { + jsxMode = true; + forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in + // parens when using ?: within JSX, because the parens are analogous to + // curly braces in an if statement. + + const wrap = doc => concat$d([ifBreak$6("(", ""), indent$7(concat$d([softline$6, doc])), softline$6, ifBreak$6(")", "")]); // The only things we don't wrap are: + // * Nested conditional expressions in alternates + // * null + // * undefined + + + const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined"; + + parts.push(" ? ", isNil(consequentNode) ? path.call(print, operatorOptions.consequentNodePropertyName) : wrap(path.call(print, operatorOptions.consequentNodePropertyName)), " : ", alternateNode.type === operatorOptions.conditionalNodeType || isNil(alternateNode) ? path.call(print, operatorOptions.alternateNodePropertyName) : wrap(path.call(print, operatorOptions.alternateNodePropertyName))); + } else { + // normal mode + const part = concat$d([line$9, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$6("", "(") : "", align$1(2, path.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$6("", ")") : "", line$9, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) : align$1(2, path.call(print, operatorOptions.alternateNodePropertyName))]); + parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$2(indent$7(part)) : align$1(Math.max(0, options.tabWidth - 2), part)); + } // We want a whole chain of ConditionalExpressions to all + // break if any of them break. That means we should only group around the + // outer-most ConditionalExpression. + + + const maybeGroup = doc => parent === firstNonConditionalParent ? group$b(doc) : doc; // Break the closing paren to keep the chain right after it: + // (a + // ? b + // : c + // ).call() + + + const breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed; + const result = maybeGroup(concat$d([].concat((testDoc => + /** + * a + * ? b + * : multiline + * test + * node + * ^^ align(2) + * ? d + * : e + */ + parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc)(concat$d(operatorOptions.beforeParts())), forceNoIndent ? concat$d(parts) : indent$7(concat$d(parts)), operatorOptions.afterParts(breakClosingParen)))); + return isParentTest ? group$b(concat$d([indent$7(concat$d([softline$6, result])), softline$6])) : result; + } + + function printPathNoParens(path, options, print, args) { + const n = path.getValue(); + const semi = options.semi ? ";" : ""; + + if (!n) { + return ""; + } + + if (typeof n === "string") { + return n; + } + + const htmlBinding = printHtmlBinding$1(path, options, print); + + if (htmlBinding) { + return htmlBinding; + } + + let parts = []; + + switch (n.type) { + case "JsExpressionRoot": + return path.call(print, "node"); + + case "JsonRoot": + return concat$d([path.call(print, "node"), hardline$9]); + + case "File": + // Print @babel/parser's InterpreterDirective here so that + // leading comments on the `Program` node get printed after the hashbang. + if (n.program && n.program.interpreter) { + parts.push(path.call(programPath => programPath.call(print, "interpreter"), "program")); + } + + parts.push(path.call(print, "program")); + return concat$d(parts); + + case "Program": + // Babel 6 + if (n.directives) { + path.each(childPath => { + parts.push(print(childPath), semi, hardline$9); + + if (isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) { + parts.push(hardline$9); + } + }, "directives"); + } + + parts.push(path.call(bodyPath => { + return printStatementSequence(bodyPath, options, print); + }, "body")); + parts.push(comments.printDanglingComments(path, options, + /* sameIndent */ + true)); // Only force a trailing newline if there were any contents. + + if (!n.body.every(({ + type + }) => type === "EmptyStatement") || n.comments) { + parts.push(hardline$9); + } + + return concat$d(parts); + // Babel extension. + + case "EmptyStatement": + return ""; + + case "ExpressionStatement": + // Detect Flow-parsed directives + if (n.directive) { + return concat$d([nodeStr(n.expression, options, true), semi]); + } + + if (options.parser === "__vue_event_binding") { + const parent = path.getParentNode(); + + if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) { + return concat$d([path.call(print, "expression"), isVueEventBindingExpression$3(n.expression) ? ";" : ""]); + } + } // Do not append semicolon after the only JSX element in a program + + + return concat$d([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$1(options, path) ? "" : semi]); + // Babel non-standard node. Used for Closure-style type casts. See postprocess.js. + + case "ParenthesizedExpression": + { + const shouldHug = !n.expression.comments; + + if (shouldHug) { + return concat$d(["(", path.call(print, "expression"), ")"]); + } + + return group$b(concat$d(["(", indent$7(concat$d([softline$6, path.call(print, "expression")])), softline$6, ")"])); + } + + case "AssignmentExpression": + return printAssignment(n.left, path.call(print, "left"), concat$d([" ", n.operator]), n.right, path.call(print, "right"), options); + + case "BinaryExpression": + case "LogicalExpression": + case "NGPipeExpression": + { + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + const isInsideParenthesis = n !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "SwitchStatement" || parent.type === "DoWhileStatement"); + const parts = printBinaryishExpressions(path, print, options, + /* isNested */ + false, isInsideParenthesis); // if ( + // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft + // ) { + // + // looks super weird, we want to break the children if the parent breaks + // + // if ( + // this.hasPlugin("dynamicImports") && + // this.lookahead().type === tt.parenLeft + // ) { + + if (isInsideParenthesis) { + return concat$d(parts); + } // Break between the parens in + // unaries or in a member or specific call expression, i.e. + // + // ( + // a && + // b && + // c + // ).call() + + + if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || parent.type === "UnaryExpression" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed) { + return group$b(concat$d([indent$7(concat$d([softline$6, concat$d(parts)])), softline$6])); + } // Avoid indenting sub-expressions in some cases where the first sub-expression is already + // indented accordingly. We should indent sub-expressions where the first case isn't indented. + + + const shouldNotIndent = parent.type === "ReturnStatement" || parent.type === "ThrowStatement" || parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || n.operator !== "|" && parent.type === "JsExpressionRoot" || n.type !== "NGPipeExpression" && (parent.type === "NGRoot" && options.parser === "__ng_binding" || parent.type === "NGMicrosyntaxExpression" && parentParent.type === "NGMicrosyntax" && parentParent.body.length === 1) || n === parent.body && parent.type === "ArrowFunctionExpression" || n !== parent.body && parent.type === "ForStatement" || parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement" && parentParent.type !== "ThrowStatement" && parentParent.type !== "CallExpression" && parentParent.type !== "OptionalCallExpression" || parent.type === "TemplateLiteral"; + const shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || parent.type === "ObjectProperty" || parent.type === "Property"; + const samePrecedenceSubExpression = isBinaryish$1(n.left) && shouldFlatten$1(n.operator, n.left.operator); + + if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) { + return group$b(concat$d(parts)); + } + + if (parts.length === 0) { + return ""; + } // If the right part is a JSX node, we include it in a separate group to + // prevent it breaking the whole chain, so we can print the expression like: + // + // foo && bar && ( + // <Foo> + // <Bar /> + // </Foo> + // ) + + + const hasJSX = isJSXNode$1(n.right); + const rest = concat$d(hasJSX ? parts.slice(1, -1) : parts.slice(1)); + const groupId = Symbol("logicalChain-" + ++uid); + const chain = group$b(concat$d([// Don't include the initial expression in the indentation + // level. The first item is guaranteed to be the first + // left-most expression. + parts.length > 0 ? parts[0] : "", indent$7(rest)]), { + id: groupId + }); + + if (!hasJSX) { + return chain; + } + + const jsxPart = getLast$3(parts); + return group$b(concat$d([chain, ifBreak$6(indent$7(jsxPart), jsxPart, { + groupId + })])); + } + + case "AssignmentPattern": + return concat$d([path.call(print, "left"), " = ", path.call(print, "right")]); + + case "TSTypeAssertion": + { + const shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression"); + const castGroup = group$b(concat$d(["<", indent$7(concat$d([softline$6, path.call(print, "typeAnnotation")])), softline$6, ">"])); + const exprContents = concat$d([ifBreak$6("("), indent$7(concat$d([softline$6, path.call(print, "expression")])), softline$6, ifBreak$6(")")]); + + if (shouldBreakAfterCast) { + return conditionalGroup$1([concat$d([castGroup, path.call(print, "expression")]), concat$d([castGroup, group$b(exprContents, { + shouldBreak: true + })]), concat$d([castGroup, path.call(print, "expression")])]); + } + + return group$b(concat$d([castGroup, path.call(print, "expression")])); + } + + case "OptionalMemberExpression": + case "MemberExpression": + { + const parent = path.getParentNode(); + let firstNonMemberParent; + let i = 0; + + do { + firstNonMemberParent = path.getParentNode(i); + i++; + } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression")); + + const shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "VariableDeclarator" && firstNonMemberParent.id.type !== "Identifier" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || n.computed || n.object.type === "Identifier" && n.property.type === "Identifier" && parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression"; + return concat$d([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$b(indent$7(concat$d([softline$6, printMemberLookup(path, options, print)])))]); + } + + case "MetaProperty": + return concat$d([path.call(print, "meta"), ".", path.call(print, "property")]); + + case "BindExpression": + if (n.object) { + parts.push(path.call(print, "object")); + } + + parts.push(group$b(indent$7(concat$d([softline$6, printBindExpressionCallee(path, options, print)])))); + return concat$d(parts); + + case "Identifier": + { + return concat$d([n.name, printOptionalToken(path), printTypeAnnotation(path, options, print)]); + } + + case "V8IntrinsicIdentifier": + return concat$d(["%", n.name]); + + case "SpreadElement": + case "SpreadElementPattern": + case "SpreadProperty": + case "SpreadPropertyPattern": + case "RestElement": + case "ObjectTypeSpreadProperty": + return concat$d(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]); + + case "FunctionDeclaration": + case "FunctionExpression": + parts.push(printFunctionDeclaration(path, print, options)); + + if (!n.body) { + parts.push(semi); + } + + return concat$d(parts); + + case "ArrowFunctionExpression": + { + if (n.async) { + parts.push("async "); + } + + if (shouldPrintParamsWithoutParens(path, options)) { + parts.push(path.call(print, "params", 0)); + } else { + parts.push(group$b(concat$d([printFunctionParams(path, print, options, + /* expandLast */ + args && (args.expandLastArg || args.expandFirstArg), + /* printTypeParams */ + true), printReturnType(path, print, options)]))); + } + + const dangling = comments.printDanglingComments(path, options, + /* sameIndent */ + true, comment => { + const nextCharacter = getNextNonSpaceNonCommentCharacterIndex$3(options.originalText, comment, options.locEnd); + return options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>"; + }); + + if (dangling) { + parts.push(" ", dangling); + } + + parts.push(" =>"); + const body = path.call(bodyPath => print(bodyPath, args), "body"); // We want to always keep these types of nodes on the same line + // as the arrow. + + if (!hasLeadingOwnLineComment$1(options.originalText, n.body, options) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode$1(n.body) || isTemplateOnItsOwnLine$1(n.body, options.originalText, options) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) { + return group$b(concat$d([concat$d(parts), " ", body])); + } // We handle sequence expressions as the body of arrows specially, + // so that the required parentheses end up on their own lines. + + + if (n.body.type === "SequenceExpression") { + return group$b(concat$d([concat$d(parts), group$b(concat$d([" (", indent$7(concat$d([softline$6, body])), softline$6, ")"]))])); + } // if the arrow function is expanded as last argument, we are adding a + // level of indentation and need to add a softline to align the closing ) + // with the opening (, or if it's inside a JSXExpression (e.g. an attribute) + // we should align the expression's closing } with the line with the opening {. + + + const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length); + const printTrailingComma = args && args.expandLastArg && shouldPrintComma$1(options, "all"); // In order to avoid confusion between + // a => a ? a : a + // a <= a ? a : a + + const shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$1(n.body, + /* forbidFunctionAndClass */ + false); + return group$b(concat$d([concat$d(parts), group$b(concat$d([indent$7(concat$d([line$9, shouldAddParens ? ifBreak$6("", "(") : "", body, shouldAddParens ? ifBreak$6("", ")") : ""])), shouldAddSoftLine ? concat$d([ifBreak$6(printTrailingComma ? "," : ""), softline$6]) : ""]))])); + } + + case "YieldExpression": + parts.push("yield"); + + if (n.delegate) { + parts.push("*"); + } + + if (n.argument) { + parts.push(" ", path.call(print, "argument")); + } + + return concat$d(parts); + + case "AwaitExpression": + { + parts.push("await ", path.call(print, "argument")); + const parent = path.getParentNode(); + + if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && parent.object === n) { + return group$b(concat$d([indent$7(concat$d([softline$6, concat$d(parts)])), softline$6])); + } + + return concat$d(parts); + } + + case "ImportSpecifier": + if (n.importKind) { + parts.push(path.call(print, "importKind"), " "); + } + + parts.push(path.call(print, "imported")); + + if (n.local && n.local.name !== n.imported.name) { + parts.push(" as ", path.call(print, "local")); + } + + return concat$d(parts); + + case "ExportSpecifier": + parts.push(path.call(print, "local")); + + if (n.exported && n.exported.name !== n.local.name) { + parts.push(" as ", path.call(print, "exported")); + } + + return concat$d(parts); + + case "ImportNamespaceSpecifier": + parts.push("* as "); + parts.push(path.call(print, "local")); + return concat$d(parts); + + case "ImportDefaultSpecifier": + return path.call(print, "local"); + + case "TSExportAssignment": + return concat$d(["export = ", path.call(print, "expression"), semi]); + + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + return printExportDeclaration(path, options, print); + + case "ExportAllDeclaration": + parts.push("export "); + + if (n.exportKind === "type") { + parts.push("type "); + } + + parts.push("* "); + + if (n.exported) { + parts.push("as ", path.call(print, "exported"), " "); + } + + parts.push("from ", path.call(print, "source"), semi); + return concat$d(parts); + + case "ExportNamespaceSpecifier": + case "ExportDefaultSpecifier": + return path.call(print, "exported"); + + case "ImportDeclaration": + { + parts.push("import "); + + if (n.importKind && n.importKind !== "value") { + parts.push(n.importKind + " "); + } + + const standalones = []; + const grouped = []; + + if (n.specifiers && n.specifiers.length > 0) { + path.each(specifierPath => { + const value = specifierPath.getValue(); + + if (value.type === "ImportDefaultSpecifier" || value.type === "ImportNamespaceSpecifier") { + standalones.push(print(specifierPath)); + } else { + grouped.push(print(specifierPath)); + } + }, "specifiers"); + + if (standalones.length > 0) { + parts.push(join$9(", ", standalones)); + } + + if (standalones.length > 0 && grouped.length > 0) { + parts.push(", "); + } + + if (grouped.length === 1 && standalones.length === 0 && n.specifiers && !n.specifiers.some(node => node.comments)) { + parts.push(concat$d(["{", options.bracketSpacing ? " " : "", concat$d(grouped), options.bracketSpacing ? " " : "", "}"])); + } else if (grouped.length >= 1) { + parts.push(group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, join$9(concat$d([",", line$9]), grouped)])), ifBreak$6(shouldPrintComma$1(options) ? "," : ""), options.bracketSpacing ? line$9 : softline$6, "}"]))); + } + + parts.push(" from "); + } else if (n.importKind && n.importKind === "type" || // import {} from 'x' + /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) { + parts.push("{} from "); + } + + parts.push(path.call(print, "source"), semi); + return concat$d(parts); + } + + case "Import": + return "import"; + + case "TSModuleBlock": + case "BlockStatement": + { + const naked = path.call(bodyPath => { + return printStatementSequence(bodyPath, options, print); + }, "body"); + const hasContent = n.body.find(node => node.type !== "EmptyStatement"); + const hasDirectives = n.directives && n.directives.length > 0; + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + + if (!hasContent && !hasDirectives && !hasDanglingComments$1(n) && (parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration")) { + return "{}"; + } + + parts.push("{"); // Babel 6 + + if (hasDirectives) { + path.each(childPath => { + parts.push(indent$7(concat$d([hardline$9, print(childPath), semi]))); + + if (isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) { + parts.push(hardline$9); + } + }, "directives"); + } + + if (hasContent) { + parts.push(indent$7(concat$d([hardline$9, naked]))); + } + + parts.push(comments.printDanglingComments(path, options)); + parts.push(hardline$9, "}"); + return concat$d(parts); + } + + case "ReturnStatement": + return concat$d(["return", printReturnAndThrowArgument(path, options, print)]); + + case "NewExpression": + case "OptionalCallExpression": + case "CallExpression": + { + const isNew = n.type === "NewExpression"; + const optional = printOptionalToken(path); + + if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style + // define calls, as a unit. + // e.g. `define(["some/lib", (lib) => {` + !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments + n.arguments.length === 1 && isTemplateOnItsOwnLine$1(n.arguments[0], options.originalText, options) || // Keep test declarations on a single line + // e.g. `it('long name', () => {` + !isNew && isTestCall$1(n, path.getParentNode())) { + return concat$d([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), concat$d(["(", join$9(", ", path.map(print, "arguments")), ")"])]); + } // Inline Flow annotation comments following Identifiers in Call nodes need to + // stay with the Identifier. For example: + // + // foo /*:: <SomeGeneric> */(bar); + // + // Here, we ensure that such comments stay between the Identifier and the Callee. + + + const isIdentifierWithFlowAnnotation = n.callee.type === "Identifier" && hasFlowAnnotationComment$1(n.callee.trailingComments); + + if (isIdentifierWithFlowAnnotation) { + n.callee.trailingComments[0].printed = true; + } // We detect calls on member lookups and possibly print them in a + // special chain format. See `printMemberChain` for more info. + + + if (!isNew && isMemberish$1(n.callee) && !path.call(path => needsParens_1(path, options), "callee")) { + return printMemberChain(path, options, print); + } + + const contents = concat$d([isNew ? "new " : "", path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? "/*:: ".concat(n.callee.trailingComments[0].value.slice(2).trim(), " */") : "", printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]); // We group here when the callee is itself a call expression. + // See `isLongCurriedCallExpression` for more info. + + if (isCallOrOptionalCallExpression$1(n.callee)) { + return group$b(contents); + } + + return contents; + } + + case "TSInterfaceDeclaration": + if (n.declare) { + parts.push("declare "); + } + + parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print), "interface ", path.call(print, "id"), n.typeParameters ? path.call(print, "typeParameters") : "", " "); + + if (n.extends && n.extends.length) { + parts.push(group$b(indent$7(concat$d([softline$6, "extends ", (n.extends.length === 1 ? identity$2 : indent$7)(join$9(concat$d([",", line$9]), path.map(print, "extends"))), " "])))); + } + + parts.push(path.call(print, "body")); + return concat$d(parts); + + case "ObjectTypeInternalSlot": + return concat$d([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken(path), n.method ? "" : ": ", path.call(print, "value")]); + + case "ObjectExpression": + case "ObjectPattern": + case "ObjectTypeAnnotation": + case "TSInterfaceBody": + case "TSTypeLiteral": + { + let propertiesField; + + if (n.type === "TSTypeLiteral") { + propertiesField = "members"; + } else if (n.type === "TSInterfaceBody") { + propertiesField = "body"; + } else { + propertiesField = "properties"; + } + + const isTypeAnnotation = n.type === "ObjectTypeAnnotation"; + const fields = []; + + if (isTypeAnnotation) { + fields.push("indexers", "callProperties", "internalSlots"); + } + + fields.push(propertiesField); + const firstProperty = fields.map(field => n[field][0]).sort((a, b) => options.locStart(a) - options.locStart(b))[0]; + const parent = path.getParentNode(0); + const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body"; + const shouldBreak = n.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || n.type === "ObjectPattern" && parent.type !== "FunctionDeclaration" && parent.type !== "FunctionExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "ObjectMethod" && parent.type !== "ClassMethod" && parent.type !== "ClassPrivateMethod" && parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && n.properties.some(property => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern")) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$3(options.originalText, options.locStart(n), options.locStart(firstProperty)); + const separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$6(semi, ";") : ","; + const leftBrace = n.exact ? "{|" : "{"; + const rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be + // interleaved in the source code. So we need to reorder them before + // printing them. + + const propsAndLoc = []; + fields.forEach(field => { + path.each(childPath => { + const node = childPath.getValue(); + propsAndLoc.push({ + node, + printed: print(childPath), + loc: options.locStart(node) + }); + }, field); + }); + let separatorParts = []; + const props = propsAndLoc.sort((a, b) => a.loc - b.loc).map(prop => { + const result = concat$d(separatorParts.concat(group$b(prop.printed))); + separatorParts = [separator, line$9]; + + if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$2(prop.node)) { + separatorParts.shift(); + } + + if (isNextLineEmpty$4(options.originalText, prop.node, options.locEnd)) { + separatorParts.push(hardline$9); + } + + return result; + }); + + if (n.inexact) { + let printed; + + if (hasDanglingComments$1(n)) { + const hasLineComments = !n.comments.every(comments$1.isBlockComment); + const printedDanglingComments = comments.printDanglingComments(path, options, + /* sameIndent */ + true); + printed = concat$d([printedDanglingComments, hasLineComments || hasNewline$5(options.originalText, options.locEnd(n.comments[n.comments.length - 1])) ? hardline$9 : line$9, "..."]); + } else { + printed = "..."; + } + + props.push(concat$d(separatorParts.concat(printed))); + } + + const lastElem = getLast$3(n[propertiesField]); + const canHaveTrailingSeparator = !(n.inexact || lastElem && (lastElem.type === "RestElement" || hasNodeIgnoreComment$2(lastElem))); + let content; + + if (props.length === 0) { + if (!hasDanglingComments$1(n)) { + return concat$d([leftBrace, rightBrace, printTypeAnnotation(path, options, print)]); + } + + content = group$b(concat$d([leftBrace, comments.printDanglingComments(path, options), softline$6, rightBrace, printOptionalToken(path), printTypeAnnotation(path, options, print)])); + } else { + content = concat$d([leftBrace, indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, concat$d(props)])), ifBreak$6(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma$1(options)) ? separator : ""), concat$d([options.bracketSpacing ? line$9 : softline$6, rightBrace]), printOptionalToken(path), printTypeAnnotation(path, options, print)]); + } // If we inline the object as first argument of the parent, we don't want + // to create another group so that the object breaks before the return + // type + + + if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0) || path.match(shouldHugType, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0)) { + return content; + } + + return group$b(content, { + shouldBreak + }); + } + // Babel 6 + + case "ObjectProperty": // Non-standard AST node type. + + case "Property": + if (n.method || n.kind === "get" || n.kind === "set") { + return printMethod(path, options, print); + } + + if (n.shorthand) { + parts.push(path.call(print, "value")); + } else { + parts.push(printAssignment(n.key, printPropertyKey(path, options, print), ":", n.value, path.call(print, "value"), options)); + } + + return concat$d(parts); + // Babel 6 + + case "ClassMethod": + case "ClassPrivateMethod": + case "MethodDefinition": + case "TSAbstractMethodDefinition": + case "TSDeclareMethod": + if (n.decorators && n.decorators.length !== 0) { + parts.push(printDecorators(path, options, print)); + } + + if (n.accessibility) { + parts.push(n.accessibility + " "); + } + + if (n.static) { + parts.push("static "); + } + + if (n.type === "TSAbstractMethodDefinition" || n.abstract) { + parts.push("abstract "); + } + + parts.push(printMethod(path, options, print)); + return concat$d(parts); + + case "ObjectMethod": + return printMethod(path, options, print); + + case "Decorator": + return concat$d(["@", path.call(print, "expression"), path.call(print, "callee")]); + + case "ArrayExpression": + case "ArrayPattern": + if (n.elements.length === 0) { + if (!hasDanglingComments$1(n)) { + parts.push("[]"); + } else { + parts.push(group$b(concat$d(["[", comments.printDanglingComments(path, options), softline$6, "]"]))); + } + } else { + const lastElem = getLast$3(n.elements); + const canHaveTrailingComma = !(lastElem && lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which + // changes its length based on the number of commas. The algorithm + // is that if the last argument is null, we need to force insert + // a comma to ensure JavaScript recognizes it. + // [,].length === 1 + // [1,].length === 1 + // [1,,].length === 2 + // + // Note that getLast returns null if the array is empty, but + // we already check for an empty array just above so we are safe + + const needsForcedTrailingComma = canHaveTrailingComma && lastElem === null; + const shouldBreak = n.elements.length > 1 && n.elements.every((element, i, elements) => { + const elementType = element && element.type; + + if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") { + return false; + } + + const nextElement = elements[i + 1]; + + if (nextElement && elementType !== nextElement.type) { + return false; + } + + const itemsKey = elementType === "ArrayExpression" ? "elements" : "properties"; + return element[itemsKey] && element[itemsKey].length > 1; + }); + parts.push(group$b(concat$d(["[", indent$7(concat$d([softline$6, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$6(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma$1(options) ? "," : ""), comments.printDanglingComments(path, options, + /* sameIndent */ + true), softline$6, "]"]), { + shouldBreak + })); + } + + parts.push(printOptionalToken(path), printTypeAnnotation(path, options, print)); + return concat$d(parts); + + case "SequenceExpression": + { + const parent = path.getParentNode(0); + + if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") { + // For ExpressionStatements and for-loop heads, which are among + // the few places a SequenceExpression appears unparenthesized, we want + // to indent expressions after the first. + const parts = []; + path.each(p => { + if (p.getName() === 0) { + parts.push(print(p)); + } else { + parts.push(",", indent$7(concat$d([line$9, print(p)]))); + } + }, "expressions"); + return group$b(concat$d(parts)); + } + + return group$b(concat$d([join$9(concat$d([",", line$9]), path.map(print, "expressions"))])); + } + + case "ThisExpression": + return "this"; + + case "Super": + return "super"; + + case "NullLiteral": + // Babel 6 Literal split + return "null"; + + case "RegExpLiteral": + // Babel 6 Literal split + return printRegex(n); + + case "NumericLiteral": + // Babel 6 Literal split + return printNumber$2(n.extra.raw); + + case "BigIntLiteral": + // babel: n.extra.raw, typescript: n.raw, flow: n.bigint + return (n.bigint || (n.extra ? n.extra.raw : n.raw)).toLowerCase(); + + case "BooleanLiteral": // Babel 6 Literal split + + case "StringLiteral": // Babel 6 Literal split + + case "Literal": + { + if (n.regex) { + return printRegex(n.regex); + } + + if (typeof n.value === "number") { + return printNumber$2(n.raw); + } + + if (typeof n.value !== "string") { + return "" + n.value; + } // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2 + // See corresponding workaround in needs-parens.js + + + const grandParent = path.getParentNode(1); + const isTypeScriptDirective = options.parser === "typescript" && typeof n.value === "string" && grandParent && (grandParent.type === "Program" || grandParent.type === "BlockStatement"); + return nodeStr(n, options, isTypeScriptDirective); + } + + case "Directive": + return path.call(print, "value"); + // Babel 6 + + case "DirectiveLiteral": + return nodeStr(n, options); + + case "UnaryExpression": + parts.push(n.operator); + + if (/[a-z]$/.test(n.operator)) { + parts.push(" "); + } + + if (n.argument.comments && n.argument.comments.length > 0) { + parts.push(group$b(concat$d(["(", indent$7(concat$d([softline$6, path.call(print, "argument")])), softline$6, ")"]))); + } else { + parts.push(path.call(print, "argument")); + } + + return concat$d(parts); + + case "UpdateExpression": + parts.push(path.call(print, "argument"), n.operator); + + if (n.prefix) { + parts.reverse(); + } + + return concat$d(parts); + + case "ConditionalExpression": + return printTernaryOperator(path, options, print, { + beforeParts: () => [path.call(print, "test")], + afterParts: breakClosingParen => [breakClosingParen ? softline$6 : ""], + shouldCheckJsx: true, + conditionalNodeType: "ConditionalExpression", + consequentNodePropertyName: "consequent", + alternateNodePropertyName: "alternate", + testNodePropertyNames: ["test"] + }); + + case "VariableDeclaration": + { + const printed = path.map(childPath => { + return print(childPath); + }, "declarations"); // We generally want to terminate all variable declarations with a + // semicolon, except when they in the () part of for loops. + + const parentNode = path.getParentNode(); + const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement"; + const hasValue = n.declarations.some(decl => decl.init); + let firstVariable; + + if (printed.length === 1 && !n.declarations[0].comments) { + firstVariable = printed[0]; + } else if (printed.length > 0) { + // Indent first var to comply with eslint one-var rule + firstVariable = indent$7(printed[0]); + } + + parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$d([" ", firstVariable]) : "", indent$7(concat$d(printed.slice(1).map(p => concat$d([",", hasValue && !isParentForLoop ? hardline$9 : line$9, p]))))]; + + if (!(isParentForLoop && parentNode.body !== n)) { + parts.push(semi); + } + + return group$b(concat$d(parts)); + } + + case "TSTypeAliasDeclaration": + { + if (n.declare) { + parts.push("declare "); + } + + const printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options); + parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi); + return group$b(concat$d(parts)); + } + + case "VariableDeclarator": + return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options); + + case "WithStatement": + return group$b(concat$d(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))])); + + case "IfStatement": + { + const con = adjustClause(n.consequent, path.call(print, "consequent")); + const opening = group$b(concat$d(["if (", group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "test")])), softline$6])), ")", con])); + parts.push(opening); + + if (n.alternate) { + const commentOnOwnLine = hasTrailingComment$1(n.consequent) && n.consequent.comments.some(comment => comment.trailing && !comments$1.isBlockComment(comment)) || needsHardlineAfterDanglingComment$1(n); + const elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine; + parts.push(elseOnSameLine ? " " : hardline$9); + + if (hasDanglingComments$1(n)) { + parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$9 : " "); + } + + parts.push("else", group$b(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement"))); + } + + return concat$d(parts); + } + + case "ForStatement": + { + const body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent. + // Any comment positioned between the for statement and the parentheses + // is going to be printed before the statement. + + const dangling = comments.printDanglingComments(path, options, + /* sameLine */ + true); + const printedComments = dangling ? concat$d([dangling, softline$6]) : ""; + + if (!n.init && !n.test && !n.update) { + return concat$d([printedComments, group$b(concat$d(["for (;;)", body]))]); + } + + return concat$d([printedComments, group$b(concat$d(["for (", group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "init"), ";", line$9, path.call(print, "test"), ";", line$9, path.call(print, "update")])), softline$6])), ")", body]))]); + } + + case "WhileStatement": + return group$b(concat$d(["while (", group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "test")])), softline$6])), ")", adjustClause(n.body, path.call(print, "body"))])); + + case "ForInStatement": + // Note: esprima can't actually parse "for each (". + return group$b(concat$d([n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))])); + + case "ForOfStatement": + return group$b(concat$d(["for", n.await ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))])); + + case "DoWhileStatement": + { + const clause = adjustClause(n.body, path.call(print, "body")); + const doBody = group$b(concat$d(["do", clause])); + parts = [doBody]; + + if (n.body.type === "BlockStatement") { + parts.push(" "); + } else { + parts.push(hardline$9); + } + + parts.push("while ("); + parts.push(group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "test")])), softline$6])), ")", semi); + return concat$d(parts); + } + + case "DoExpression": + return concat$d(["do ", path.call(print, "body")]); + + case "BreakStatement": + parts.push("break"); + + if (n.label) { + parts.push(" ", path.call(print, "label")); + } + + parts.push(semi); + return concat$d(parts); + + case "ContinueStatement": + parts.push("continue"); + + if (n.label) { + parts.push(" ", path.call(print, "label")); + } + + parts.push(semi); + return concat$d(parts); + + case "LabeledStatement": + if (n.body.type === "EmptyStatement") { + return concat$d([path.call(print, "label"), ":;"]); + } + + return concat$d([path.call(print, "label"), ": ", path.call(print, "body")]); + + case "TryStatement": + return concat$d(["try ", path.call(print, "block"), n.handler ? concat$d([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$d([" finally ", path.call(print, "finalizer")]) : ""]); + + case "CatchClause": + if (n.param) { + const hasComments = n.param.comments && n.param.comments.some(comment => !comments$1.isBlockComment(comment) || comment.leading && hasNewline$5(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$5(options.originalText, options.locStart(comment), { + backwards: true + })); + const param = path.call(print, "param"); + return concat$d(["catch ", hasComments ? concat$d(["(", indent$7(concat$d([softline$6, param])), softline$6, ") "]) : concat$d(["(", param, ") "]), path.call(print, "body")]); + } + + return concat$d(["catch ", path.call(print, "body")]); + + case "ThrowStatement": + return concat$d(["throw", printReturnAndThrowArgument(path, options, print)]); + // Note: ignoring n.lexical because it has no printing consequences. + + case "SwitchStatement": + return concat$d([group$b(concat$d(["switch (", indent$7(concat$d([softline$6, path.call(print, "discriminant")])), softline$6, ")"])), " {", n.cases.length > 0 ? indent$7(concat$d([hardline$9, join$9(hardline$9, path.map(casePath => { + const caseNode = casePath.getValue(); + return concat$d([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$4(options.originalText, caseNode, options.locEnd) ? hardline$9 : ""]); + }, "cases"))])) : "", hardline$9, "}"]); + + case "SwitchCase": + { + if (n.test) { + parts.push("case ", path.call(print, "test"), ":"); + } else { + parts.push("default:"); + } + + const consequent = n.consequent.filter(node => node.type !== "EmptyStatement"); + + if (consequent.length > 0) { + const cons = path.call(consequentPath => { + return printStatementSequence(consequentPath, options, print); + }, "consequent"); + parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$d([" ", cons]) : indent$7(concat$d([hardline$9, cons]))); + } + + return concat$d(parts); + } + // JSX extensions below. + + case "DebuggerStatement": + return concat$d(["debugger", semi]); + + case "JSXAttribute": + parts.push(path.call(print, "name")); + + if (n.value) { + let res; + + if (isStringLiteral$1(n.value)) { + const raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote + + let final = raw.replace(/'/g, "'").replace(/"/g, '"'); + const quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"'); + const escape = quote === "'" ? "'" : """; + final = final.slice(1, -1).replace(new RegExp(quote, "g"), escape); + res = concat$d([quote, final, quote]); + } else { + res = path.call(print, "value"); + } + + parts.push("=", res); + } + + return concat$d(parts); + + case "JSXIdentifier": + return "" + n.name; + + case "JSXNamespacedName": + return join$9(":", [path.call(print, "namespace"), path.call(print, "name")]); + + case "JSXMemberExpression": + return join$9(".", [path.call(print, "object"), path.call(print, "property")]); + + case "TSQualifiedName": + return join$9(".", [path.call(print, "left"), path.call(print, "right")]); + + case "JSXSpreadAttribute": + case "JSXSpreadChild": + { + return concat$d(["{", path.call(p => { + const printed = concat$d(["...", print(p)]); + const n = p.getValue(); + + if (!n.comments || !n.comments.length) { + return printed; + } + + return concat$d([indent$7(concat$d([softline$6, comments.printComments(p, () => printed, options)])), softline$6]); + }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]); + } + + case "JSXExpressionContainer": + { + const parent = path.getParentNode(0); + const hasComments = n.expression.comments && n.expression.comments.length > 0; + const shouldInline = n.expression.type === "JSXEmptyExpression" || !hasComments && (n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression" || n.expression.type === "ArrowFunctionExpression" || n.expression.type === "CallExpression" || n.expression.type === "OptionalCallExpression" || n.expression.type === "FunctionExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode$1(parent) && (n.expression.type === "ConditionalExpression" || isBinaryish$1(n.expression))); + + if (shouldInline) { + return group$b(concat$d(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"])); + } + + return group$b(concat$d(["{", indent$7(concat$d([softline$6, path.call(print, "expression")])), softline$6, lineSuffixBoundary$1, "}"])); + } + + case "JSXFragment": + case "JSXElement": + { + const elem = comments.printComments(path, () => printJSXElement(path, options, print), options); + return maybeWrapJSXElementInParens(path, elem, options); + } + + case "JSXOpeningElement": + { + const n = path.getValue(); + const nameHasComments = n.name && n.name.comments && n.name.comments.length > 0 || n.typeParameters && n.typeParameters.comments && n.typeParameters.comments.length > 0; // Don't break self-closing elements with no attributes and no comments + + if (n.selfClosing && !n.attributes.length && !nameHasComments) { + return concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]); + } // don't break up opening elements with a single long text attribute + + + if (n.attributes && n.attributes.length === 1 && n.attributes[0].value && isStringLiteral$1(n.attributes[0].value) && !n.attributes[0].value.value.includes("\n") && // We should break for the following cases: + // <div + // // comment + // attr="value" + // > + // <div + // attr="value" + // // comment + // > + !nameHasComments && (!n.attributes[0].comments || !n.attributes[0].comments.length)) { + return group$b(concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$d(path.map(print, "attributes")), n.selfClosing ? " />" : ">"])); + } + + const lastAttrHasTrailingComments = n.attributes.length && hasTrailingComment$1(getLast$3(n.attributes)); + const bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be + // kept unbroken regardless of `jsxBracketSameLine` + !n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases: + // <div + // // comment + // > + // <div + // attr // comment + // > + !nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a + // string literal with newlines + + const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n")); + return group$b(concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$d([indent$7(concat$d(path.map(attr => concat$d([line$9, print(attr)]), "attributes"))), n.selfClosing ? line$9 : bracketSameLine ? ">" : softline$6]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), { + shouldBreak + }); + } + + case "JSXClosingElement": + return concat$d(["</", path.call(print, "name"), ">"]); + + case "JSXOpeningFragment": + case "JSXClosingFragment": + { + const hasComment = n.comments && n.comments.length; + const hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment); + const isOpeningFragment = n.type === "JSXOpeningFragment"; + return concat$d([isOpeningFragment ? "<" : "</", indent$7(concat$d([hasOwnLineComment ? hardline$9 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$9 : "", ">"]); + } + + case "JSXText": + /* istanbul ignore next */ + throw new Error("JSXTest should be handled by JSXElement"); + + case "JSXEmptyExpression": + { + const requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment); + return concat$d([comments.printDanglingComments(path, options, + /* sameIndent */ + !requiresHardline), requiresHardline ? hardline$9 : ""]); + } + + case "ClassBody": + if (!n.comments && n.body.length === 0) { + return "{}"; + } + + return concat$d(["{", n.body.length > 0 ? indent$7(concat$d([hardline$9, path.call(bodyPath => { + return printStatementSequence(bodyPath, options, print); + }, "body")])) : comments.printDanglingComments(path, options), hardline$9, "}"]); + + case "ClassProperty": + case "TSAbstractClassProperty": + case "ClassPrivateProperty": + { + if (n.decorators && n.decorators.length !== 0) { + parts.push(printDecorators(path, options, print)); + } + + if (n.accessibility) { + parts.push(n.accessibility + " "); + } + + if (n.declare) { + parts.push("declare "); + } + + if (n.static) { + parts.push("static "); + } + + if (n.type === "TSAbstractClassProperty" || n.abstract) { + parts.push("abstract "); + } + + if (n.readonly) { + parts.push("readonly "); + } + + const variance = getFlowVariance$1(n); + + if (variance) { + parts.push(variance); + } + + parts.push(printPropertyKey(path, options, print), printOptionalToken(path), printTypeAnnotation(path, options, print)); + + if (n.value) { + parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options)); + } + + parts.push(semi); + return group$b(concat$d(parts)); + } + + case "ClassDeclaration": + case "ClassExpression": + if (n.declare) { + parts.push("declare "); + } + + parts.push(concat$d(printClass(path, options, print))); + return concat$d(parts); + + case "TSInterfaceHeritage": + case "TSExpressionWithTypeArguments": + // Babel AST + parts.push(path.call(print, "expression")); + + if (n.typeParameters) { + parts.push(path.call(print, "typeParameters")); + } + + return concat$d(parts); + + case "TemplateElement": + return join$9(literalline$4, n.value.raw.split(/\r?\n/g)); + + case "TemplateLiteral": + { + let expressions = path.map(print, "expressions"); + const parentNode = path.getParentNode(); + + if (isJestEachTemplateLiteral$1(n, parentNode)) { + const printed = printJestEachTemplateLiteral(n, expressions, options); + + if (printed) { + return printed; + } + } + + const isSimple = isSimpleTemplateLiteral$1(n); + + if (isSimple) { + expressions = expressions.map(doc => printDocToString$2(doc, Object.assign({}, options, { + printWidth: Infinity + })).formatted); + } + + parts.push(lineSuffixBoundary$1, "`"); + path.each(childPath => { + const i = childPath.getName(); + parts.push(print(childPath)); + + if (i < expressions.length) { + // For a template literal of the following form: + // `someQuery { + // ${call({ + // a, + // b, + // })} + // }` + // the expression is on its own line (there is a \n in the previous + // quasi literal), therefore we want to indent the JavaScript + // expression inside at the beginning of ${ instead of the beginning + // of the `. + const { + tabWidth + } = options; + const quasi = childPath.getValue(); + const indentSize = getIndentSize$2(quasi.value.raw, tabWidth); + let printed = expressions[i]; + + if (!isSimple) { + // Breaks at the template element boundaries (${ and }) are preferred to breaking + // in the middle of a MemberExpression + if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression" || n.expressions[i].type === "SequenceExpression" || n.expressions[i].type === "TSAsExpression" || isBinaryish$1(n.expressions[i])) { + printed = concat$d([indent$7(concat$d([softline$6, printed])), softline$6]); + } + } + + const aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, printed) : addAlignmentToDoc$2(printed, indentSize, tabWidth); + parts.push(group$b(concat$d(["${", aligned, lineSuffixBoundary$1, "}"]))); + } + }, "quasis"); + parts.push("`"); + return concat$d(parts); + } + // These types are unprintable because they serve as abstract + // supertypes for other (printable) types. + + case "TaggedTemplateExpression": + return concat$d([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]); + + case "Node": + case "Printable": + case "SourceLocation": + case "Position": + case "Statement": + case "Function": + case "Pattern": + case "Expression": + case "Declaration": + case "Specifier": + case "NamedSpecifier": + case "Comment": + case "MemberTypeAnnotation": // Flow + + case "Type": + /* istanbul ignore next */ + throw new Error("unprintable type: " + JSON.stringify(n.type)); + // Type Annotations for Facebook Flow, typically stripped out or + // transformed away before printing. + + case "TypeAnnotation": + case "TSTypeAnnotation": + if (n.typeAnnotation) { + return path.call(print, "typeAnnotation"); + } + /* istanbul ignore next */ + + + return ""; + + case "TSTupleType": + case "TupleTypeAnnotation": + { + const typesField = n.type === "TSTupleType" ? "elementTypes" : "types"; + const hasRest = n[typesField].length > 0 && getLast$3(n[typesField]).type === "TSRestType"; + return group$b(concat$d(["[", indent$7(concat$d([softline$6, printArrayItems(path, options, typesField, print)])), ifBreak$6(shouldPrintComma$1(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options, + /* sameIndent */ + true), softline$6, "]"])); + } + + case "ExistsTypeAnnotation": + return "*"; + + case "EmptyTypeAnnotation": + return "empty"; + + case "AnyTypeAnnotation": + return "any"; + + case "MixedTypeAnnotation": + return "mixed"; + + case "ArrayTypeAnnotation": + return concat$d([path.call(print, "elementType"), "[]"]); + + case "BooleanTypeAnnotation": + return "boolean"; + + case "BooleanLiteralTypeAnnotation": + return "" + n.value; + + case "DeclareClass": + return printFlowDeclaration(path, printClass(path, options, print)); + + case "TSDeclareFunction": + // For TypeScript the TSDeclareFunction node shares the AST + // structure with FunctionDeclaration + return concat$d([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]); + + case "DeclareFunction": + return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]); + + case "DeclareModule": + return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]); + + case "DeclareModuleExports": + return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]); + + case "DeclareVariable": + return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]); + + case "DeclareExportAllDeclaration": + return concat$d(["declare export * from ", path.call(print, "source")]); + + case "DeclareExportDeclaration": + return concat$d(["declare ", printExportDeclaration(path, options, print)]); + + case "DeclareOpaqueType": + case "OpaqueType": + { + parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters")); + + if (n.supertype) { + parts.push(": ", path.call(print, "supertype")); + } + + if (n.impltype) { + parts.push(" = ", path.call(print, "impltype")); + } + + parts.push(semi); + + if (n.type === "DeclareOpaqueType") { + return printFlowDeclaration(path, parts); + } + + return concat$d(parts); + } + + case "EnumDeclaration": + return concat$d(["enum ", path.call(print, "id"), " ", path.call(print, "body")]); + + case "EnumBooleanBody": + case "EnumNumberBody": + case "EnumStringBody": + case "EnumSymbolBody": + { + if (n.type === "EnumSymbolBody" || n.explicitType) { + let type = null; + + switch (n.type) { + case "EnumBooleanBody": + type = "boolean"; + break; + + case "EnumNumberBody": + type = "number"; + break; + + case "EnumStringBody": + type = "string"; + break; + + case "EnumSymbolBody": + type = "symbol"; + break; + } + + parts.push("of ", type, " "); + } + + if (n.members.length === 0) { + parts.push(group$b(concat$d(["{", comments.printDanglingComments(path, options), softline$6, "}"]))); + } else { + parts.push(group$b(concat$d(["{", indent$7(concat$d([hardline$9, printArrayItems(path, options, "members", print), shouldPrintComma$1(options) ? "," : ""])), comments.printDanglingComments(path, options, + /* sameIndent */ + true), hardline$9, "}"]))); + } + + return concat$d(parts); + } + + case "EnumBooleanMember": + case "EnumNumberMember": + case "EnumStringMember": + return concat$d([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]); + + case "EnumDefaultedMember": + return path.call(print, "id"); + + case "FunctionTypeAnnotation": + case "TSFunctionType": + { + // FunctionTypeAnnotation is ambiguous: + // declare function foo(a: B): void; OR + // var A: (a: B) => void; + const parent = path.getParentNode(0); + const parentParent = path.getParentNode(1); + const parentParentParent = path.getParentNode(2); + let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(parent) && !parent.optional && options.locStart(parent) === options.locStart(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction"); + let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are + // printing ":" as part of the expression and it would put parenthesis + // around :( + + const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression"; + + if (isObjectTypePropertyAFunction$1(parent, options)) { + isArrowFunctionTypeAnnotation = true; + needsColon = true; + } + + if (needsParens) { + parts.push("("); + } + + parts.push(printFunctionParams(path, print, options, + /* expandArg */ + false, + /* printTypeParams */ + true)); // The returnType is not wrapped in a TypeAnnotation, so the colon + // needs to be added separately. + + if (n.returnType || n.predicate || n.typeAnnotation) { + parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation")); + } + + if (needsParens) { + parts.push(")"); + } + + return group$b(concat$d(parts)); + } + + case "TSRestType": + return concat$d(["...", path.call(print, "typeAnnotation")]); + + case "TSOptionalType": + return concat$d([path.call(print, "typeAnnotation"), "?"]); + + case "FunctionTypeParam": + return concat$d([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]); + + case "GenericTypeAnnotation": + return concat$d([path.call(print, "id"), path.call(print, "typeParameters")]); + + case "DeclareInterface": + case "InterfaceDeclaration": + case "InterfaceTypeAnnotation": + { + if (n.type === "DeclareInterface" || n.declare) { + parts.push("declare "); + } + + parts.push("interface"); + + if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") { + parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters")); + } + + if (n.extends.length > 0) { + parts.push(group$b(indent$7(concat$d([line$9, "extends ", (n.extends.length === 1 ? identity$2 : indent$7)(join$9(concat$d([",", line$9]), path.map(print, "extends")))])))); + } + + parts.push(" ", path.call(print, "body")); + return group$b(concat$d(parts)); + } + + case "ClassImplements": + case "InterfaceExtends": + return concat$d([path.call(print, "id"), path.call(print, "typeParameters")]); + + case "TSClassImplements": + return concat$d([path.call(print, "expression"), path.call(print, "typeParameters")]); + + case "TSIntersectionType": + case "IntersectionTypeAnnotation": + { + const types = path.map(print, "types"); + const result = []; + let wasIndented = false; + + for (let i = 0; i < types.length; ++i) { + if (i === 0) { + result.push(types[i]); + } else if (isObjectType$1(n.types[i - 1]) && isObjectType$1(n.types[i])) { + // If both are objects, don't indent + result.push(concat$d([" & ", wasIndented ? indent$7(types[i]) : types[i]])); + } else if (!isObjectType$1(n.types[i - 1]) && !isObjectType$1(n.types[i])) { + // If no object is involved, go to the next line if it breaks + result.push(indent$7(concat$d([" &", line$9, types[i]]))); + } else { + // If you go from object to non-object or vis-versa, then inline it + if (i > 1) { + wasIndented = true; + } + + result.push(" & ", i > 1 ? indent$7(types[i]) : types[i]); + } + } + + return group$b(concat$d(result)); + } + + case "TSUnionType": + case "UnionTypeAnnotation": + { + // single-line variation + // A | B | C + // multi-line variation + // | A + // | B + // | C + const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation + + const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // { + // a: string + // } | null | void + // should be inlined and not be printed in the multi-line variant + + const shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like + // | child1 + // // comment + // | child2 + + const printed = path.map(typePath => { + let printedType = typePath.call(print); + + if (!shouldHug) { + printedType = align$1(2, printedType); + } + + return comments.printComments(typePath, () => printedType, options); + }, "types"); + + if (shouldHug) { + return join$9(" | ", printed); + } + + const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options); + const code = concat$d([ifBreak$6(concat$d([shouldAddStartLine ? line$9 : "", "| "])), join$9(concat$d([line$9, "| "]), printed)]); + + if (needsParens_1(path, options)) { + return group$b(concat$d([indent$7(code), softline$6])); + } + + if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) { + return group$b(concat$d([indent$7(concat$d([ifBreak$6(concat$d(["(", softline$6])), code])), softline$6, ifBreak$6(")")])); + } + + return group$b(shouldIndent ? indent$7(code) : code); + } + + case "NullableTypeAnnotation": + return concat$d(["?", path.call(print, "typeAnnotation")]); + + case "TSNullKeyword": + case "NullLiteralTypeAnnotation": + return "null"; + + case "ThisTypeAnnotation": + return "this"; + + case "NumberTypeAnnotation": + return "number"; + + case "SymbolTypeAnnotation": + return "symbol"; + + case "ObjectTypeCallProperty": + if (n.static) { + parts.push("static "); + } + + parts.push(path.call(print, "value")); + return concat$d(parts); + + case "ObjectTypeIndexer": + { + const variance = getFlowVariance$1(n); + return concat$d([variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]); + } + + case "ObjectTypeProperty": + { + const variance = getFlowVariance$1(n); + let modifier = ""; + + if (n.proto) { + modifier = "proto "; + } else if (n.static) { + modifier = "static "; + } + + return concat$d([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", variance || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]); + } + + case "QualifiedTypeIdentifier": + return concat$d([path.call(print, "qualification"), ".", path.call(print, "id")]); + + case "StringLiteralTypeAnnotation": + return nodeStr(n, options); + + case "NumberLiteralTypeAnnotation": + assert.strictEqual(typeof n.value, "number"); + + if (n.extra != null) { + return printNumber$2(n.extra.raw); + } + + return printNumber$2(n.raw); + + case "StringTypeAnnotation": + return "string"; + + case "DeclareTypeAlias": + case "TypeAlias": + { + if (n.type === "DeclareTypeAlias" || n.declare) { + parts.push("declare "); + } + + const printed = printAssignmentRight(n.id, n.right, path.call(print, "right"), options); + parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi); + return group$b(concat$d(parts)); + } + + case "TypeCastExpression": + { + return concat$d(["(", path.call(print, "expression"), printTypeAnnotation(path, options, print), ")"]); + } + + case "TypeParameterDeclaration": + case "TypeParameterInstantiation": + { + const value = path.getValue(); + const commentStart = value.range ? options.originalText.slice(0, value.range[0]).lastIndexOf("/*") : -1; // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here + // because we know for sure that this is a type definition. + + const commentSyntax = commentStart >= 0 && options.originalText.slice(commentStart).match(/^\/\*\s*::/); + + if (commentSyntax) { + return concat$d(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]); + } + + return printTypeParameters(path, options, print, "params"); + } + + case "TSTypeParameterDeclaration": + case "TSTypeParameterInstantiation": + return printTypeParameters(path, options, print, "params"); + + case "TSTypeParameter": + case "TypeParameter": + { + const parent = path.getParentNode(); + + if (parent.type === "TSMappedType") { + parts.push("[", path.call(print, "name")); + + if (n.constraint) { + parts.push(" in ", path.call(print, "constraint")); + } + + parts.push("]"); + return concat$d(parts); + } + + const variance = getFlowVariance$1(n); + + if (variance) { + parts.push(variance); + } + + parts.push(path.call(print, "name")); + + if (n.bound) { + parts.push(": "); + parts.push(path.call(print, "bound")); + } + + if (n.constraint) { + parts.push(" extends ", path.call(print, "constraint")); + } + + if (n.default) { + parts.push(" = ", path.call(print, "default")); + } // Keep comma if the file extension is .tsx and + // has one type parameter that isn't extend with any types. + // Because, otherwise formatted result will be invalid as tsx. + + + const grandParent = path.getNode(2); + + if (parent.params && parent.params.length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") { + parts.push(","); + } + + return concat$d(parts); + } + + case "TypeofTypeAnnotation": + return concat$d(["typeof ", path.call(print, "argument")]); + + case "VoidTypeAnnotation": + return "void"; + + case "InferredPredicate": + return "%checks"; + // Unhandled types below. If encountered, nodes of these types should + // be either left alone or desugared into AST types that are fully + // supported by the pretty-printer. + + case "DeclaredPredicate": + return concat$d(["%checks(", path.call(print, "value"), ")"]); + + case "TSAbstractKeyword": + return "abstract"; + + case "TSAnyKeyword": + return "any"; + + case "TSAsyncKeyword": + return "async"; + + case "TSBooleanKeyword": + return "boolean"; + + case "TSBigIntKeyword": + return "bigint"; + + case "TSConstKeyword": + return "const"; + + case "TSDeclareKeyword": + return "declare"; + + case "TSExportKeyword": + return "export"; + + case "TSNeverKeyword": + return "never"; + + case "TSNumberKeyword": + return "number"; + + case "TSObjectKeyword": + return "object"; + + case "TSProtectedKeyword": + return "protected"; + + case "TSPrivateKeyword": + return "private"; + + case "TSPublicKeyword": + return "public"; + + case "TSReadonlyKeyword": + return "readonly"; + + case "TSSymbolKeyword": + return "symbol"; + + case "TSStaticKeyword": + return "static"; + + case "TSStringKeyword": + return "string"; + + case "TSUndefinedKeyword": + return "undefined"; + + case "TSUnknownKeyword": + return "unknown"; + + case "TSVoidKeyword": + return "void"; + + case "TSAsExpression": + return concat$d([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]); + + case "TSArrayType": + return concat$d([path.call(print, "elementType"), "[]"]); + + case "TSPropertySignature": + { + if (n.export) { + parts.push("export "); + } + + if (n.accessibility) { + parts.push(n.accessibility + " "); + } + + if (n.static) { + parts.push("static "); + } + + if (n.readonly) { + parts.push("readonly "); + } + + parts.push(printPropertyKey(path, options, print), printOptionalToken(path)); + + if (n.typeAnnotation) { + parts.push(": "); + parts.push(path.call(print, "typeAnnotation")); + } // This isn't valid semantically, but it's in the AST so we can print it. + + + if (n.initializer) { + parts.push(" = ", path.call(print, "initializer")); + } + + return concat$d(parts); + } + + case "TSParameterProperty": + if (n.accessibility) { + parts.push(n.accessibility + " "); + } + + if (n.export) { + parts.push("export "); + } + + if (n.static) { + parts.push("static "); + } + + if (n.readonly) { + parts.push("readonly "); + } + + parts.push(path.call(print, "parameter")); + return concat$d(parts); + + case "TSTypeReference": + return concat$d([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]); + + case "TSTypeQuery": + return concat$d(["typeof ", path.call(print, "exprName")]); + + case "TSIndexSignature": + { + const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're + // using them, it makes sense to have a trailing comma. But if you + // aren't, this is more like a computed property name than an array. + // So we leave off the trailing comma when there's just one parameter. + + const trailingComma = n.parameters.length > 1 ? ifBreak$6(shouldPrintComma$1(options) ? "," : "") : ""; + const parametersGroup = group$b(concat$d([indent$7(concat$d([softline$6, join$9(concat$d([", ", softline$6]), path.map(print, "parameters"))])), trailingComma, softline$6])); + return concat$d([n.export ? "export " : "", n.accessibility ? concat$d([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]); + } + + case "TSTypePredicate": + return concat$d([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$d([" is ", path.call(print, "typeAnnotation")]) : ""]); + + case "TSNonNullExpression": + return concat$d([path.call(print, "expression"), "!"]); + + case "TSThisType": + return "this"; + + case "TSImportType": + return concat$d([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$d([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]); + + case "TSLiteralType": + return path.call(print, "literal"); + + case "TSIndexedAccessType": + return concat$d([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]); + + case "TSConstructSignatureDeclaration": + case "TSCallSignatureDeclaration": + case "TSConstructorType": + { + if (n.type !== "TSCallSignatureDeclaration") { + parts.push("new "); + } + + parts.push(group$b(printFunctionParams(path, print, options, + /* expandArg */ + false, + /* printTypeParams */ + true))); + + if (n.returnType || n.typeAnnotation) { + const isType = n.type === "TSConstructorType"; + parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation")); + } + + return concat$d(parts); + } + + case "TSTypeOperator": + return concat$d([n.operator, " ", path.call(print, "typeAnnotation")]); + + case "TSMappedType": + { + const shouldBreak = hasNewlineInRange$3(options.originalText, options.locStart(n), options.locEnd(n)); + return group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, n.readonly ? concat$d([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$6(semi, "")])), comments.printDanglingComments(path, options, + /* sameIndent */ + true), options.bracketSpacing ? line$9 : softline$6, "}"]), { + shouldBreak + }); + } + + case "TSMethodSignature": + parts.push(n.accessibility ? concat$d([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken(path), printFunctionParams(path, print, options, + /* expandArg */ + false, + /* printTypeParams */ + true)); + + if (n.returnType || n.typeAnnotation) { + parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation")); + } + + return group$b(concat$d(parts)); + + case "TSNamespaceExportDeclaration": + parts.push("export as namespace ", path.call(print, "id")); + + if (options.semi) { + parts.push(";"); + } + + return group$b(concat$d(parts)); + + case "TSEnumDeclaration": + if (n.declare) { + parts.push("declare "); + } + + if (n.modifiers) { + parts.push(printTypeScriptModifiers(path, options, print)); + } + + if (n.const) { + parts.push("const "); + } + + parts.push("enum ", path.call(print, "id"), " "); + + if (n.members.length === 0) { + parts.push(group$b(concat$d(["{", comments.printDanglingComments(path, options), softline$6, "}"]))); + } else { + parts.push(group$b(concat$d(["{", indent$7(concat$d([hardline$9, printArrayItems(path, options, "members", print), shouldPrintComma$1(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options, + /* sameIndent */ + true), hardline$9, "}"]))); + } + + return concat$d(parts); + + case "TSEnumMember": + parts.push(path.call(print, "id")); + + if (n.initializer) { + parts.push(" = ", path.call(print, "initializer")); + } + + return concat$d(parts); + + case "TSImportEqualsDeclaration": + if (n.isExport) { + parts.push("export "); + } + + parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference")); + + if (options.semi) { + parts.push(";"); + } + + return group$b(concat$d(parts)); + + case "TSExternalModuleReference": + return concat$d(["require(", path.call(print, "expression"), ")"]); + + case "TSModuleDeclaration": + { + const parent = path.getParentNode(); + const isExternalModule = isLiteral$1(n.id); + const parentIsDeclaration = parent.type === "TSModuleDeclaration"; + const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration"; + + if (parentIsDeclaration) { + parts.push("."); + } else { + if (n.declare) { + parts.push("declare "); + } + + parts.push(printTypeScriptModifiers(path, options, print)); + const textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this: + // (declare)? global { ... } + + const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId); + + if (!isGlobalDeclaration) { + parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace "); + } + } + + parts.push(path.call(print, "id")); + + if (bodyIsDeclaration) { + parts.push(path.call(print, "body")); + } else if (n.body) { + parts.push(" ", group$b(path.call(print, "body"))); + } else { + parts.push(semi); + } + + return concat$d(parts); + } + + case "PrivateName": + return concat$d(["#", path.call(print, "id")]); + // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields. + + case "TSPrivateIdentifier": + return n.escapedText; + + case "TSConditionalType": + return printTernaryOperator(path, options, print, { + beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")], + afterParts: () => [], + shouldCheckJsx: false, + conditionalNodeType: "TSConditionalType", + consequentNodePropertyName: "trueType", + alternateNodePropertyName: "falseType", + testNodePropertyNames: ["checkType", "extendsType"] + }); + + case "TSInferType": + return concat$d(["infer", " ", path.call(print, "typeParameter")]); + + case "InterpreterDirective": + parts.push("#!", n.value, hardline$9); + + if (isNextLineEmpty$4(options.originalText, n, options.locEnd)) { + parts.push(hardline$9); + } + + return concat$d(parts); + + case "NGRoot": + return concat$d([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$d([" //", n.node.comments[0].value.trimEnd()]))); + + case "NGChainedExpression": + return group$b(join$9(concat$d([";", line$9]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$d(["(", print(childPath), ")"]), "expressions"))); + + case "NGEmptyExpression": + return ""; + + case "NGQuotedExpression": + return concat$d([n.prefix, ": ", n.value.trim()]); + + case "NGMicrosyntax": + return concat$d(path.map((childPath, index) => concat$d([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$d([";", line$9]), print(childPath)]), "body")); + + case "NGMicrosyntaxKey": + return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name); + + case "NGMicrosyntaxExpression": + return concat$d([path.call(print, "expression"), n.alias === null ? "" : concat$d([" as ", path.call(print, "alias")])]); + + case "NGMicrosyntaxKeyedExpression": + { + const index = path.getName(); + const parentNode = path.getParentNode(); + const shouldNotPrintColon = isNgForOf$1(n, index, parentNode) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression"; + return concat$d([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]); + } + + case "NGMicrosyntaxLet": + return concat$d(["let ", path.call(print, "key"), n.value === null ? "" : concat$d([" = ", path.call(print, "value")])]); + + case "NGMicrosyntaxAs": + return concat$d([path.call(print, "key"), " as ", path.call(print, "alias")]); + + case "ArgumentPlaceholder": + return "?"; + // These are not valid TypeScript. Printing them just for the sake of error recovery. + + case "TSJSDocAllType": + return "*"; + + case "TSJSDocUnknownType": + return "?"; + + case "TSJSDocNullableType": + return concat$d(["?", path.call(print, "typeAnnotation")]); + + case "TSJSDocNonNullableType": + return concat$d(["!", path.call(print, "typeAnnotation")]); + + case "TSJSDocFunctionType": + return concat$d(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error). + "): ", path.call(print, "typeAnnotation")]); + + default: + /* istanbul ignore next */ + throw new Error("unknown type: " + JSON.stringify(n.type)); + } + } + + function printStatementSequence(path, options, print) { + const printed = []; + const bodyNode = path.getNode(); + const isClass = bodyNode.type === "ClassBody"; + path.map((stmtPath, i) => { + const stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy + // "statements," it's safer simply to skip them. + + /* istanbul ignore if */ + + if (!stmt) { + return; + } // Skip printing EmptyStatement nodes to avoid leaving stray + // semicolons lying around. + + + if (stmt.type === "EmptyStatement") { + return; + } + + const stmtPrinted = print(stmtPath); + const text = options.originalText; + const parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI + // don't prepend the only JSX element in a program with semicolon + + if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) { + if (stmt.comments && stmt.comments.some(comment => comment.leading)) { + parts.push(print(stmtPath, { + needsSemi: true + })); + } else { + parts.push(";", stmtPrinted); + } + } else { + parts.push(stmtPrinted); + } + + if (!options.semi && isClass) { + if (classPropMayCauseASIProblems$1(stmtPath)) { + parts.push(";"); + } else if (stmt.type === "ClassProperty") { + const nextChild = bodyNode.body[i + 1]; + + if (classChildNeedsASIProtection$1(nextChild)) { + parts.push(";"); + } + } + } + + if (isNextLineEmpty$4(text, stmt, options.locEnd) && !isLastStatement$1(stmtPath)) { + parts.push(hardline$9); + } + + printed.push(concat$d(parts)); + }); + return join$9(hardline$9, printed); + } + + function printPropertyKey(path, options, print) { + const node = path.getNode(); + + if (node.computed) { + return concat$d(["[", path.call(print, "key"), "]"]); + } + + const parent = path.getParentNode(); + const { + key + } = node; + + if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key + key.type === "Identifier") { + return concat$d(["#", path.call(print, "key")]); + } + + if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) { + const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToCoerceToIdentifier$1(prop, options)); + needsQuoteProps.set(parent, objectHasStringProp); + } + + if (key.type === "Identifier" && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) { + // a -> "a" + const prop = printString$2(JSON.stringify(key.name), options); + return path.call(keyPath => comments.printComments(keyPath, () => prop, options), "key"); + } + + if (isStringPropSafeToCoerceToIdentifier$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) { + // 'a' -> a + return path.call(keyPath => comments.printComments(keyPath, () => key.value, options), "key"); + } + + return path.call(print, "key"); + } + + function printMethod(path, options, print) { + const node = path.getNode(); + const { + kind + } = node; + const value = node.value || node; + const parts = []; + + if (!kind || kind === "init" || kind === "method" || kind === "constructor") { + if (value.async) { + parts.push("async "); + } + + if (value.generator) { + parts.push("*"); + } + } else { + assert.ok(kind === "get" || kind === "set"); + parts.push(kind, " "); + } + + parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value")); + return concat$d(parts); + } + + function printMethodInternal(path, options, print) { + const parts = [printFunctionTypeParameters(path, options, print), group$b(concat$d([printFunctionParams(path, print, options), printReturnType(path, print, options)]))]; + + if (path.getNode().body) { + parts.push(" ", path.call(print, "body")); + } else { + parts.push(options.semi ? ";" : ""); + } + + return concat$d(parts); + } + + function couldGroupArg(arg) { + return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertion" && couldGroupArg(arg.expression) || arg.type === "TSAsExpression" && couldGroupArg(arg.expression) || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && ( // we want to avoid breaking inside composite return types but not simple keywords + // https://github.com/prettier/prettier/issues/4070 + // export class Thing implements OtherThing { + // do: (type: Type) => Provider<Prop> = memoize( + // (type: ObjectType): Provider<Opts> => {} + // ); + // } + // https://github.com/prettier/prettier/issues/6099 + // app.get("/", (req, res): void => { + // res.send("Hello World!"); + // }); + !arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference") && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode$1(arg.body)); + } + + function shouldGroupLastArg(args) { + const lastArg = getLast$3(args); + const penultimateArg = getPenultimate$1(args); + return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type, + // disable last element expansion. + !penultimateArg || penultimateArg.type !== lastArg.type); + } + + function shouldGroupFirstArg(args) { + if (args.length !== 2) { + return false; + } + + const [firstArg, secondArg] = args; + return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg); + } + + function printJestEachTemplateLiteral(node, expressions, options) { + /** + * a | b | expected + * ${1} | ${1} | ${2} + * ${1} | ${2} | ${3} + * ${2} | ${1} | ${3} + */ + const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/); + + if (headerNames.length > 1 || headerNames.some(headerName => headerName.length !== 0)) { + const parts = []; + const stringifiedExpressions = expressions.map(doc => "${" + printDocToString$2(doc, Object.assign({}, options, { + printWidth: Infinity, + endOfLine: "lf" + })).formatted + "}"); + const tableBody = [{ + hasLineBreak: false, + cells: [] + }]; + + for (let i = 1; i < node.quasis.length; i++) { + const row = tableBody[tableBody.length - 1]; + const correspondingExpression = stringifiedExpressions[i - 1]; + row.cells.push(correspondingExpression); + + if (correspondingExpression.includes("\n")) { + row.hasLineBreak = true; + } + + if (node.quasis[i].value.raw.includes("\n")) { + tableBody.push({ + hasLineBreak: false, + cells: [] + }); + } + } + + const maxColumnCount = Math.max(headerNames.length, ...tableBody.map(row => row.cells.length)); + const maxColumnWidths = Array.from({ + length: maxColumnCount + }).fill(0); + const table = [{ + cells: headerNames + }, ...tableBody.filter(row => row.cells.length !== 0)]; + + for (const { + cells + } of table.filter(row => !row.hasLineBreak)) { + cells.forEach((cell, index) => { + maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$3(cell)); + }); + } + + parts.push(lineSuffixBoundary$1, "`", indent$7(concat$d([hardline$9, join$9(hardline$9, table.map(row => join$9(" | ", row.cells.map((cell, index) => row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$3(cell))))))])), hardline$9, "`"); + return concat$d(parts); + } + } + + function printArgumentsList(path, options, print) { + const node = path.getValue(); + const args = node.arguments; + + if (args.length === 0) { + return concat$d(["(", comments.printDanglingComments(path, options, + /* sameIndent */ + true), ")"]); + } // useEffect(() => { ... }, [foo, bar, baz]) + + + if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.find(arg => arg.comments)) { + return concat$d(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]); + } // func( + // ({ + // a, + // b + // }) => {} + // ); + + + function shouldBreakForArrowFunctionInArguments(arg, argPath) { + if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) { + return false; + } + + let shouldBreak = false; + argPath.each(paramPath => { + const printed = concat$d([print(paramPath)]); + shouldBreak = shouldBreak || willBreak$1(printed); + }, "params"); + return shouldBreak; + } + + let anyArgEmptyLine = false; + let shouldBreakForArrowFunction = false; + let hasEmptyLineFollowingFirstArg = false; + const lastArgIndex = args.length - 1; + const printedArguments = path.map((argPath, index) => { + const arg = argPath.getNode(); + const parts = [print(argPath)]; + + if (index === lastArgIndex) ; else if (isNextLineEmpty$4(options.originalText, arg, options.locEnd)) { + if (index === 0) { + hasEmptyLineFollowingFirstArg = true; + } + + anyArgEmptyLine = true; + parts.push(",", hardline$9, hardline$9); + } else { + parts.push(",", line$9); + } + + shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath); + return concat$d(parts); + }, "arguments"); + const maybeTrailingComma = // Dynamic imports cannot have trailing commas + !(node.callee && node.callee.type === "Import") && shouldPrintComma$1(options, "all") ? "," : ""; + + function allArgsBrokenOut() { + return group$b(concat$d(["(", indent$7(concat$d([line$9, concat$d(printedArguments)])), maybeTrailingComma, line$9, ")"]), { + shouldBreak: true + }); + } + + if (path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs$1(args)) { + return allArgsBrokenOut(); + } + + const shouldGroupFirst = shouldGroupFirstArg(args); + const shouldGroupLast = shouldGroupLastArg(args); + + if (shouldGroupFirst || shouldGroupLast) { + const shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag + + let printedExpanded; + let i = 0; + path.each(argPath => { + if (shouldGroupFirst && i === 0) { + printedExpanded = [concat$d([argPath.call(p => print(p, { + expandFirstArg: true + })), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$9 : line$9, hasEmptyLineFollowingFirstArg ? hardline$9 : ""])].concat(printedArguments.slice(1)); + } + + if (shouldGroupLast && i === args.length - 1) { + printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(p => print(p, { + expandLastArg: true + }))); + } + + i++; + }, "arguments"); + const somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1); + const simpleConcat = concat$d(["(", concat$d(printedExpanded), ")"]); + return concat$d([somePrintedArgumentsWillBreak ? breakParent$3 : "", conditionalGroup$1([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$6(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$d(["(", group$b(printedExpanded[0], { + shouldBreak: true + }), concat$d(printedExpanded.slice(1)), ")"]) : concat$d(["(", concat$d(printedArguments.slice(0, -1)), group$b(getLast$3(printedExpanded), { + shouldBreak: true + }), ")"]), allArgsBrokenOut()], { + shouldBreak + })]); + } + + const contents = concat$d(["(", indent$7(concat$d([softline$6, concat$d(printedArguments)])), ifBreak$6(maybeTrailingComma), softline$6, ")"]); + + if (isLongCurriedCallExpression$1(path)) { + // By not wrapping the arguments in a group, the printer prioritizes + // breaking up these arguments rather than the args of the parent call. + return contents; + } + + return group$b(contents, { + shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine + }); + } + + function printTypeAnnotation(path, options, print) { + const node = path.getValue(); + + if (!node.typeAnnotation) { + return ""; + } + + const parentNode = path.getParentNode(); + const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite; + const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node; + + if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) { + return concat$d([" /*: ", path.call(print, "typeAnnotation"), " */"]); + } + + return concat$d([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]); + } + + function printFunctionTypeParameters(path, options, print) { + const fun = path.getValue(); + + if (fun.typeArguments) { + return path.call(print, "typeArguments"); + } + + if (fun.typeParameters) { + return path.call(print, "typeParameters"); + } + + return ""; + } + + function printFunctionParams(path, print, options, expandArg, printTypeParams) { + const fun = path.getValue(); + const parent = path.getParentNode(); + const paramsField = fun.parameters ? "parameters" : "params"; + const isParametersInTestCall = isTestCall$1(parent); + const shouldHugParameters = shouldHugArguments(fun); + const shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(n => n.comments)); + const typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : ""; + let printed = []; + + if (fun[paramsField]) { + const lastArgIndex = fun[paramsField].length - 1; + printed = path.map((childPath, index) => { + const parts = []; + const param = childPath.getValue(); + parts.push(print(childPath)); + + if (index === lastArgIndex) { + if (fun.rest) { + parts.push(",", line$9); + } + } else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) { + parts.push(", "); + } else if (isNextLineEmpty$4(options.originalText, param, options.locEnd)) { + parts.push(",", hardline$9, hardline$9); + } else { + parts.push(",", line$9); + } + + return concat$d(parts); + }, paramsField); + } + + if (fun.rest) { + printed.push(concat$d(["...", path.call(print, "rest")])); + } + + if (printed.length === 0) { + return concat$d([typeParams, "(", comments.printDanglingComments(path, options, + /* sameIndent */ + true, comment => getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")"), ")"]); + } + + const lastParam = getLast$3(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the + // params of the first/last argument, we don't want the arguments to break and instead + // want the whole expression to be on a new line. + // + // Good: Bad: + // verylongcall( verylongcall(( + // (a, b) => { a, + // } b, + // }) ) => { + // }) + + if (shouldExpandParameters) { + return group$b(concat$d([removeLines$2(typeParams), "(", concat$d(printed.map(removeLines$2)), ")"])); + } // Single object destructuring should hug + // + // function({ + // a, + // b, + // c + // }) {} + + + const hasNotParameterDecorator = fun[paramsField].every(param => !param.decorators); + + if (shouldHugParameters && hasNotParameterDecorator) { + return concat$d([typeParams, "(", concat$d(printed), ")"]); + } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})` + + + if (isParametersInTestCall) { + return concat$d([typeParams, "(", concat$d(printed), ")"]); + } + + const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent, options) || isTypeAnnotationAFunction$1(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType$1(fun[paramsField][0].typeAnnotation) && !fun.rest; + + if (isFlowShorthandWithOneArg) { + if (options.arrowParens === "always") { + return concat$d(["(", concat$d(printed), ")"]); + } + + return concat$d(printed); + } + + const canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest; + return concat$d([typeParams, "(", indent$7(concat$d([softline$6, concat$d(printed)])), ifBreak$6(canHaveTrailingComma && shouldPrintComma$1(options, "all") ? "," : ""), softline$6, ")"]); + } + + function shouldPrintParamsWithoutParens(path, options) { + if (options.arrowParens === "always") { + return false; + } + + if (options.arrowParens === "avoid") { + const node = path.getValue(); + return canPrintParamsWithoutParens(node); + } // Fallback default; should be unreachable + + + return false; + } + + function canPrintParamsWithoutParens(node) { + return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments$1(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType; + } + + function printFunctionDeclaration(path, print, options) { + const n = path.getValue(); + const parts = []; + + if (n.async) { + parts.push("async "); + } + + if (n.generator) { + parts.push("function* "); + } else { + parts.push("function "); + } + + if (n.id) { + parts.push(path.call(print, "id")); + } + + parts.push(printFunctionTypeParameters(path, options, print), group$b(concat$d([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body")); + return concat$d(parts); + } + + function printReturnType(path, print, options) { + const n = path.getValue(); + const returnType = path.call(print, "returnType"); + + if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) { + return concat$d([" /*: ", returnType, " */"]); + } + + const parts = [returnType]; // prepend colon to TypeScript type annotation + + if (n.returnType && n.returnType.typeAnnotation) { + parts.unshift(": "); + } + + if (n.predicate) { + // The return type will already add the colon, but otherwise we + // need to do it ourselves + parts.push(n.returnType ? " " : ": ", path.call(print, "predicate")); + } + + return concat$d(parts); + } + + function printExportDeclaration(path, options, print) { + const decl = path.getValue(); + const semi = options.semi ? ";" : ""; + const parts = ["export "]; + const isDefault = decl.default || decl.type === "ExportDefaultDeclaration"; + + if (isDefault) { + parts.push("default "); + } + + parts.push(comments.printDanglingComments(path, options, + /* sameIndent */ + true)); + + if (needsHardlineAfterDanglingComment$1(decl)) { + parts.push(hardline$9); + } + + if (decl.declaration) { + parts.push(path.call(print, "declaration")); + + if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction") { + parts.push(semi); + } + } else { + if (decl.specifiers && decl.specifiers.length > 0) { + const specifiers = []; + const defaultSpecifiers = []; + const namespaceSpecifiers = []; + path.each(specifierPath => { + const specifierType = path.getValue().type; + + if (specifierType === "ExportSpecifier") { + specifiers.push(print(specifierPath)); + } else if (specifierType === "ExportDefaultSpecifier") { + defaultSpecifiers.push(print(specifierPath)); + } else if (specifierType === "ExportNamespaceSpecifier") { + namespaceSpecifiers.push(concat$d(["* as ", print(specifierPath)])); + } + }, "specifiers"); + const isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0; + const isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0); + const canBreak = specifiers.length > 1 || defaultSpecifiers.length > 0 || decl.specifiers && decl.specifiers.some(node => node.comments); + let printed = ""; + + if (specifiers.length !== 0) { + if (canBreak) { + printed = group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, join$9(concat$d([",", line$9]), specifiers)])), ifBreak$6(shouldPrintComma$1(options) ? "," : ""), options.bracketSpacing ? line$9 : softline$6, "}"])); + } else { + printed = concat$d(["{", options.bracketSpacing ? " " : "", concat$d(specifiers), options.bracketSpacing ? " " : "", "}"]); + } + } + + parts.push(decl.exportKind === "type" ? "type " : "", concat$d(defaultSpecifiers), concat$d([isDefaultFollowed ? ", " : ""]), concat$d(namespaceSpecifiers), concat$d([isNamespaceFollowed ? ", " : ""]), printed); + } else { + parts.push("{}"); + } + + if (decl.source) { + parts.push(" from ", path.call(print, "source")); + } + + parts.push(semi); + } + + return concat$d(parts); + } + + function printFlowDeclaration(path, parts) { + const parentExportDecl = getParentExportDeclaration$1(path); + + if (parentExportDecl) { + assert.strictEqual(parentExportDecl.type, "DeclareExportDeclaration"); + } else { + // If the parent node has type DeclareExportDeclaration, then it + // will be responsible for printing the "declare" token. Otherwise + // it needs to be printed with this non-exported declaration node. + parts.unshift("declare "); + } + + return concat$d(parts); + } + + function printTypeScriptModifiers(path, options, print) { + const n = path.getValue(); + + if (!n.modifiers || !n.modifiers.length) { + return ""; + } + + return concat$d([join$9(" ", path.map(print, "modifiers")), " "]); + } + + function printTypeParameters(path, options, print, paramsKey) { + const n = path.getValue(); + + if (!n[paramsKey]) { + return ""; + } // for TypeParameterDeclaration typeParameters is a single node + + + if (!Array.isArray(n[paramsKey])) { + return path.call(print, paramsKey); + } + + const grandparent = path.getNode(2); + const greatGrandParent = path.getNode(3); + const greatGreatGrandParent = path.getNode(4); + const isParameterInTestCall = grandparent != null && isTestCall$1(grandparent); + const shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation" || // See https://github.com/prettier/prettier/pull/6467 for the context. + greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent.type === "TSTypeAnnotation" && greatGrandParent.type !== "ArrowFunctionExpression" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSIntersectionType" && n[paramsKey][0].type !== "IntersectionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType" && n[paramsKey][0].type !== "TSTypeOperator" && n[paramsKey][0].type !== "TSIndexedAccessType" && n[paramsKey][0].type !== "TSArrayType"); + + function printDanglingCommentsForInline(n) { + if (!hasDanglingComments$1(n)) { + return ""; + } + + const hasOnlyBlockComments = n.comments.every(comments$1.isBlockComment); + const printed = comments.printDanglingComments(path, options, + /* sameIndent */ + hasOnlyBlockComments); + + if (hasOnlyBlockComments) { + return printed; + } + + return concat$d([printed, hardline$9]); + } + + if (shouldInline) { + return concat$d(["<", join$9(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(n), ">"]); + } + + return group$b(concat$d(["<", indent$7(concat$d([softline$6, join$9(concat$d([",", line$9]), path.map(print, paramsKey))])), ifBreak$6(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma$1(options, "all") ? "," : ""), softline$6, ">"])); + } + + function printClass(path, options, print) { + const n = path.getValue(); + const parts = []; + + if (n.abstract) { + parts.push("abstract "); + } + + parts.push("class"); + + if (n.id) { + parts.push(" ", path.call(print, "id")); + } + + parts.push(path.call(print, "typeParameters")); + const partsGroup = []; + + if (n.superClass) { + const printed = concat$d(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line + // If there is only on extends and there are not comments + + if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) { + parts.push(concat$d([" ", path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")])); + } else { + partsGroup.push(group$b(concat$d([line$9, path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")]))); + } + } else if (n.extends && n.extends.length > 0) { + parts.push(" extends ", join$9(", ", path.map(print, "extends"))); + } + + if (n.mixins && n.mixins.length > 0) { + partsGroup.push(line$9, "mixins ", group$b(indent$7(join$9(concat$d([",", line$9]), path.map(print, "mixins"))))); + } + + if (n.implements && n.implements.length > 0) { + partsGroup.push(line$9, "implements", group$b(indent$7(concat$d([line$9, join$9(concat$d([",", line$9]), path.map(print, "implements"))])))); + } + + if (partsGroup.length > 0) { + parts.push(group$b(indent$7(concat$d(partsGroup)))); + } + + if (n.body && n.body.comments && hasLeadingOwnLineComment$1(options.originalText, n.body, options)) { + parts.push(hardline$9); + } else { + parts.push(" "); + } + + parts.push(path.call(print, "body")); + return parts; + } + + function printOptionalToken(path) { + const node = path.getValue(); + + if (!node.optional || // It's an optional computed method parsed by typescript-estree. + // "?" is printed in `printMethod`. + node.type === "Identifier" && node === path.getParentNode().key) { + return ""; + } + + if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) { + return "?."; + } + + return "?"; + } + + function printMemberLookup(path, options, print) { + const property = path.call(print, "property"); + const n = path.getValue(); + const optional = printOptionalToken(path); + + if (!n.computed) { + return concat$d([optional, ".", property]); + } + + if (!n.property || isNumericLiteral$1(n.property)) { + return concat$d([optional, "[", property, "]"]); + } + + return group$b(concat$d([optional, "[", indent$7(concat$d([softline$6, property])), softline$6, "]"])); + } + + function printBindExpressionCallee(path, options, print) { + return concat$d(["::", path.call(print, "callee")]); + } // We detect calls on member expressions specially to format a + // common pattern better. The pattern we are looking for is this: + // + // arr + // .map(x => x + 1) + // .filter(x => x > 10) + // .some(x => x % 2) + // + // The way it is structured in the AST is via a nested sequence of + // MemberExpression and CallExpression. We need to traverse the AST + // and make groups out of it to print it in the desired way. + + + function printMemberChain(path, options, print) { + // The first phase is to linearize the AST by traversing it down. + // + // a().b() + // has the following AST structure: + // CallExpression(MemberExpression(CallExpression(Identifier))) + // and we transform it into + // [Identifier, CallExpression, MemberExpression, CallExpression] + const printedNodes = []; // Here we try to retain one typed empty line after each call expression or + // the first group whether it is in parentheses or not + + function shouldInsertEmptyLineAfter(node) { + const { + originalText + } = options; + const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$3(originalText, node, options.locEnd); + const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty + // line after that parenthesis + + if (nextChar === ")") { + return isNextLineEmptyAfterIndex$2(originalText, nextCharIndex + 1, options.locEnd); + } + + return isNextLineEmpty$4(originalText, node, options.locEnd); + } + + function rec(path) { + const node = path.getValue(); + + if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish$1(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) { + printedNodes.unshift({ + node, + printed: concat$d([comments.printComments(path, () => concat$d([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]), options), shouldInsertEmptyLineAfter(node) ? hardline$9 : ""]) + }); + path.call(callee => rec(callee), "callee"); + } else if (isMemberish$1(node)) { + printedNodes.unshift({ + node, + needsParens: needsParens_1(path, options), + printed: comments.printComments(path, () => node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print), options) + }); + path.call(object => rec(object), "object"); + } else if (node.type === "TSNonNullExpression") { + printedNodes.unshift({ + node, + printed: comments.printComments(path, () => "!", options) + }); + path.call(expression => rec(expression), "expression"); + } else { + printedNodes.unshift({ + node, + printed: path.call(print) + }); + } + } // Note: the comments of the root node have already been printed, so we + // need to extract this first call without printing them as they would + // if handled inside of the recursive call. + + + const node = path.getValue(); + printedNodes.unshift({ + node, + printed: concat$d([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]) + }); + path.call(callee => rec(callee), "callee"); // Once we have a linear list of printed nodes, we want to create groups out + // of it. + // + // a().b.c().d().e + // will be grouped as + // [ + // [Identifier, CallExpression], + // [MemberExpression, MemberExpression, CallExpression], + // [MemberExpression, CallExpression], + // [MemberExpression], + // ] + // so that we can print it as + // a() + // .b.c() + // .d() + // .e + // The first group is the first node followed by + // - as many CallExpression as possible + // < fn()()() >.something() + // - as many array accessors as possible + // < fn()[0][1][2] >.something() + // - then, as many MemberExpression as possible but the last one + // < this.items >.something() + + const groups = []; + let currentGroup = [printedNodes[0]]; + let i = 1; + + for (; i < printedNodes.length; ++i) { + if (printedNodes[i].node.type === "TSNonNullExpression" || printedNodes[i].node.type === "OptionalCallExpression" || printedNodes[i].node.type === "CallExpression" || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) { + currentGroup.push(printedNodes[i]); + } else { + break; + } + } + + if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") { + for (; i + 1 < printedNodes.length; ++i) { + if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) { + currentGroup.push(printedNodes[i]); + } else { + break; + } + } + } + + groups.push(currentGroup); + currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by + // a sequence of CallExpression. To compute it, we keep adding things to the + // group until we has seen a CallExpression in the past and reach a + // MemberExpression + + let hasSeenCallExpression = false; + + for (; i < printedNodes.length; ++i) { + if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) { + // [0] should be appended at the end of the group instead of the + // beginning of the next one + if (printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) { + currentGroup.push(printedNodes[i]); + continue; + } + + groups.push(currentGroup); + currentGroup = []; + hasSeenCallExpression = false; + } + + if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") { + hasSeenCallExpression = true; + } + + currentGroup.push(printedNodes[i]); + + if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(comment => comment.trailing)) { + groups.push(currentGroup); + currentGroup = []; + hasSeenCallExpression = false; + } + } + + if (currentGroup.length > 0) { + groups.push(currentGroup); + } // There are cases like Object.keys(), Observable.of(), _.values() where + // they are the subject of all the chained calls and therefore should + // be kept on the same line: + // + // Object.keys(items) + // .filter(x => x) + // .map(x => x) + // + // In order to detect those cases, we use an heuristic: if the first + // node is an identifier with the name starting with a capital + // letter or just a sequence of _$. The rationale is that they are + // likely to be factories. + + + function isFactory(name) { + return /^[A-Z]|^[_$]+$/.test(name); + } // In case the Identifier is shorter than tab width, we can keep the + // first call in a single line, if it's an ExpressionStatement. + // + // d3.scaleLinear() + // .domain([0, 100]) + // .range([0, width]); + // + + + function isShort(name) { + return name.length <= options.tabWidth; + } + + function shouldNotWrap(groups) { + const parent = path.getParentNode(); + const isExpression = parent && parent.type === "ExpressionStatement"; + const hasComputed = groups[1].length && groups[1][0].node.computed; + + if (groups[0].length === 1) { + const firstNode = groups[0][0].node; + return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed); + } + + const lastNode = getLast$3(groups[0]).node; + return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed); + } + + const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups); + + function printGroup(printedGroup) { + const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print + // accordingly + + if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) { + return concat$d(["(", ...printed, ")"]); + } + + return concat$d(printed); + } + + function printIndentedGroup(groups) { + if (groups.length === 0) { + return ""; + } + + return indent$7(group$b(concat$d([hardline$9, join$9(hardline$9, groups.map(printGroup))]))); + } + + const printedGroups = groups.map(printGroup); + const oneLine = concat$d(printedGroups); + const cutoff = shouldMerge ? 3 : 2; + const flatGroups = groups.reduce((res, group) => res.concat(group), []); + const hasComment = flatGroups.slice(1, -1).some(node => hasLeadingComment$3(node.node)) || flatGroups.slice(0, -1).some(node => hasTrailingComment$1(node.node)) || groups[cutoff] && hasLeadingComment$3(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just + // render everything concatenated together. + + if (groups.length <= cutoff && !hasComment) { + if (isLongCurriedCallExpression$1(path)) { + return oneLine; + } + + return group$b(oneLine); + } // Find out the last node in the first group and check if it has an + // empty line after + + + const lastNodeBeforeIndent = getLast$3(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node; + const shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent); + const expanded = concat$d([printGroup(groups[0]), shouldMerge ? concat$d(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$9 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]); + const callExpressions = printedNodes.map(({ + node + }) => node).filter(isCallOrOptionalCallExpression$1); // We don't want to print in one line if the chain has: + // * A comment. + // * Non-trivial arguments. + // * Any group but the last one has a hard line. + // If the last group is a function it's okay to inline if it fits. + + if (hasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument$1(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$1) || + /** + * scopes.filter(scope => scope.value !== '').map((scope, i) => { + * // multi line content + * }) + */ + ((lastGroupDoc, lastGroupNode) => isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$1(lastGroupDoc))(getLast$3(printedGroups), getLast$3(getLast$3(groups)).node) && callExpressions.slice(0, -1).some(n => n.arguments.some(isFunctionOrArrowExpression$1))) { + return group$b(expanded); + } + + return concat$d([// We only need to check `oneLine` because if `expanded` is chosen + // that means that the parent group has already been broken + // naturally + willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$3 : "", conditionalGroup$1([oneLine, expanded])]); + } + + function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) { + if (isFacebookTranslationTag) { + return ""; + } + + if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) { + return child.length === 1 ? softline$6 : hardline$9; + } + + return softline$6; + } + + function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) { + if (isFacebookTranslationTag) { + return hardline$9; + } + + if (child.length === 1) { + return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$9 : softline$6; + } + + return hardline$9; + } // JSX Children are strange, mostly for two reasons: + // 1. JSX reads newlines into string values, instead of skipping them like JS + // 2. up to one whitespace between elements within a line is significant, + // but not between lines. + // + // Leading, trailing, and lone whitespace all need to + // turn themselves into the rather ugly `{' '}` when breaking. + // + // We print JSX using the `fill` doc primitive. + // This requires that we give it an array of alternating + // content and whitespace elements. + // To ensure this we add dummy `""` content elements as needed. + + + function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) { + const n = path.getValue(); + const children = []; // using `map` instead of `each` because it provides `i` + + path.map((childPath, i) => { + const child = childPath.getValue(); + + if (isLiteral$1(child)) { + const text = rawText$1(child); // Contains a non-whitespace character + + if (isMeaningfulJSXText$1(child)) { + const words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace + + if (words[0] === "") { + children.push(""); + words.shift(); + + if (/\n/.test(words[0])) { + const next = n.children[i + 1]; + children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next)); + } else { + children.push(jsxWhitespace); + } + + words.shift(); + } + + let endWhitespace; // Ends with whitespace + + if (getLast$3(words) === "") { + words.pop(); + endWhitespace = words.pop(); + } // This was whitespace only without a new line. + + + if (words.length === 0) { + return; + } + + words.forEach((word, i) => { + if (i % 2 === 1) { + children.push(line$9); + } else { + children.push(word); + } + }); + + if (endWhitespace !== undefined) { + if (/\n/.test(endWhitespace)) { + const next = n.children[i + 1]; + children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$3(children), child, next)); + } else { + children.push(jsxWhitespace); + } + } else { + const next = n.children[i + 1]; + children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$3(children), child, next)); + } + } else if (/\n/.test(text)) { + // Keep (up to one) blank line between tags/expressions/text. + // Note: We don't keep blank lines between text elements. + if (text.match(/\n/g).length > 1) { + children.push(""); + children.push(hardline$9); + } + } else { + children.push(""); + children.push(jsxWhitespace); + } + } else { + const printedChild = print(childPath); + children.push(printedChild); + const next = n.children[i + 1]; + const directlyFollowedByMeaningfulText = next && isMeaningfulJSXText$1(next); + + if (directlyFollowedByMeaningfulText) { + const firstWord = rawText$1(next).trim().split(matchJsxWhitespaceRegex$1)[0]; + children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next)); + } else { + children.push(hardline$9); + } + } + }, "children"); + return children; + } // JSX expands children from the inside-out, instead of the outside-in. + // This is both to break children before attributes, + // and to ensure that when children break, their parents do as well. + // + // Any element that is written without any newlines and fits on a single line + // is left that way. + // Not only that, any user-written-line containing multiple JSX siblings + // should also be kept on one line if possible, + // so each user-written-line is wrapped in its own group. + // + // Elements that contain newlines or don't fit on a single line (recursively) + // are fully-split, using hardline and shouldBreak: true. + // + // To support that case properly, all leading and trailing spaces + // are stripped from the list of children, and replaced with a single hardline. + + + function printJSXElement(path, options, print) { + const n = path.getValue(); + + if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) { + return concat$d([path.call(print, "openingElement"), path.call(print, "closingElement")]); + } + + const openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment"); + const closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment"); + + if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) { + return concat$d([openingLines, concat$d(path.map(print, "children")), closingLines]); + } // Convert `{" "}` to text nodes containing a space. + // This makes it easy to turn them into `jsxWhitespace` which + // can then print as either a space or `{" "}` when breaking. + + + n.children = n.children.map(child => { + if (isJSXWhitespaceExpression$1(child)) { + return { + type: "JSXText", + value: " ", + raw: " " + }; + } + + return child; + }); + const containsTag = n.children.filter(isJSXNode$1).length > 0; + const containsMultipleExpressions = n.children.filter(child => child.type === "JSXExpressionContainer").length > 1; + const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true. + + let forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions; + const isMdxBlock = path.getParentNode().rootMarker === "mdx"; + const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}'; + const jsxWhitespace = isMdxBlock ? concat$d([" "]) : ifBreak$6(concat$d([rawJsxWhitespace, softline$6]), " "); + const isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt"; + const children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag); + const containsText = n.children.some(child => isMeaningfulJSXText$1(child)); // We can end up we multiple whitespace elements with empty string + // content between them. + // We need to remove empty whitespace and softlines before JSX whitespace + // to get the correct output. + + for (let i = children.length - 2; i >= 0; i--) { + const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === ""; + const isPairOfHardlines = children[i] === hardline$9 && children[i + 1] === "" && children[i + 2] === hardline$9; + const isLineFollowedByJSXWhitespace = (children[i] === softline$6 || children[i] === hardline$9) && children[i + 1] === "" && children[i + 2] === jsxWhitespace; + const isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$6 || children[i + 2] === hardline$9); + const isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace; + const isPairOfHardOrSoftLines = children[i] === softline$6 && children[i + 1] === "" && children[i + 2] === hardline$9 || children[i] === hardline$9 && children[i + 1] === "" && children[i + 2] === softline$6; + + if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) { + children.splice(i, 2); + } else if (isJSXWhitespaceFollowedByLine) { + children.splice(i + 1, 2); + } + } // Trim trailing lines (or empty strings) + + + while (children.length && (isLineNext$1(getLast$3(children)) || isEmpty$1(getLast$3(children)))) { + children.pop(); + } // Trim leading lines (or empty strings) + + + while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) { + children.shift(); + children.shift(); + } // Tweak how we format children if outputting this element over multiple lines. + // Also detect whether we will force this element to output over multiple lines. + + + const multilineChildren = []; + children.forEach((child, i) => { + // There are a number of situations where we need to ensure we display + // whitespace as `{" "}` when outputting this element over multiple lines. + if (child === jsxWhitespace) { + if (i === 1 && children[i - 1] === "") { + if (children.length === 2) { + // Solitary whitespace + multilineChildren.push(rawJsxWhitespace); + return; + } // Leading whitespace + + + multilineChildren.push(concat$d([rawJsxWhitespace, hardline$9])); + return; + } else if (i === children.length - 1) { + // Trailing whitespace + multilineChildren.push(rawJsxWhitespace); + return; + } else if (children[i - 1] === "" && children[i - 2] === hardline$9) { + // Whitespace after line break + multilineChildren.push(rawJsxWhitespace); + return; + } + } + + multilineChildren.push(child); + + if (willBreak$1(child)) { + forcedBreak = true; + } + }); // If there is text we use `fill` to fit as much onto each line as possible. + // When there is no text (just tags and expressions) we use `group` + // to output each on a separate line. + + const content = containsText ? fill$4(multilineChildren) : group$b(concat$d(multilineChildren), { + shouldBreak: true + }); + + if (isMdxBlock) { + return content; + } + + const multiLineElem = group$b(concat$d([openingLines, indent$7(concat$d([hardline$9, content])), hardline$9, closingLines])); + + if (forcedBreak) { + return multiLineElem; + } + + return conditionalGroup$1([group$b(concat$d([openingLines, concat$d(children), closingLines])), multiLineElem]); + } + + function maybeWrapJSXElementInParens(path, elem, options) { + const parent = path.getParentNode(); + + if (!parent) { + return elem; + } + + const NO_WRAP_PARENTS = { + ArrayExpression: true, + JSXAttribute: true, + JSXElement: true, + JSXExpressionContainer: true, + JSXFragment: true, + ExpressionStatement: true, + CallExpression: true, + OptionalCallExpression: true, + ConditionalExpression: true, + JsExpressionRoot: true + }; + + if (NO_WRAP_PARENTS[parent.type]) { + return elem; + } + + const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression$1, node => node.type === "JSXExpressionContainer"); + const needsParens = needsParens_1(path, options); + return group$b(concat$d([needsParens ? "" : ifBreak$6("("), indent$7(concat$d([softline$6, elem])), softline$6, needsParens ? "" : ifBreak$6(")")]), { + shouldBreak + }); + } + + function shouldInlineLogicalExpression(node) { + if (node.type !== "LogicalExpression") { + return false; + } + + if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) { + return true; + } + + if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) { + return true; + } + + if (isJSXNode$1(node.right)) { + return true; + } + + return false; + } // For binary expressions to be consistent, we need to group + // subsequent operators with the same precedence level under a single + // group. Otherwise they will be nested such that some of them break + // onto new lines but not all. Operators with the same precedence + // level should either all break or not. Because we group them by + // precedence level and the AST is structured based on precedence + // level, things are naturally broken up correctly, i.e. `&&` is + // broken before `+`. + + + function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) { + let parts = []; + const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same. + + if (isBinaryish$1(node)) { + // Put all operators with the same precedence level in the same + // group. The reason we only need to do this with the `left` + // expression is because given an expression like `1 + 2 - 3`, it + // is always parsed like `((1 + 2) - 3)`, meaning the `left` side + // is where the rest of the expression will exist. Binary + // expressions on the right side mean they have a difference + // precedence level and should be treated as a separate group, so + // print them normally. (This doesn't hold for the `**` operator, + // which is unique in that it is right-associative.) + if (shouldFlatten$1(node.operator, node.left.operator)) { + // Flatten them out by recursively calling this function. + parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options, + /* isNested */ + true, isInsideParenthesis), "left")); + } else { + parts.push(path.call(print, "left")); + } + + const shouldInline = shouldInlineLogicalExpression(node); + const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options); + const operator = node.type === "NGPipeExpression" ? "|" : node.operator; + const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$b(indent$7(concat$d([softline$6, ": ", join$9(concat$d([softline$6, ":", ifBreak$6(" ")]), path.map(print, "arguments").map(arg => align$1(2, group$b(arg))))]))) : ""; + const right = shouldInline ? concat$d([operator, " ", path.call(print, "right"), rightSuffix]) : concat$d([lineBeforeOperator ? softline$6 : "", operator, lineBeforeOperator ? " " : line$9, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group + // in order to avoid having a small right part like -1 be on its own line. + + const parent = path.getParentNode(); + const shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type; + parts.push(" ", shouldGroup ? group$b(right) : right); // The root comments are already printed, but we need to manually print + // the other ones since we don't call the normal print on BinaryExpression, + // only for the left and right parts + + if (isNested && node.comments) { + parts = comments.printComments(path, () => concat$d(parts), options); + } + } else { + // Our stopping case. Simply print the node normally. + parts.push(path.call(print)); + } + + return parts; + } + + function printAssignmentRight(leftNode, rightNode, printedRight, options) { + if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) { + return indent$7(concat$d([line$9, printedRight])); + } + + const canBreak = isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$1(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$1(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$1(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json + options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression"; + + if (canBreak) { + return group$b(indent$7(concat$d([line$9, printedRight]))); + } + + return concat$d([" ", printedRight]); + } + + function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) { + if (!rightNode) { + return printedLeft; + } + + const printed = printAssignmentRight(leftNode, rightNode, printedRight, options); + return group$b(concat$d([printedLeft, operator, printed])); + } + + function adjustClause(node, clause, forceSpace) { + if (node.type === "EmptyStatement") { + return ";"; + } + + if (node.type === "BlockStatement" || forceSpace) { + return concat$d([" ", clause]); + } + + return indent$7(concat$d([line$9, clause])); + } + + function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) { + const raw = rawText$1(node); + const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral"; + return printString$2(raw, options, isDirectiveLiteral); + } + + function printRegex(node) { + const flags = node.flags.split("").sort().join(""); + return "/".concat(node.pattern, "/").concat(flags); + } + + function exprNeedsASIProtection(path, options) { + const node = path.getValue(); + const maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$1(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex; + + if (maybeASIProblem) { + return true; + } + + if (!hasNakedLeftSide$2(node)) { + return false; + } + + return path.call(childPath => exprNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node)); + } + + function stmtNeedsASIProtection(path, options) { + const node = path.getNode(); + + if (node.type !== "ExpressionStatement") { + return false; + } + + return path.call(childPath => exprNeedsASIProtection(childPath, options), "expression"); + } + + function shouldHugType(node) { + if (isSimpleFlowType$1(node) || isObjectType$1(node)) { + return true; + } + + if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") { + const voidCount = node.types.filter(n => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword").length; + const hasObject = node.types.some(n => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}> + n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference"); + + if (node.types.length - 1 === voidCount && hasObject) { + return true; + } + } + + return false; + } + + function shouldHugArguments(fun) { + if (!fun || fun.rest) { + return false; + } + + const params = fun.params || fun.parameters; + + if (!params || params.length !== 1) { + return false; + } + + const param = params[0]; + return !param.comments && (param.type === "ObjectPattern" || param.type === "ArrayPattern" || param.type === "Identifier" && param.typeAnnotation && (param.typeAnnotation.type === "TypeAnnotation" || param.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(param.typeAnnotation.typeAnnotation) || param.type === "FunctionTypeParam" && isObjectType$1(param.typeAnnotation) || param.type === "AssignmentPattern" && (param.left.type === "ObjectPattern" || param.left.type === "ArrayPattern") && (param.right.type === "Identifier" || param.right.type === "ObjectExpression" && param.right.properties.length === 0 || param.right.type === "ArrayExpression" && param.right.elements.length === 0)); + } + + function printArrayItems(path, options, printPath, print) { + const printedElements = []; + let separatorParts = []; + path.each(childPath => { + printedElements.push(concat$d(separatorParts)); + printedElements.push(group$b(print(childPath))); + separatorParts = [",", line$9]; + + if (childPath.getValue() && isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) { + separatorParts.push(softline$6); + } + }, printPath); + return concat$d(printedElements); + } + + function printReturnAndThrowArgument(path, options, print) { + const node = path.getValue(); + const semi = options.semi ? ";" : ""; + const parts = []; + + if (node.argument) { + if (returnArgumentHasLeadingComment$1(options, node.argument)) { + parts.push(concat$d([" (", indent$7(concat$d([hardline$9, path.call(print, "argument")])), hardline$9, ")"])); + } else if (isBinaryish$1(node.argument) || node.argument.type === "SequenceExpression") { + parts.push(group$b(concat$d([ifBreak$6(" (", " "), indent$7(concat$d([softline$6, path.call(print, "argument")])), softline$6, ifBreak$6(")")]))); + } else { + parts.push(" ", path.call(print, "argument")); + } + } + + const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1]; + const isLastCommentLine = lastComment && (lastComment.type === "CommentLine" || lastComment.type === "Line"); + + if (isLastCommentLine) { + parts.push(semi); + } + + if (hasDanglingComments$1(node)) { + parts.push(" ", comments.printDanglingComments(path, options, + /* sameIndent */ + true)); + } + + if (!isLastCommentLine) { + parts.push(semi); + } + + return concat$d(parts); + } + + function willPrintOwnComments(path + /*, options */ + ) { + const node = path.getValue(); + const parent = path.getParentNode(); + return (node && (isJSXNode$1(node) || hasFlowShorthandAnnotationComment$2(node) || parent && (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && (hasFlowAnnotationComment$1(node.leadingComments) || hasFlowAnnotationComment$1(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && (!hasIgnoreComment$4(path) || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType"); + } + + function canAttachComment$1(node) { + return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import"; + } + + function printComment$2(commentPath, options) { + const comment = commentPath.getValue(); + + switch (comment.type) { + case "CommentBlock": + case "Block": + { + if (isIndentableBlockComment(comment)) { + const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment + // printed as a `lineSuffix` which causes the comments to be + // interleaved. See https://github.com/prettier/prettier/issues/4412 + + if (comment.trailing && !hasNewline$5(options.originalText, options.locStart(comment), { + backwards: true + })) { + return concat$d([hardline$9, printed]); + } + + return printed; + } + + const commentEnd = options.locEnd(comment); + const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/"; + return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/"); + } + + case "CommentLine": + case "Line": + // Print shebangs with the proper comment characters + if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) { + return "#!" + comment.value.trimEnd(); + } + + return "//" + comment.value.trimEnd(); + + default: + throw new Error("Not a comment: " + JSON.stringify(comment)); + } + } + + function isIndentableBlockComment(comment) { + // If the comment has multiple lines and every line starts with a star + // we can fix the indentation of each line. The stars in the `/*` and + // `*/` delimiters are not included in the comment value, so add them + // back first. + const lines = "*".concat(comment.value, "*").split("\n"); + return lines.length > 1 && lines.every(line => line.trim()[0] === "*"); + } + + function printIndentableBlockComment(comment) { + const lines = comment.value.split("\n"); + return concat$d(["/*", join$9(hardline$9, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]); + } + + var printerEstree = { + preprocess: preprocess_1$1, + print: genericPrint$3, + embed: embed_1$1, + insertPragma: insertPragma$7, + massageAstNode: clean_1$1, + hasPrettierIgnore: hasPrettierIgnore$5, + willPrintOwnComments, + canAttachComment: canAttachComment$1, + printComment: printComment$2, + isBlockComment: comments$1.isBlockComment, + handleComments: { + ownLine: comments$1.handleOwnLineComment, + endOfLine: comments$1.handleEndOfLineComment, + remaining: comments$1.handleRemainingComment + }, + getGapRegex: comments$1.getGapRegex, + getCommentChildNodes: comments$1.getCommentChildNodes + }; + + const { + concat: concat$e, + hardline: hardline$a, + indent: indent$8, + join: join$a + } = document.builders; + + function genericPrint$4(path, options, print) { + const node = path.getValue(); + + switch (node.type) { + case "JsonRoot": + return concat$e([path.call(print, "node"), hardline$a]); + + case "ArrayExpression": + return node.elements.length === 0 ? "[]" : concat$e(["[", indent$8(concat$e([hardline$a, join$a(concat$e([",", hardline$a]), path.map(print, "elements"))])), hardline$a, "]"]); + + case "ObjectExpression": + return node.properties.length === 0 ? "{}" : concat$e(["{", indent$8(concat$e([hardline$a, join$a(concat$e([",", hardline$a]), path.map(print, "properties"))])), hardline$a, "}"]); + + case "ObjectProperty": + return concat$e([path.call(print, "key"), ": ", path.call(print, "value")]); + + case "UnaryExpression": + return concat$e([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]); + + case "NullLiteral": + return "null"; + + case "BooleanLiteral": + return node.value ? "true" : "false"; + + case "StringLiteral": + case "NumericLiteral": + return JSON.stringify(node.value); + + case "Identifier": + return JSON.stringify(node.name); + + default: + /* istanbul ignore next */ + throw new Error("unknown type: " + JSON.stringify(node.type)); + } + } + + function clean$5(node, newNode + /*, parent*/ + ) { + delete newNode.start; + delete newNode.end; + delete newNode.extra; + delete newNode.loc; + delete newNode.comments; + delete newNode.errors; + + if (node.type === "Identifier") { + return { + type: "StringLiteral", + value: node.name + }; + } + + if (node.type === "UnaryExpression" && node.operator === "+") { + return newNode.argument; + } + } + + var printerEstreeJson = { + preprocess: preprocess_1$1, + print: genericPrint$4, + massageAstNode: clean$5 + }; + + const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js + + var options$5 = { + arrowParens: { + since: "1.9.0", + category: CATEGORY_JAVASCRIPT, + type: "choice", + default: [{ + since: "1.9.0", + value: "avoid" + }, { + since: "2.0.0", + value: "always" + }], + description: "Include parentheses around a sole arrow function parameter.", + choices: [{ + value: "always", + description: "Always include parens. Example: `(x) => x`" + }, { + value: "avoid", + description: "Omit parens when possible. Example: `x => x`" + }] + }, + bracketSpacing: commonOptions.bracketSpacing, + jsxBracketSameLine: { + since: "0.17.0", + category: CATEGORY_JAVASCRIPT, + type: "boolean", + default: false, + description: "Put > on the last line instead of at a new line." + }, + semi: { + since: "1.0.0", + category: CATEGORY_JAVASCRIPT, + type: "boolean", + default: true, + description: "Print semicolons.", + oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them." + }, + singleQuote: commonOptions.singleQuote, + jsxSingleQuote: { + since: "1.15.0", + category: CATEGORY_JAVASCRIPT, + type: "boolean", + default: false, + description: "Use single quotes in JSX." + }, + quoteProps: { + since: "1.17.0", + category: CATEGORY_JAVASCRIPT, + type: "choice", + default: "as-needed", + description: "Change when properties in objects are quoted.", + choices: [{ + value: "as-needed", + description: "Only add quotes around object properties where required." + }, { + value: "consistent", + description: "If at least one property in an object requires quotes, quote all properties." + }, { + value: "preserve", + description: "Respect the input use of quotes in object properties." + }] + }, + trailingComma: { + since: "0.0.0", + category: CATEGORY_JAVASCRIPT, + type: "choice", + default: [{ + since: "0.0.0", + value: false + }, { + since: "0.19.0", + value: "none" + }, { + since: "2.0.0", + value: "es5" + }], + description: "Print trailing commas wherever possible when multi-line.", + choices: [{ + value: "es5", + description: "Trailing commas where valid in ES5 (objects, arrays, etc.)" + }, { + value: "none", + description: "No trailing commas." + }, { + value: "all", + description: "Trailing commas wherever possible (including function arguments)." + }] + } + }; + + var name$9 = "JavaScript"; + var type$8 = "programming"; + var tmScope$8 = "source.js"; + var aceMode$8 = "javascript"; + var codemirrorMode$4 = "javascript"; + var codemirrorMimeType$4 = "text/javascript"; + var color$3 = "#f1e05a"; + var aliases$2 = [ + "js", + "node" + ]; + var extensions$8 = [ + ".js", + "._js", + ".bones", + ".cjs", + ".es", + ".es6", + ".frag", + ".gs", + ".jake", + ".jsb", + ".jscad", + ".jsfl", + ".jsm", + ".jss", + ".mjs", + ".njs", + ".pac", + ".sjs", + ".ssjs", + ".xsjs", + ".xsjslib" + ]; + var filenames = [ + "Jakefile" + ]; + var interpreters = [ + "chakra", + "d8", + "gjs", + "js", + "node", + "qjs", + "rhino", + "v8", + "v8-shell" + ]; + var languageId$8 = 183; + var JavaScript = { + name: name$9, + type: type$8, + tmScope: tmScope$8, + aceMode: aceMode$8, + codemirrorMode: codemirrorMode$4, + codemirrorMimeType: codemirrorMimeType$4, + color: color$3, + aliases: aliases$2, + extensions: extensions$8, + filenames: filenames, + interpreters: interpreters, + languageId: languageId$8 + }; + + var JavaScript$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$9, + type: type$8, + tmScope: tmScope$8, + aceMode: aceMode$8, + codemirrorMode: codemirrorMode$4, + codemirrorMimeType: codemirrorMimeType$4, + color: color$3, + aliases: aliases$2, + extensions: extensions$8, + filenames: filenames, + interpreters: interpreters, + languageId: languageId$8, + 'default': JavaScript + }); + + var name$a = "JSX"; + var type$9 = "programming"; + var group$c = "JavaScript"; + var extensions$9 = [ + ".jsx" + ]; + var tmScope$9 = "source.js.jsx"; + var aceMode$9 = "javascript"; + var codemirrorMode$5 = "jsx"; + var codemirrorMimeType$5 = "text/jsx"; + var languageId$9 = 178; + var JSX = { + name: name$a, + type: type$9, + group: group$c, + extensions: extensions$9, + tmScope: tmScope$9, + aceMode: aceMode$9, + codemirrorMode: codemirrorMode$5, + codemirrorMimeType: codemirrorMimeType$5, + languageId: languageId$9 + }; + + var JSX$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$a, + type: type$9, + group: group$c, + extensions: extensions$9, + tmScope: tmScope$9, + aceMode: aceMode$9, + codemirrorMode: codemirrorMode$5, + codemirrorMimeType: codemirrorMimeType$5, + languageId: languageId$9, + 'default': JSX + }); + + var name$b = "TypeScript"; + var type$a = "programming"; + var color$4 = "#2b7489"; + var aliases$3 = [ + "ts" + ]; + var interpreters$1 = [ + "deno", + "ts-node" + ]; + var extensions$a = [ + ".ts" + ]; + var tmScope$a = "source.ts"; + var aceMode$a = "typescript"; + var codemirrorMode$6 = "javascript"; + var codemirrorMimeType$6 = "application/typescript"; + var languageId$a = 378; + var TypeScript = { + name: name$b, + type: type$a, + color: color$4, + aliases: aliases$3, + interpreters: interpreters$1, + extensions: extensions$a, + tmScope: tmScope$a, + aceMode: aceMode$a, + codemirrorMode: codemirrorMode$6, + codemirrorMimeType: codemirrorMimeType$6, + languageId: languageId$a + }; + + var TypeScript$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$b, + type: type$a, + color: color$4, + aliases: aliases$3, + interpreters: interpreters$1, + extensions: extensions$a, + tmScope: tmScope$a, + aceMode: aceMode$a, + codemirrorMode: codemirrorMode$6, + codemirrorMimeType: codemirrorMimeType$6, + languageId: languageId$a, + 'default': TypeScript + }); + + var name$c = "TSX"; + var type$b = "programming"; + var group$d = "TypeScript"; + var extensions$b = [ + ".tsx" + ]; + var tmScope$b = "source.tsx"; + var aceMode$b = "javascript"; + var codemirrorMode$7 = "jsx"; + var codemirrorMimeType$7 = "text/jsx"; + var languageId$b = 94901924; + var TSX = { + name: name$c, + type: type$b, + group: group$d, + extensions: extensions$b, + tmScope: tmScope$b, + aceMode: aceMode$b, + codemirrorMode: codemirrorMode$7, + codemirrorMimeType: codemirrorMimeType$7, + languageId: languageId$b + }; + + var TSX$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$c, + type: type$b, + group: group$d, + extensions: extensions$b, + tmScope: tmScope$b, + aceMode: aceMode$b, + codemirrorMode: codemirrorMode$7, + codemirrorMimeType: codemirrorMimeType$7, + languageId: languageId$b, + 'default': TSX + }); + + var name$d = "JSON"; + var type$c = "data"; + var tmScope$c = "source.json"; + var aceMode$c = "json"; + var codemirrorMode$8 = "javascript"; + var codemirrorMimeType$8 = "application/json"; + var searchable = false; + var extensions$c = [ + ".json", + ".avsc", + ".geojson", + ".gltf", + ".har", + ".ice", + ".JSON-tmLanguage", + ".jsonl", + ".mcmeta", + ".tfstate", + ".tfstate.backup", + ".topojson", + ".webapp", + ".webmanifest", + ".yy", + ".yyp" + ]; + var filenames$1 = [ + ".arcconfig", + ".htmlhintrc", + ".tern-config", + ".tern-project", + ".watchmanconfig", + "composer.lock", + "mcmod.info" + ]; + var languageId$c = 174; + var _JSON = { + name: name$d, + type: type$c, + tmScope: tmScope$c, + aceMode: aceMode$c, + codemirrorMode: codemirrorMode$8, + codemirrorMimeType: codemirrorMimeType$8, + searchable: searchable, + extensions: extensions$c, + filenames: filenames$1, + languageId: languageId$c + }; + + var _JSON$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$d, + type: type$c, + tmScope: tmScope$c, + aceMode: aceMode$c, + codemirrorMode: codemirrorMode$8, + codemirrorMimeType: codemirrorMimeType$8, + searchable: searchable, + extensions: extensions$c, + filenames: filenames$1, + languageId: languageId$c, + 'default': _JSON + }); + + var name$e = "JSON with Comments"; + var type$d = "data"; + var group$e = "JSON"; + var tmScope$d = "source.js"; + var aceMode$d = "javascript"; + var codemirrorMode$9 = "javascript"; + var codemirrorMimeType$9 = "text/javascript"; + var aliases$4 = [ + "jsonc" + ]; + var extensions$d = [ + ".jsonc", + ".sublime-build", + ".sublime-commands", + ".sublime-completions", + ".sublime-keymap", + ".sublime-macro", + ".sublime-menu", + ".sublime-mousemap", + ".sublime-project", + ".sublime-settings", + ".sublime-theme", + ".sublime-workspace", + ".sublime_metrics", + ".sublime_session" + ]; + var filenames$2 = [ + ".babelrc", + ".eslintrc.json", + ".jscsrc", + ".jshintrc", + ".jslintrc", + "jsconfig.json", + "language-configuration.json", + "tsconfig.json" + ]; + var languageId$d = 423; + var JSON_with_Comments = { + name: name$e, + type: type$d, + group: group$e, + tmScope: tmScope$d, + aceMode: aceMode$d, + codemirrorMode: codemirrorMode$9, + codemirrorMimeType: codemirrorMimeType$9, + aliases: aliases$4, + extensions: extensions$d, + filenames: filenames$2, + languageId: languageId$d + }; + + var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$e, + type: type$d, + group: group$e, + tmScope: tmScope$d, + aceMode: aceMode$d, + codemirrorMode: codemirrorMode$9, + codemirrorMimeType: codemirrorMimeType$9, + aliases: aliases$4, + extensions: extensions$d, + filenames: filenames$2, + languageId: languageId$d, + 'default': JSON_with_Comments + }); + + var name$f = "JSON5"; + var type$e = "data"; + var extensions$e = [ + ".json5" + ]; + var tmScope$e = "source.js"; + var aceMode$e = "javascript"; + var codemirrorMode$a = "javascript"; + var codemirrorMimeType$a = "application/json"; + var languageId$e = 175; + var JSON5 = { + name: name$f, + type: type$e, + extensions: extensions$e, + tmScope: tmScope$e, + aceMode: aceMode$e, + codemirrorMode: codemirrorMode$a, + codemirrorMimeType: codemirrorMimeType$a, + languageId: languageId$e + }; + + var JSON5$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$f, + type: type$e, + extensions: extensions$e, + tmScope: tmScope$e, + aceMode: aceMode$e, + codemirrorMode: codemirrorMode$a, + codemirrorMimeType: codemirrorMimeType$a, + languageId: languageId$e, + 'default': JSON5 + }); + + var require$$0$6 = getCjsExportFromNamespace(JavaScript$1); + + var require$$1$2 = getCjsExportFromNamespace(JSX$1); + + var require$$2$1 = getCjsExportFromNamespace(TypeScript$1); + + var require$$3$1 = getCjsExportFromNamespace(TSX$1); + + var require$$4 = getCjsExportFromNamespace(_JSON$1); + + var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1); + + var require$$6 = getCjsExportFromNamespace(JSON5$1); + + const languages$4 = [createLanguage(require$$0$6, data => ({ + since: "0.0.0", + parsers: ["babel", "flow"], + vscodeLanguageIds: ["javascript", "mongo"], + interpreters: data.interpreters.concat(["nodejs"]) + })), createLanguage(require$$0$6, () => ({ + name: "Flow", + since: "0.0.0", + parsers: ["babel", "flow"], + vscodeLanguageIds: ["javascript"], + aliases: [], + filenames: [], + extensions: [".js.flow"] + })), createLanguage(require$$1$2, () => ({ + since: "0.0.0", + parsers: ["babel", "flow"], + vscodeLanguageIds: ["javascriptreact"] + })), createLanguage(require$$2$1, () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescript"] + })), createLanguage(require$$3$1, () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescriptreact"] + })), createLanguage(require$$4, () => ({ + name: "JSON.stringify", + since: "1.13.0", + parsers: ["json-stringify"], + vscodeLanguageIds: ["json"], + extensions: [], + // .json file defaults to json instead of json-stringify + filenames: ["package.json", "package-lock.json", "composer.json"] + })), createLanguage(require$$4, data => ({ + since: "1.5.0", + parsers: ["json"], + vscodeLanguageIds: ["json"], + filenames: data.filenames.concat([".prettierrc"]) + })), createLanguage(require$$5, data => ({ + since: "1.5.0", + parsers: ["json"], + vscodeLanguageIds: ["jsonc"], + filenames: data.filenames.concat([".eslintrc"]) + })), createLanguage(require$$6, () => ({ + since: "1.13.0", + parsers: ["json5"], + vscodeLanguageIds: ["json5"] + }))]; + const printers$4 = { + estree: printerEstree, + "estree-json": printerEstreeJson + }; + var languageJs = { + languages: languages$4, + options: options$5, + printers: printers$4 + }; + + var json$1 = { + "cjkPattern": "[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d]", + "kPattern": "[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]", + "punctuationPattern": "[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c77\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e4f\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud803[\\udf55-\\udf59]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc8\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\udc3b\\udde2\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71\\udef7-\\udef8\\udfff]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud81b[\\ude97-\\ude9a\\udfe2]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]" + }; + + const { + cjkPattern, + kPattern, + punctuationPattern + } = json$1; + const { + getLast: getLast$4 + } = util$1; + const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"]; + const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]); + const kRegex = new RegExp(kPattern); + const punctuationRegex = new RegExp(punctuationPattern); + /** + * split text into whitespaces and words + * @param {string} text + * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>} + */ + + function splitText(text, options) { + const KIND_NON_CJK = "non-cjk"; + const KIND_CJ_LETTER = "cj-letter"; + const KIND_K_LETTER = "k-letter"; + const KIND_CJK_PUNCTUATION = "cjk-punctuation"; + const nodes = []; + (options.proseWrap === "preserve" ? text : text.replace(new RegExp("(".concat(cjkPattern, ")\n(").concat(cjkPattern, ")"), "g"), "$1$2")).split(/([ \t\n]+)/).forEach((token, index, tokens) => { + // whitespace + if (index % 2 === 1) { + nodes.push({ + type: "whitespace", + value: /\n/.test(token) ? "\n" : " " + }); + return; + } // word separated by whitespace + + + if ((index === 0 || index === tokens.length - 1) && token === "") { + return; + } + + token.split(new RegExp("(".concat(cjkPattern, ")"))).forEach((innerToken, innerIndex, innerTokens) => { + if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") { + return; + } // non-CJK word + + + if (innerIndex % 2 === 0) { + if (innerToken !== "") { + appendNode({ + type: "word", + value: innerToken, + kind: KIND_NON_CJK, + hasLeadingPunctuation: punctuationRegex.test(innerToken[0]), + hasTrailingPunctuation: punctuationRegex.test(getLast$4(innerToken)) + }); + } + + return; + } // CJK character + + + appendNode(punctuationRegex.test(innerToken) ? { + type: "word", + value: innerToken, + kind: KIND_CJK_PUNCTUATION, + hasLeadingPunctuation: true, + hasTrailingPunctuation: true + } : { + type: "word", + value: innerToken, + kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER, + hasLeadingPunctuation: false, + hasTrailingPunctuation: false + }); + }); + }); + return nodes; + + function appendNode(node) { + const lastNode = getLast$4(nodes); + + if (lastNode && lastNode.type === "word") { + if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) { + nodes.push({ + type: "whitespace", + value: " " + }); + } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace + ![lastNode.value, node.value].some(value => /\u3000/.test(value))) { + nodes.push({ + type: "whitespace", + value: "" + }); + } + } + + nodes.push(node); + + function isBetween(kind1, kind2) { + return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1; + } + } + } + + function getOrderedListItemInfo(orderListItem, originalText) { + const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/); + return { + numberText, + marker, + leadingSpaces + }; + } + + function hasGitDiffFriendlyOrderedList(node, options) { + if (!node.ordered) { + return false; + } + + if (node.children.length < 2) { + return false; + } + + const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText); + const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText); + + if (firstNumber === 0 && node.children.length > 2) { + const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText); + return secondNumber === 1 && thirdNumber === 1; + } + + return secondNumber === 1; + } // workaround for https://github.com/remarkjs/remark/issues/351 + // leading and trailing newlines are stripped by remark + + + function getFencedCodeBlockValue(node, originalText) { + const text = originalText.slice(node.position.start.offset, node.position.end.offset); + const leadingSpaceCount = text.match(/^\s*/)[0].length; + const replaceRegex = new RegExp("^\\s{0,".concat(leadingSpaceCount, "}")); + const lineContents = text.split("\n"); + const markerStyle = text[leadingSpaceCount]; // ` or ~ + + const marker = text.slice(leadingSpaceCount).match(new RegExp("^[".concat(markerStyle, "]+")))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces + // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence + + const hasEndMarker = new RegExp("^\\s{0,3}".concat(marker)).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1))); + return lineContents.slice(1, hasEndMarker ? -1 : undefined).map((x, i) => x.slice(getIndent(i + 1)).replace(replaceRegex, "")).join("\n"); + + function getIndent(lineIndex) { + return node.position.indent[lineIndex - 1] - 1; + } + } + + function mapAst(ast, handler) { + return function preorder(node, index, parentStack) { + parentStack = parentStack || []; + const newNode = Object.assign({}, handler(node, index, parentStack)); + + if (newNode.children) { + newNode.children = newNode.children.map((child, index) => { + return preorder(child, index, [newNode].concat(parentStack)); + }); + } + + return newNode; + }(ast, null, null); + } + + var utils$6 = { + mapAst, + splitText, + punctuationPattern, + getFencedCodeBlockValue, + getOrderedListItemInfo, + hasGitDiffFriendlyOrderedList, + INLINE_NODE_TYPES, + INLINE_NODE_WRAPPER_TYPES + }; + + const { + builders: { + hardline: hardline$b, + literalline: literalline$5, + concat: concat$f, + markAsRoot: markAsRoot$3 + }, + utils: { + mapDoc: mapDoc$4 + } + } = document; + const { + getFencedCodeBlockValue: getFencedCodeBlockValue$1 + } = utils$6; + + function embed$4(path, print, textToDoc, options) { + const node = path.getValue(); + + if (node.type === "code" && node.lang !== null) { + // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk) + const langMatch = node.lang.match(/^[A-Za-z0-9_-]+/); + const lang = langMatch ? langMatch[0] : ""; + const parser = getParserName(lang); + + if (parser) { + const styleUnit = options.__inJsTemplate ? "~" : "`"; + const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1)); + const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), { + parser + }); + return markAsRoot$3(concat$f([style, node.lang, hardline$b, replaceNewlinesWithLiterallines(doc), style])); + } + } + + if (node.type === "yaml") { + return markAsRoot$3(concat$f(["---", hardline$b, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, { + parser: "yaml" + })) : "", "---"])); + } // MDX + + + switch (node.type) { + case "importExport": + return textToDoc(node.value, { + parser: "babel" + }); + + case "jsx": + return textToDoc("<$>".concat(node.value, "</$>"), { + parser: "__js_expression", + rootMarker: "mdx" + }); + } + + return null; + + function getParserName(lang) { + const supportInfo = support.getSupportInfo({ + plugins: options.plugins + }); + const language = supportInfo.languages.find(language => language.name.toLowerCase() === lang || language.aliases && language.aliases.includes(lang) || language.extensions && language.extensions.find(ext => ext === ".".concat(lang))); + + if (language) { + return language.parsers[0]; + } + + return null; + } + + function replaceNewlinesWithLiterallines(doc) { + return mapDoc$4(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$f(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$5)) : currentDoc); + } + } + + var embed_1$2 = embed$4; + + const pragmas = ["format", "prettier"]; + + function startWithPragma(text) { + const pragma = "@(".concat(pragmas.join("|"), ")"); + const regex = new RegExp(["<!--\\s*".concat(pragma, "\\s*-->"), "<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*".concat(pragma, "[^\\S\n]*($|\n)[\\s\\S]*\n.*-->")].join("|"), "m"); + const matched = text.match(regex); + return matched && matched.index === 0; + } + + var pragma$4 = { + startWithPragma, + hasPragma: text => startWithPragma(frontMatter(text).content.trimStart()), + insertPragma: text => { + const extracted = frontMatter(text); + const pragma = "<!-- @".concat(pragmas[0], " -->"); + return extracted.frontMatter ? "".concat(extracted.frontMatter.raw, "\n\n").concat(pragma, "\n\n").concat(extracted.content) : "".concat(pragma, "\n\n").concat(extracted.content); + } + }; + + const { + getOrderedListItemInfo: getOrderedListItemInfo$1, + mapAst: mapAst$1, + splitText: splitText$1 + } = utils$6; // 0x0 ~ 0x10ffff + // eslint-disable-next-line no-control-regex + + const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/; + + function preprocess$2(ast, options) { + ast = restoreUnescapedCharacter(ast, options); + ast = mergeContinuousTexts(ast); + ast = transformInlineCode(ast); + ast = transformIndentedCodeblockAndMarkItsParentList(ast, options); + ast = markAlignedList(ast, options); + ast = splitTextIntoSentences(ast, options); + ast = transformImportExport(ast); + ast = mergeContinuousImportExport(ast); + return ast; + } + + function transformImportExport(ast) { + return mapAst$1(ast, node => { + if (node.type !== "import" && node.type !== "export") { + return node; + } + + return Object.assign({}, node, { + type: "importExport" + }); + }); + } + + function transformInlineCode(ast) { + return mapAst$1(ast, node => { + if (node.type !== "inlineCode") { + return node; + } + + return Object.assign({}, node, { + value: node.value.replace(/\s+/g, " ") + }); + }); + } + + function restoreUnescapedCharacter(ast, options) { + return mapAst$1(ast, node => { + return node.type !== "text" ? node : Object.assign({}, node, { + value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer + isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value + }); + }); + } + + function mergeContinuousImportExport(ast) { + return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({ + type: "importExport", + value: prevNode.value + "\n\n" + node.value, + position: { + start: prevNode.position.start, + end: node.position.end + } + })); + } + + function mergeChildren(ast, shouldMerge, mergeNode) { + return mapAst$1(ast, node => { + if (!node.children) { + return node; + } + + const children = node.children.reduce((current, child) => { + const lastChild = current[current.length - 1]; + + if (lastChild && shouldMerge(lastChild, child)) { + current.splice(-1, 1, mergeNode(lastChild, child)); + } else { + current.push(child); + } + + return current; + }, []); + return Object.assign({}, node, { + children + }); + }); + } + + function mergeContinuousTexts(ast) { + return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({ + type: "text", + value: prevNode.value + node.value, + position: { + start: prevNode.position.start, + end: node.position.end + } + })); + } + + function splitTextIntoSentences(ast, options) { + return mapAst$1(ast, (node, index, [parentNode]) => { + if (node.type !== "text") { + return node; + } + + let { + value + } = node; + + if (parentNode.type === "paragraph") { + if (index === 0) { + value = value.trimStart(); + } + + if (index === parentNode.children.length - 1) { + value = value.trimEnd(); + } + } + + return { + type: "sentence", + position: node.position, + children: splitText$1(value, options) + }; + }); + } + + function transformIndentedCodeblockAndMarkItsParentList(ast, options) { + return mapAst$1(ast, (node, index, parentStack) => { + if (node.type === "code") { + // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it + const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset)); + node.isIndented = isIndented; + + if (isIndented) { + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; // no need to check checked items + + if (parent.hasIndentedCodeblock) { + break; + } + + if (parent.type === "list") { + parent.hasIndentedCodeblock = true; + } + } + } + } + + return node; + }); + } + + function markAlignedList(ast, options) { + return mapAst$1(ast, (node, index, parentStack) => { + if (node.type === "list" && node.children.length !== 0) { + // if one of its parents is not aligned, it's not possible to be aligned in sub-lists + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; + + if (parent.type === "list" && !parent.isAligned) { + node.isAligned = false; + return node; + } + } + + node.isAligned = isAligned(node); + } + + return node; + }); + + function getListItemStart(listItem) { + return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1; + } + + function isAligned(list) { + if (!list.ordered) { + /** + * - 123 + * - 123 + */ + return true; + } + + const [firstItem, secondItem] = list.children; + const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText); + + if (firstInfo.leadingSpaces.length > 1) { + /** + * 1. 123 + * + * 1. 123 + * 1. 123 + */ + return true; + } + + const firstStart = getListItemStart(firstItem); + + if (firstStart === -1) { + /** + * 1. + * + * 1. + * 1. + */ + return false; + } + + if (list.children.length === 1) { + /** + * aligned: + * + * 11. 123 + * + * not aligned: + * + * 1. 123 + */ + return firstStart % options.tabWidth === 0; + } + + const secondStart = getListItemStart(secondItem); + + if (firstStart !== secondStart) { + /** + * 11. 123 + * 1. 123 + * + * 1. 123 + * 11. 123 + */ + return false; + } + + if (firstStart % options.tabWidth === 0) { + /** + * 11. 123 + * 12. 123 + */ + return true; + } + /** + * aligned: + * + * 11. 123 + * 1. 123 + * + * not aligned: + * + * 1. 123 + * 2. 123 + */ + + + const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText); + return secondInfo.leadingSpaces.length > 1; + } + } + + var preprocess_1$2 = preprocess$2; + + const { + builders: { + breakParent: breakParent$4, + concat: concat$g, + join: join$b, + line: line$a, + literalline: literalline$6, + markAsRoot: markAsRoot$4, + hardline: hardline$c, + softline: softline$7, + ifBreak: ifBreak$7, + fill: fill$5, + align: align$2, + indent: indent$9, + group: group$f + }, + utils: { + mapDoc: mapDoc$5 + }, + printer: { + printDocToString: printDocToString$3 + } + } = document; + const { + getFencedCodeBlockValue: getFencedCodeBlockValue$2, + hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1, + splitText: splitText$2, + punctuationPattern: punctuationPattern$1, + INLINE_NODE_TYPES: INLINE_NODE_TYPES$1, + INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1 + } = utils$6; + const { + replaceEndOfLineWith: replaceEndOfLineWith$2 + } = util$1; + const TRAILING_HARDLINE_NODES = ["importExport"]; + const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"]; + const SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"]; + + function genericPrint$5(path, options, print) { + const node = path.getValue(); + + if (shouldRemainTheSameContent(path)) { + return concat$g(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options))); + } + + switch (node.type) { + case "root": + if (node.children.length === 0) { + return ""; + } + + return concat$g([normalizeDoc(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.includes(getLastDescendantNode(node).type) ? hardline$c : ""]); + + case "paragraph": + return printChildren$2(path, options, print, { + postprocessor: fill$5 + }); + + case "sentence": + return printChildren$2(path, options, print); + + case "word": + return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math) + .replace(new RegExp(["(^|".concat(punctuationPattern$1, ")(_+)"), "(_+)(".concat(punctuationPattern$1, "|$)")].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? "".concat(text1).concat(underscore1) : "".concat(underscore2).concat(text2)).replace(/_/g, "\\_")); + // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis + + case "whitespace": + { + const parentNode = path.getParentNode(); + const index = parentNode.children.indexOf(node); + const nextNode = parentNode.children[index + 1]; + const proseWrap = // leading char that may cause different syntax + nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap; + return printLine(path, node.value, { + proseWrap + }); + } + + case "emphasis": + { + const parentNode = path.getParentNode(); + const index = parentNode.children.indexOf(node); + const prevNode = parentNode.children[index - 1]; + const nextNode = parentNode.children[index + 1]; + const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not + prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util$1.getLast(prevNode.children).type === "word" && !util$1.getLast(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation; + const style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_"; + return concat$g([style, printChildren$2(path, options, print), style]); + } + + case "strong": + return concat$g(["**", printChildren$2(path, options, print), "**"]); + + case "delete": + return concat$g(["~~", printChildren$2(path, options, print), "~~"]); + + case "inlineCode": + { + const backtickCount = util$1.getMinNotPresentContinuousCount(node.value, "`"); + const style = "`".repeat(backtickCount || 1); + const gap = backtickCount ? " " : ""; + return concat$g([style, gap, node.value, gap, style]); + } + + case "link": + switch (options.originalText[node.position.start.offset]) { + case "<": + { + const mailto = "mailto:"; + const url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" } + node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url; + return concat$g(["<", url, ">"]); + } + + case "[": + return concat$g(["[", printChildren$2(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]); + + default: + return options.originalText.slice(node.position.start.offset, node.position.end.offset); + } + + case "image": + return concat$g(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]); + + case "blockquote": + return concat$g(["> ", align$2("> ", printChildren$2(path, options, print))]); + + case "heading": + return concat$g(["#".repeat(node.depth) + " ", printChildren$2(path, options, print)]); + + case "code": + { + if (node.isIndented) { + // indented code block + const alignment = " ".repeat(4); + return align$2(alignment, concat$g([alignment, concat$g(replaceEndOfLineWith$2(node.value, hardline$c))])); + } // fenced code block + + + const styleUnit = options.__inJsTemplate ? "~" : "`"; + const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1)); + return concat$g([style, node.lang || "", hardline$c, concat$g(replaceEndOfLineWith$2(getFencedCodeBlockValue$2(node, options.originalText), hardline$c)), hardline$c, style]); + } + + case "yaml": + case "toml": + return options.originalText.slice(node.position.start.offset, node.position.end.offset); + + case "html": + { + const parentNode = path.getParentNode(); + const value = parentNode.type === "root" && util$1.getLast(parentNode.children) === node ? node.value.trimEnd() : node.value; + const isHtmlComment = /^<!--[\s\S]*-->$/.test(value); + return concat$g(replaceEndOfLineWith$2(value, isHtmlComment ? hardline$c : markAsRoot$4(literalline$6))); + } + + case "list": + { + const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode()); + const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options); + return printChildren$2(path, options, print, { + processor: (childPath, index) => { + const prefix = getPrefix(); + const childNode = childPath.getValue(); + + if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) { + return concat$g([prefix, printListItem(childPath, options, print, prefix)]); + } + + return concat$g([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]); + + function getPrefix() { + const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* "; + return node.isAligned || + /* workaround for https://github.com/remarkjs/remark/issues/315 */ + node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix; + } + } + }); + } + + case "thematicBreak": + { + const counter = getAncestorCounter$1(path, "list"); + + if (counter === -1) { + return "---"; + } + + const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1)); + return nthSiblingIndex % 2 === 0 ? "***" : "---"; + } + + case "linkReference": + return concat$g(["[", printChildren$2(path, options, print), "]", node.referenceType === "full" ? concat$g(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]); + + case "imageReference": + switch (node.referenceType) { + case "full": + return concat$g(["![", node.alt || "", "][", node.identifier, "]"]); + + default: + return concat$g(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]); + } + + case "definition": + { + const lineOrSpace = options.proseWrap === "always" ? line$a : " "; + return group$f(concat$g([concat$g(["[", node.identifier, "]:"]), indent$9(concat$g([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$g([lineOrSpace, printTitle(node.title, options, false)])]))])); + } + + case "footnote": + return concat$g(["[^", printChildren$2(path, options, print), "]"]); + + case "footnoteReference": + return concat$g(["[^", node.identifier, "]"]); + + case "footnoteDefinition": + { + const nextNode = path.getParentNode().children[path.getName() + 1]; + const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line); + return concat$g(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$2(path, options, print) : group$f(concat$g([align$2(" ".repeat(options.tabWidth), printChildren$2(path, options, print, { + processor: (childPath, index) => { + return index === 0 ? group$f(concat$g([softline$7, childPath.call(print)])) : childPath.call(print); + } + })), nextNode && nextNode.type === "footnoteDefinition" ? softline$7 : ""]))]); + } + + case "table": + return printTable(path, options, print); + + case "tableCell": + return printChildren$2(path, options, print); + + case "break": + return /\s/.test(options.originalText[node.position.start.offset]) ? concat$g([" ", markAsRoot$4(literalline$6)]) : concat$g(["\\", hardline$c]); + + case "liquidNode": + return concat$g(replaceEndOfLineWith$2(node.value, hardline$c)); + // MDX + + case "importExport": + case "jsx": + return node.value; + // fallback to the original text if multiparser failed + + case "math": + return concat$g(["$$", hardline$c, node.value ? concat$g([concat$g(replaceEndOfLineWith$2(node.value, hardline$c)), hardline$c]) : "", "$$"]); + + case "inlineMath": + { + // remark-math trims content but we don't want to remove whitespaces + // since it's very possible that it's recognized as math accidentally + return options.originalText.slice(options.locStart(node), options.locEnd(node)); + } + + case "tableRow": // handled in "table" + + case "listItem": // handled in "list" + + default: + throw new Error("Unknown markdown type ".concat(JSON.stringify(node.type))); + } + } + + function printListItem(path, options, print, listPrefix) { + const node = path.getValue(); + const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] "; + return concat$g([prefix, printChildren$2(path, options, print, { + processor: (childPath, index) => { + if (index === 0 && childPath.getValue().type !== "list") { + return align$2(" ".repeat(prefix.length), childPath.call(print)); + } + + const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block + ); + return concat$g([alignment, align$2(alignment, childPath.call(print))]); + } + })]); + } + + function alignListPrefix(prefix, options) { + const additionalSpaces = getAdditionalSpaces(); + return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block + ); + + function getAdditionalSpaces() { + const restSpaces = prefix.length % options.tabWidth; + return restSpaces === 0 ? 0 : options.tabWidth - restSpaces; + } + } + + function getNthListSiblingIndex(node, parentNode) { + return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered); + } + + function getNthSiblingIndex(node, parentNode, condition) { + condition = condition || (() => true); + + let index = -1; + + for (const childNode of parentNode.children) { + if (childNode.type === node.type && condition(childNode)) { + index++; + } else { + index = -1; + } + + if (childNode === node) { + return index; + } + } + } + + function getAncestorCounter$1(path, typeOrTypes) { + const types = [].concat(typeOrTypes); + let counter = -1; + let ancestorNode; + + while (ancestorNode = path.getParentNode(++counter)) { + if (types.includes(ancestorNode.type)) { + return counter; + } + } + + return -1; + } + + function getAncestorNode$2(path, typeOrTypes) { + const counter = getAncestorCounter$1(path, typeOrTypes); + return counter === -1 ? null : path.getParentNode(counter); + } + + function printLine(path, value, options) { + if (options.proseWrap === "preserve" && value === "\n") { + return hardline$c; + } + + const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES); + return value !== "" ? isBreakable ? line$a : " " : isBreakable ? softline$7 : ""; + } + + function printTable(path, options, print) { + const hardlineWithoutBreakParent = hardline$c.parts[0]; + const node = path.getValue(); + const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } } + + path.map(rowPath => { + const rowContents = []; + rowPath.map(cellPath => { + rowContents.push(printDocToString$3(cellPath.call(print), options).formatted); + }, "children"); + contents.push(rowContents); + }, "children"); // Get the width of each column + + const columnMaxWidths = contents.reduce((currentWidths, rowContents) => currentWidths.map((width, columnIndex) => Math.max(width, util$1.getStringWidth(rowContents[columnIndex]))), contents[0].map(() => 3) // minimum width = 3 (---, :--, :-:, --:) + ); + const alignedTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents)))]); + + if (options.proseWrap !== "never") { + return concat$g([breakParent$4, alignedTable]); + } // Only if the --prose-wrap never is set and it exceeds the print width. + + + const compactTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0], + /* isCompact */ + true), printSeparator( + /* isCompact */ + true), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents, + /* isCompact */ + true)))]); + return concat$g([breakParent$4, group$f(ifBreak$7(compactTable, alignedTable))]); + + function printSeparator(isCompact) { + return concat$g(["| ", join$b(" | ", columnMaxWidths.map((width, index) => { + const spaces = isCompact ? 3 : width; + + switch (node.align[index]) { + case "left": + return ":" + "-".repeat(spaces - 1); + + case "right": + return "-".repeat(spaces - 1) + ":"; + + case "center": + return ":" + "-".repeat(spaces - 2) + ":"; + + default: + return "-".repeat(spaces); + } + })), " |"]); + } + + function printRow(rowContents, isCompact) { + return concat$g(["| ", join$b(" | ", isCompact ? rowContents : rowContents.map((rowContent, columnIndex) => { + switch (node.align[columnIndex]) { + case "right": + return alignRight(rowContent, columnMaxWidths[columnIndex]); + + case "center": + return alignCenter(rowContent, columnMaxWidths[columnIndex]); + + default: + return alignLeft(rowContent, columnMaxWidths[columnIndex]); + } + })), " |"]); + } + + function alignLeft(text, width) { + const spaces = width - util$1.getStringWidth(text); + return concat$g([text, " ".repeat(spaces)]); + } + + function alignRight(text, width) { + const spaces = width - util$1.getStringWidth(text); + return concat$g([" ".repeat(spaces), text]); + } + + function alignCenter(text, width) { + const spaces = width - util$1.getStringWidth(text); + const left = Math.floor(spaces / 2); + const right = spaces - left; + return concat$g([" ".repeat(left), text, " ".repeat(right)]); + } + } + + function printRoot(path, options, print) { + /** @typedef {{ index: number, offset: number }} IgnorePosition */ + + /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */ + const ignoreRanges = []; + /** @type {IgnorePosition | null} */ + + let ignoreStart = null; + const { + children + } = path.getValue(); + children.forEach((childNode, index) => { + switch (isPrettierIgnore$1(childNode)) { + case "start": + if (ignoreStart === null) { + ignoreStart = { + index, + offset: childNode.position.end.offset + }; + } + + break; + + case "end": + if (ignoreStart !== null) { + ignoreRanges.push({ + start: ignoreStart, + end: { + index, + offset: childNode.position.start.offset + } + }); + ignoreStart = null; + } + + break; + } + }); + return printChildren$2(path, options, print, { + processor: (childPath, index) => { + if (ignoreRanges.length !== 0) { + const ignoreRange = ignoreRanges[0]; + + if (index === ignoreRange.start.index) { + return concat$g([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]); + } + + if (ignoreRange.start.index < index && index < ignoreRange.end.index) { + return false; + } + + if (index === ignoreRange.end.index) { + ignoreRanges.shift(); + return false; + } + } + + return childPath.call(print); + } + }); + } + + function printChildren$2(path, options, print, events) { + events = events || {}; + const postprocessor = events.postprocessor || concat$g; + + const processor = events.processor || (childPath => childPath.call(print)); + + const node = path.getValue(); + const parts = []; + let lastChildNode; + path.map((childPath, index) => { + const childNode = childPath.getValue(); + const result = processor(childPath, index); + + if (result !== false) { + const data = { + parts, + prevNode: lastChildNode, + parentNode: node, + options + }; + + if (!shouldNotPrePrintHardline(childNode, data)) { + parts.push(hardline$c); + + if (lastChildNode && TRAILING_HARDLINE_NODES.includes(lastChildNode.type)) { + if (shouldPrePrintTripleHardline(childNode, data)) { + parts.push(hardline$c); + } + } else { + if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) { + parts.push(hardline$c); + } + + if (shouldPrePrintTripleHardline(childNode, data)) { + parts.push(hardline$c); + } + } + } + + parts.push(result); + lastChildNode = childNode; + } + }, "children"); + return postprocessor(parts); + } + + function getLastDescendantNode(node) { + let current = node; + + while (current.children && current.children.length !== 0) { + current = current.children[current.children.length - 1]; + } + + return current; + } + /** @return {false | 'next' | 'start' | 'end'} */ + + + function isPrettierIgnore$1(node) { + if (node.type !== "html") { + return false; + } + + const match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/); + return match === null ? false : match[1] ? match[1] : "next"; + } + + function shouldNotPrePrintHardline(node, data) { + const isFirstNode = data.parts.length === 0; + const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type); + const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type); + return isFirstNode || isInlineNode || isInlineHTML; + } + + function shouldPrePrintDoubleHardline(node, data) { + const isSequence = (data.prevNode && data.prevNode.type) === node.type; + const isSiblingNode = isSequence && SIBLING_NODE_TYPES.includes(node.type); + const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose; + const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose; + const isPrevNodePrettierIgnore = isPrettierIgnore$1(data.prevNode) === "next"; + const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line; + const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line; + return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem); + } + + function shouldPrePrintTripleHardline(node, data) { + const isPrevNodeList = data.prevNode && data.prevNode.type === "list"; + const isIndentedCode = node.type === "code" && node.isIndented; + return isPrevNodeList && isIndentedCode; + } + + function shouldRemainTheSameContent(path) { + const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]); + return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full"); + } + + function normalizeDoc(doc) { + return mapDoc$5(doc, currentDoc => { + if (!currentDoc.parts) { + return currentDoc; + } + + if (currentDoc.type === "concat" && currentDoc.parts.length === 1) { + return currentDoc.parts[0]; + } + + const parts = currentDoc.parts.reduce((parts, part) => { + if (part.type === "concat") { + parts.push(...part.parts); + } else if (part !== "") { + parts.push(part); + } + + return parts; + }, []); + return Object.assign({}, currentDoc, { + parts: normalizeParts$2(parts) + }); + }); + } + + function printUrl(url, dangerousCharOrChars) { + const dangerousChars = [" "].concat(dangerousCharOrChars || []); + return new RegExp(dangerousChars.map(x => "\\".concat(x)).join("|")).test(url) ? "<".concat(url, ">") : url; + } + + function printTitle(title, options, printSpace) { + if (printSpace == null) { + printSpace = true; + } + + if (!title) { + return ""; + } + + if (printSpace) { + return " " + printTitle(title, options, false); + } + + if (title.includes('"') && title.includes("'") && !title.includes(")")) { + return "(".concat(title, ")"); // avoid escaped quotes + } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split + + + const singleCount = title.split("'").length - 1; + const doubleCount = title.split('"').length - 1; + const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"'; + title = title.replace(new RegExp("(".concat(quote, ")"), "g"), "\\$1"); + return "".concat(quote).concat(title).concat(quote); + } + + function normalizeParts$2(parts) { + return parts.reduce((current, part) => { + const lastPart = util$1.getLast(current); + + if (typeof lastPart === "string" && typeof part === "string") { + current.splice(-1, 1, lastPart + part); + } else { + current.push(part); + } + + return current; + }, []); + } + + function clamp(value, min, max) { + return value < min ? min : value > max ? max : value; + } + + function clean$6(ast, newObj, parent) { + delete newObj.position; + delete newObj.raw; // front-matter + // for codeblock + + if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") { + delete newObj.value; + } + + if (ast.type === "list") { + delete newObj.isAligned; + } // texts can be splitted or merged + + + if (ast.type === "text") { + return null; + } + + if (ast.type === "inlineCode") { + newObj.value = ast.value.replace(/[ \t\n]+/g, " "); + } // for insert pragma + + + if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || (parent.children[0].type === "yaml" || parent.children[0].type === "toml") && parent.children[1] === ast) && ast.type === "html" && pragma$4.startWithPragma(ast.value)) { + return null; + } + } + + function hasPrettierIgnore$6(path) { + const index = +path.getName(); + + if (index === 0) { + return false; + } + + const prevNode = path.getParentNode().children[index - 1]; + return isPrettierIgnore$1(prevNode) === "next"; + } + + var printerMarkdown = { + preprocess: preprocess_1$2, + print: genericPrint$5, + embed: embed_1$2, + massageAstNode: clean$6, + hasPrettierIgnore: hasPrettierIgnore$6, + insertPragma: pragma$4.insertPragma + }; + + var options$6 = { + proseWrap: commonOptions.proseWrap, + singleQuote: commonOptions.singleQuote + }; + + var name$g = "Markdown"; + var type$f = "prose"; + var aliases$5 = [ + "pandoc" + ]; + var aceMode$f = "markdown"; + var codemirrorMode$b = "gfm"; + var codemirrorMimeType$b = "text/x-gfm"; + var wrap = true; + var extensions$f = [ + ".md", + ".markdown", + ".mdown", + ".mdwn", + ".mdx", + ".mkd", + ".mkdn", + ".mkdown", + ".ronn", + ".workbook" + ]; + var filenames$3 = [ + "contents.lr" + ]; + var tmScope$f = "source.gfm"; + var languageId$f = 222; + var Markdown = { + name: name$g, + type: type$f, + aliases: aliases$5, + aceMode: aceMode$f, + codemirrorMode: codemirrorMode$b, + codemirrorMimeType: codemirrorMimeType$b, + wrap: wrap, + extensions: extensions$f, + filenames: filenames$3, + tmScope: tmScope$f, + languageId: languageId$f + }; + + var Markdown$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$g, + type: type$f, + aliases: aliases$5, + aceMode: aceMode$f, + codemirrorMode: codemirrorMode$b, + codemirrorMimeType: codemirrorMimeType$b, + wrap: wrap, + extensions: extensions$f, + filenames: filenames$3, + tmScope: tmScope$f, + languageId: languageId$f, + 'default': Markdown + }); + + var require$$0$7 = getCjsExportFromNamespace(Markdown$1); + + const languages$5 = [createLanguage(require$$0$7, data => ({ + since: "1.8.0", + parsers: ["markdown"], + vscodeLanguageIds: ["markdown"], + filenames: data.filenames.concat(["README"]), + extensions: data.extensions.filter(extension => extension !== ".mdx") + })), createLanguage(require$$0$7, () => ({ + name: "MDX", + since: "1.15.0", + parsers: ["mdx"], + vscodeLanguageIds: ["mdx"], + filenames: [], + extensions: [".mdx"] + }))]; + const printers$5 = { + mdast: printerMarkdown + }; + var languageMarkdown = { + languages: languages$5, + options: options$6, + printers: printers$5 + }; + + function isPragma(text) { + return /^\s*@(prettier|format)\s*$/.test(text); + } + + function hasPragma$4(text) { + return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text); + } + + function insertPragma$8(text) { + return "# @format\n\n".concat(text); + } + + var pragma$5 = { + isPragma, + hasPragma: hasPragma$4, + insertPragma: insertPragma$8 + }; + + const { + getLast: getLast$5 + } = util$1; + + function getAncestorCount(path, filter) { + let counter = 0; + const pathStackLength = path.stack.length - 1; + + for (let i = 0; i < pathStackLength; i++) { + const value = path.stack[i]; + + if (isNode(value) && filter(value)) { + counter++; + } + } + + return counter; + } + /** + * @param {any} value + * @param {string[]=} types + */ + + + function isNode(value, types) { + return value && typeof value.type === "string" && (!types || types.includes(value.type)); + } + + function mapNode(node, callback, parent) { + return callback("children" in node ? Object.assign({}, node, { + children: node.children.map(childNode => mapNode(childNode, callback, node)) + }) : node, parent); + } + + function defineShortcut(x, key, getter) { + Object.defineProperty(x, key, { + get: getter, + enumerable: false + }); + } + + function isNextLineEmpty$5(node, text) { + let newlineCount = 0; + const textLength = text.length; + + for (let i = node.position.end.offset - 1; i < textLength; i++) { + const char = text[i]; + + if (char === "\n") { + newlineCount++; + } + + if (newlineCount === 1 && /\S/.test(char)) { + return false; + } + + if (newlineCount === 2) { + return true; + } + } + + return false; + } + + function isLastDescendantNode(path) { + const node = path.getValue(); + + switch (node.type) { + case "tag": + case "anchor": + case "comment": + return false; + } + + const pathStackLength = path.stack.length; + + for (let i = 1; i < pathStackLength; i++) { + const item = path.stack[i]; + const parentItem = path.stack[i - 1]; + + if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) { + return false; + } + } + + return true; + } + + function getLastDescendantNode$1(node) { + return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$5(node.children)) : node; + } + + function isPrettierIgnore$2(comment) { + return comment.value.trim() === "prettier-ignore"; + } + + function hasPrettierIgnore$7(path) { + const node = path.getValue(); + + if (node.type === "documentBody") { + const document = path.getParentNode(); + return hasEndComments(document.head) && isPrettierIgnore$2(getLast$5(document.head.endComments)); + } + + return hasLeadingComments(node) && isPrettierIgnore$2(getLast$5(node.leadingComments)); + } + + function isEmptyNode(node) { + return (!node.children || node.children.length === 0) && !hasComments(node); + } + + function hasComments(node) { + return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$2(node) || hasEndComments(node); + } + + function hasLeadingComments(node) { + return node && node.leadingComments && node.leadingComments.length !== 0; + } + + function hasMiddleComments(node) { + return node && node.middleComments && node.middleComments.length !== 0; + } + + function hasIndicatorComment(node) { + return node && node.indicatorComment; + } + + function hasTrailingComment$2(node) { + return node && node.trailingComment; + } + + function hasEndComments(node) { + return node && node.endComments && node.endComments.length !== 0; + } + /** + * " a b c d e f " -> [" a b", "c d", "e f "] + */ + + + function splitWithSingleSpace(text) { + const parts = []; + let lastPart = undefined; + + for (const part of text.split(/( +)/g)) { + if (part !== " ") { + if (lastPart === " ") { + parts.push(part); + } else { + parts.push((parts.pop() || "") + part); + } + } else if (lastPart === undefined) { + parts.unshift(""); + } + + lastPart = part; + } + + if (lastPart === " ") { + parts.push((parts.pop() || "") + " "); + } + + if (parts[0] === "") { + parts.shift(); + parts.unshift(" " + (parts.shift() || "")); + } + + return parts; + } + + function getFlowScalarLineContents(nodeType, content, options) { + const rawLineContents = content.split("\n").map((lineContent, index, lineContents) => index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimEnd() : lineContent.trimStart()); + + if (options.proseWrap === "preserve") { + return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]); + } + + return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved + nodeType === "quoteDouble" && getLast$5(getLast$5(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords); + } + + function getBlockValueLineContents(node, { + parentIndent, + isLastDescendant, + options + }) { + const content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|` + .match(/^[^\n]*?\n([\s\S]*)$/)[1]; + const leadingSpaceCount = node.indent === null ? (match => match ? match[1].length : Infinity)(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent; + const rawLineContents = content.split("\n").map(lineContent => lineContent.slice(leadingSpaceCount)); + + if (options.proseWrap === "preserve" || node.type === "blockLiteral") { + return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent])); + } + + return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$5(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => lineContentWords.reduce((reduced, word) => // disallow trailing spaces + reduced.length !== 0 && /\s$/.test(getLast$5(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word), [])).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords)); + + function removeUnnecessaryTrailingNewlines(lineContents) { + if (node.chomping === "keep") { + return getLast$5(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents; + } + + let trailingNewlineCount = 0; + + for (let i = lineContents.length - 1; i >= 0; i--) { + if (lineContents[i].length === 0) { + trailingNewlineCount++; + } else { + break; + } + } + + return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line + lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount); + } + } + + var utils$7 = { + getLast: getLast$5, + getAncestorCount, + isNode, + isEmptyNode, + mapNode, + defineShortcut, + isNextLineEmpty: isNextLineEmpty$5, + isLastDescendantNode, + getBlockValueLineContents, + getFlowScalarLineContents, + getLastDescendantNode: getLastDescendantNode$1, + hasPrettierIgnore: hasPrettierIgnore$7, + hasLeadingComments, + hasMiddleComments, + hasIndicatorComment, + hasTrailingComment: hasTrailingComment$2, + hasEndComments + }; + + const { + insertPragma: insertPragma$9, + isPragma: isPragma$1 + } = pragma$5; + const { + getAncestorCount: getAncestorCount$1, + getBlockValueLineContents: getBlockValueLineContents$1, + getFlowScalarLineContents: getFlowScalarLineContents$1, + getLast: getLast$6, + getLastDescendantNode: getLastDescendantNode$2, + hasLeadingComments: hasLeadingComments$1, + hasMiddleComments: hasMiddleComments$1, + hasIndicatorComment: hasIndicatorComment$1, + hasTrailingComment: hasTrailingComment$3, + hasEndComments: hasEndComments$1, + hasPrettierIgnore: hasPrettierIgnore$8, + isLastDescendantNode: isLastDescendantNode$1, + isNextLineEmpty: isNextLineEmpty$6, + isNode: isNode$1, + isEmptyNode: isEmptyNode$1, + defineShortcut: defineShortcut$1, + mapNode: mapNode$1 + } = utils$7; + const docBuilders$2 = document.builders; + const { + conditionalGroup: conditionalGroup$2, + breakParent: breakParent$5, + concat: concat$h, + dedent: dedent$3, + dedentToRoot: dedentToRoot$3, + fill: fill$6, + group: group$g, + hardline: hardline$d, + ifBreak: ifBreak$8, + join: join$c, + line: line$b, + lineSuffix: lineSuffix$2, + literalline: literalline$7, + markAsRoot: markAsRoot$5, + softline: softline$8 + } = docBuilders$2; + const { + replaceEndOfLineWith: replaceEndOfLineWith$3 + } = util$1; + + function preprocess$3(ast) { + return mapNode$1(ast, defineShortcuts); + } + + function defineShortcuts(node) { + switch (node.type) { + case "document": + defineShortcut$1(node, "head", () => node.children[0]); + defineShortcut$1(node, "body", () => node.children[1]); + break; + + case "documentBody": + case "sequenceItem": + case "flowSequenceItem": + case "mappingKey": + case "mappingValue": + defineShortcut$1(node, "content", () => node.children[0]); + break; + + case "mappingItem": + case "flowMappingItem": + defineShortcut$1(node, "key", () => node.children[0]); + defineShortcut$1(node, "value", () => node.children[1]); + break; + } + + return node; + } + + function genericPrint$6(path, options, print) { + const node = path.getValue(); + const parentNode = path.getParentNode(); + const tag = !node.tag ? "" : path.call(print, "tag"); + const anchor = !node.anchor ? "" : path.call(print, "anchor"); + const nextEmptyLine = isNode$1(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : ""; + return concat$h([node.type !== "mappingValue" && hasLeadingComments$1(node) ? concat$h([join$c(hardline$d, path.map(print, "leadingComments")), hardline$d]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode$1(node, ["sequence", "mapping"]) && !hasMiddleComments$1(node) ? hardline$d : " " : "", hasMiddleComments$1(node) ? concat$h([node.middleComments.length === 1 ? "" : hardline$d, join$c(hardline$d, path.map(print, "middleComments")), hardline$d]) : "", hasPrettierIgnore$8(path) ? concat$h(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset), literalline$7)) : group$g(_print(node, parentNode, path, options, print)), hasTrailingComment$3(node) && !isNode$1(node, ["document", "documentHead"]) ? lineSuffix$2(concat$h([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$5, path.call(print, "trailingComment")])) : "", nextEmptyLine, hasEndComments$1(node) && !isNode$1(node, ["documentHead", "documentBody"]) ? align$3(node.type === "sequenceItem" ? 2 : 0, concat$h([hardline$d, join$c(hardline$d, path.map(print, "endComments"))])) : ""]); + } + + function _print(node, parentNode, path, options, print) { + switch (node.type) { + case "root": + return concat$h([join$c(hardline$d, path.map((childPath, index) => { + const document = node.children[index]; + const nextDocument = node.children[index + 1]; + return concat$h([print(childPath), shouldPrintDocumentEndMarker(document, nextDocument) ? concat$h([hardline$d, "...", hasTrailingComment$3(document) ? concat$h([" ", path.call(print, "trailingComment")]) : ""]) : !nextDocument || hasTrailingComment$3(nextDocument.head) ? "" : concat$h([hardline$d, "---"])]); + }, "children")), node.children.length === 0 || (lastDescendantNode => isNode$1(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep")(getLastDescendantNode$2(node)) ? "" : hardline$d]); + + case "document": + { + const nextDocument = parentNode.children[path.getName() + 1]; + return join$c(hardline$d, [shouldPrintDocumentHeadEndMarker(node, nextDocument, parentNode, options) === "head" ? join$c(hardline$d, [node.head.children.length === 0 && node.head.endComments.length === 0 ? "" : path.call(print, "head"), concat$h(["---", hasTrailingComment$3(node.head) ? concat$h([" ", path.call(print, "head", "trailingComment")]) : ""])].filter(Boolean)) : "", shouldPrintDocumentBody(node) ? path.call(print, "body") : ""].filter(Boolean)); + } + + case "documentHead": + return join$c(hardline$d, [].concat(path.map(print, "children"), path.map(print, "endComments"))); + + case "documentBody": + { + const children = join$c(hardline$d, path.map(print, "children")).parts; + const endComments = join$c(hardline$d, path.map(print, "endComments")).parts; + const separator = children.length === 0 || endComments.length === 0 ? "" : (lastDescendantNode => isNode$1(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true) + "" : // an extra newline for better readability + concat$h([hardline$d, hardline$d]) : hardline$d)(getLastDescendantNode$2(node)); + return concat$h([].concat(children, separator, endComments)); + } + + case "directive": + return concat$h(["%", join$c(" ", [node.name].concat(node.parameters))]); + + case "comment": + return concat$h(["#", node.value]); + + case "alias": + return concat$h(["*", node.value]); + + case "tag": + return options.originalText.slice(node.position.start.offset, node.position.end.offset); + + case "anchor": + return concat$h(["&", node.value]); + + case "plain": + return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options); + + case "quoteDouble": + case "quoteSingle": + { + const singleQuote = "'"; + const doubleQuote = '"'; + const raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1); + + if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) { + // only quoteDouble can use escape chars + // and quoteSingle do not need to escape backslashes + const originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote; + return concat$h([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]); + } else if (raw.includes(doubleQuote)) { + return concat$h([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble + .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]); + } + + if (raw.includes(singleQuote)) { + return concat$h([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle + raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]); + } + + const quote = options.singleQuote ? singleQuote : doubleQuote; + return concat$h([quote, printFlowScalarContent(node.type, raw, options), quote]); + } + + case "blockFolded": + case "blockLiteral": + { + const parentIndent = getAncestorCount$1(path, ancestorNode => isNode$1(ancestorNode, ["sequence", "mapping"])); + const isLastDescendant = isLastDescendantNode$1(path); + return concat$h([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasIndicatorComment$1(node) ? concat$h([" ", path.call(print, "indicatorComment")]) : "", (node.indent === null ? dedent$3 : dedentToRoot$3)(align$3(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$h(getBlockValueLineContents$1(node, { + parentIndent, + isLastDescendant, + options + }).reduce((reduced, lineWords, index, lineContents) => reduced.concat(index === 0 ? hardline$d : "", fill$6(join$c(line$b, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$d : markAsRoot$5(literalline$7) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$d) : dedentToRoot$3(literalline$7) : ""), []))))]); + } + + case "sequence": + return join$c(hardline$d, path.map(print, "children")); + + case "sequenceItem": + return concat$h(["- ", align$3(2, !node.content ? "" : path.call(print, "content"))]); + + case "mappingKey": + return !node.content ? "" : path.call(print, "content"); + + case "mappingValue": + return !node.content ? "" : path.call(print, "content"); + + case "mapping": + return join$c(hardline$d, path.map(print, "children")); + + case "mappingItem": + case "flowMappingItem": + { + const isEmptyMappingKey = isEmptyNode$1(node.key); + const isEmptyMappingValue = isEmptyNode$1(node.value); + + if (isEmptyMappingKey && isEmptyMappingValue) { + return concat$h([": "]); + } + + const key = path.call(print, "key"); + const value = path.call(print, "value"); + + if (isEmptyMappingValue) { + return node.type === "flowMappingItem" && parentNode.type === "flowMapping" ? key : node.type === "mappingItem" && isAbsolutelyPrintedAsSingleLineNode(node.key.content, options) && !hasTrailingComment$3(node.key.content) && (!parentNode.tag || parentNode.tag.value !== "tag:yaml.org,2002:set") ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ":"]) : concat$h(["? ", align$3(2, key)]); + } + + if (isEmptyMappingKey) { + return concat$h([": ", align$3(2, value)]); + } + + const groupId = Symbol("mappingKey"); + const forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode(node.key.content); + return forceExplicitKey ? concat$h(["? ", align$3(2, key), hardline$d, join$c("", path.map(print, "value", "leadingComments").map(comment => concat$h([comment, hardline$d]))), ": ", align$3(2, value)]) : // force singleline + isSingleLineNode(node.key.content) && !hasLeadingComments$1(node.key.content) && !hasMiddleComments$1(node.key.content) && !hasTrailingComment$3(node.key.content) && !hasEndComments$1(node.key) && !hasLeadingComments$1(node.value.content) && !hasMiddleComments$1(node.value.content) && !hasEndComments$1(node.value) && isAbsolutelyPrintedAsSingleLineNode(node.value.content, options) ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", value]) : conditionalGroup$2([concat$h([group$g(concat$h([ifBreak$8("? "), group$g(align$3(2, key), { + id: groupId + })])), ifBreak$8(concat$h([hardline$d, ": ", align$3(2, value)]), indent(concat$h([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments$1(node.value.content) || hasEndComments$1(node.value) && node.value.content && !isNode$1(node.value.content, ["mapping", "sequence"]) || parentNode.type === "mapping" && hasTrailingComment$3(node.key.content) && isInlineNode(node.value.content) || isNode$1(node.value.content, ["mapping", "sequence"]) && node.value.content.tag === null && node.value.content.anchor === null ? hardline$d : !node.value.content ? "" : line$b, value])), { + groupId + })])]); + } + + case "flowMapping": + case "flowSequence": + { + const openMarker = node.type === "flowMapping" ? "{" : "["; + const closeMarker = node.type === "flowMapping" ? "}" : "]"; + const bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$b : softline$8; + + const isLastItemEmptyMappingItem = node.children.length !== 0 && (lastItem => lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value))(getLast$6(node.children)); + + return concat$h([openMarker, indent(concat$h([bracketSpacing, concat$h(path.map((childPath, index) => concat$h([print(childPath), index === node.children.length - 1 ? "" : concat$h([",", line$b, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]), "children")), ifBreak$8(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]); + } + + case "flowSequenceItem": + return path.call(print, "content"); + // istanbul ignore next + + default: + throw new Error("Unexpected node type ".concat(node.type)); + } + + function indent(doc) { + return docBuilders$2.align(" ".repeat(options.tabWidth), doc); + } + } + + function align$3(n, doc) { + return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc); + } + + function isInlineNode(node) { + if (!node) { + return true; + } + + switch (node.type) { + case "plain": + case "quoteDouble": + case "quoteSingle": + case "alias": + case "flowMapping": + case "flowSequence": + return true; + + default: + return false; + } + } + + function isSingleLineNode(node) { + if (!node) { + return true; + } + + switch (node.type) { + case "plain": + case "quoteDouble": + case "quoteSingle": + return node.position.start.line === node.position.end.line; + + case "alias": + return true; + + default: + return false; + } + } + + function shouldPrintDocumentBody(document) { + return document.body.children.length !== 0 || hasEndComments$1(document.body); + } + + function shouldPrintDocumentEndMarker(document, nextDocument) { + return ( + /** + *... # trailingComment + */ + hasTrailingComment$3(document) || nextDocument && ( + /** + * ... + * %DIRECTIVE + * --- + */ + nextDocument.head.children.length !== 0 || + /** + * ... + * # endComment + * --- + */ + hasEndComments$1(nextDocument.head)) + ); + } + + function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) { + if ( + /** + * --- + * preserve the first document head end marker + */ + root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) || + /** + * %DIRECTIVE + * --- + */ + document.head.children.length !== 0 || + /** + * # end comment + * --- + */ + hasEndComments$1(document.head) || + /** + * --- # trailing comment + */ + hasTrailingComment$3(document.head)) { + return "head"; + } + + if (shouldPrintDocumentEndMarker(document, nextDocument)) { + return false; + } + + return nextDocument ? "root" : false; + } + + function isAbsolutelyPrintedAsSingleLineNode(node, options) { + if (!node) { + return true; + } + + switch (node.type) { + case "plain": + case "quoteSingle": + case "quoteDouble": + break; + + case "alias": + return true; + + default: + return false; + } + + if (options.proseWrap === "preserve") { + return node.position.start.line === node.position.end.line; + } + + if ( // backslash-newline + /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) { + return false; + } + + switch (options.proseWrap) { + case "never": + return !node.value.includes("\n"); + + case "always": + return !/[\n ]/.test(node.value); + // istanbul ignore next + + default: + return false; + } + } + + function needsSpaceInFrontOfMappingValue(node) { + return node.key.content && node.key.content.type === "alias"; + } + + function printNextEmptyLine(path, originalText) { + const node = path.getValue(); + const root = path.stack[0]; + root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || []; + + if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) { + if (isNextLineEmpty$6(node, originalText)) { + root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true; + return softline$8; + } + } + + return ""; + } + + function printFlowScalarContent(nodeType, content, options) { + const lineContents = getFlowScalarLineContents$1(nodeType, content, options); + return join$c(hardline$d, lineContents.map(lineContentWords => fill$6(join$c(line$b, lineContentWords).parts))); + } + + function clean$7(node, newNode + /*, parent */ + ) { + if (isNode$1(newNode)) { + delete newNode.position; + + switch (newNode.type) { + case "comment": + // insert pragma + if (isPragma$1(newNode.value)) { + return null; + } + + break; + + case "quoteDouble": + case "quoteSingle": + newNode.type = "quote"; + break; + } + } + } + + var printerYaml = { + preprocess: preprocess$3, + print: genericPrint$6, + massageAstNode: clean$7, + insertPragma: insertPragma$9 + }; + + var options$7 = { + bracketSpacing: commonOptions.bracketSpacing, + singleQuote: commonOptions.singleQuote, + proseWrap: commonOptions.proseWrap + }; + + var name$h = "YAML"; + var type$g = "data"; + var tmScope$g = "source.yaml"; + var aliases$6 = [ + "yml" + ]; + var extensions$g = [ + ".yml", + ".mir", + ".reek", + ".rviz", + ".sublime-syntax", + ".syntax", + ".yaml", + ".yaml-tmlanguage", + ".yaml.sed", + ".yml.mysql" + ]; + var filenames$4 = [ + ".clang-format", + ".clang-tidy", + ".gemrc", + "glide.lock", + "yarn.lock" + ]; + var aceMode$g = "yaml"; + var codemirrorMode$c = "yaml"; + var codemirrorMimeType$c = "text/x-yaml"; + var languageId$g = 407; + var YAML = { + name: name$h, + type: type$g, + tmScope: tmScope$g, + aliases: aliases$6, + extensions: extensions$g, + filenames: filenames$4, + aceMode: aceMode$g, + codemirrorMode: codemirrorMode$c, + codemirrorMimeType: codemirrorMimeType$c, + languageId: languageId$g + }; + + var YAML$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$h, + type: type$g, + tmScope: tmScope$g, + aliases: aliases$6, + extensions: extensions$g, + filenames: filenames$4, + aceMode: aceMode$g, + codemirrorMode: codemirrorMode$c, + codemirrorMimeType: codemirrorMimeType$c, + languageId: languageId$g, + 'default': YAML + }); + + var require$$0$8 = getCjsExportFromNamespace(YAML$1); + + const languages$6 = [createLanguage(require$$0$8, data => ({ + since: "1.14.0", + parsers: ["yaml"], + vscodeLanguageIds: ["yaml"], + // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629 + filenames: data.filenames.filter(filename => filename !== "yarn.lock") + }))]; + var languageYaml = { + languages: languages$6, + printers: { + yaml: printerYaml + }, + options: options$7 + }; + + const { + version: version$2 + } = require$$0; + const { + getSupportInfo: getSupportInfo$2 + } = support; + const internalPlugins = [languageCss, languageGraphql, languageHandlebars, languageHtml, languageJs, languageMarkdown, languageYaml]; + + function withPlugins(fn, optsArgIdx = 1 // Usually `opts` is the 2nd argument + ) { + return (...args) => { + const opts = args[optsArgIdx] || {}; + const plugins = opts.plugins || []; + args[optsArgIdx] = Object.assign({}, opts, { + plugins: [...internalPlugins, ...(Array.isArray(plugins) ? plugins : Object.values(plugins))] + }); + return fn(...args); + }; + } + + const formatWithCursor = withPlugins(core.formatWithCursor); + var standalone = { + formatWithCursor, + + format(text, opts) { + return formatWithCursor(text, opts).formatted; + }, + + check(text, opts) { + const { + formatted + } = formatWithCursor(text, opts); + return formatted === text; + }, + + doc: document, + getSupportInfo: withPlugins(getSupportInfo$2, 0), + version: version$2, + util: utilShared, + __debug: { + parse: withPlugins(core.parse), + formatAST: withPlugins(core.formatAST), + formatDoc: withPlugins(core.formatDoc), + printToDoc: withPlugins(core.printToDoc), + printDocToString: withPlugins(core.printDocToString) + } + }; + + var standalone$1 = standalone; + + return standalone$1; + +}))); diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/standalone.js.xml b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/standalone.js.xml similarity index 100% rename from bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%401.14.0/standalone.js.xml rename to bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco-editor/prettier%402.0.5/standalone.js.xml diff --git a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco_editor_support.zpt b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco_editor_support.zpt index 314b42c3a4..29c421498a 100644 --- a/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco_editor_support.zpt +++ b/bt5/erp5_monaco_editor/SkinTemplateItem/portal_skins/erp5_monaco_editor/monaco_editor_support.zpt @@ -52,8 +52,8 @@ tal:content='python: "window.monacoEditorWebPackResourceBaseUrl = " + modules["json"].dumps(options["portal_url"]) + " + \"/monaco-editor/\""'> </script> -<script tal:attributes="src string:${options/portal_url}/monaco-editor/prettier@1.14.0/standalone.js"></script> -<script tal:attributes="src string:${options/portal_url}/monaco-editor/prettier@1.14.0/parser-babylon.js"></script> +<script tal:attributes="src string:${options/portal_url}/monaco-editor/prettier@2.0.5/standalone.js"></script> +<script tal:attributes="src string:${options/portal_url}/monaco-editor/prettier@2.0.5/parser-babel.js"></script> <script charset="utf-8"> /* we need to defer import for the monacoEditorWebPackResourceBaseUrl trick to work as expected in ZMI */ @@ -149,8 +149,8 @@ $script.onload = function() { monaco.languages.registerDocumentFormattingEditProvider('javascript', { provideDocumentFormattingEdits(model, options, token) { const text = prettier.format(model.getValue(), { - parser: 'babylon', - plugins: [prettierPlugins.babylon], + parser: 'babel', + plugins: [prettierPlugins.babel], // see http://json.schemastore.org/prettierrc for supported options. singleQuote: true, tabWidth: 2 -- 2.30.9