UNPKG

@striven-erp/striven-editor

Version:
1,380 lines (1,181 loc) 718 kB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["striveneditor"] = factory(); else root["striveneditor"] = factory(); })(window, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 33); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.inherits = inherits; function inherits(parent, child) { var props = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var extended = Object.create(parent.prototype); for (var p in props) { extended[p] = props[p]; } extended.constructor = child; child.prototype = extended; return child; } /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.AMPERSAND = exports.CLOSEPAREN = exports.CLOSEANGLEBRACKET = exports.CLOSEBRACKET = exports.CLOSEBRACE = exports.OPENPAREN = exports.OPENANGLEBRACKET = exports.OPENBRACKET = exports.OPENBRACE = exports.WS = exports.TLD = exports.SYM = exports.UNDERSCORE = exports.SLASH = exports.MAILTO = exports.PROTOCOL = exports.QUERY = exports.POUND = exports.PLUS = exports.NUM = exports.NL = exports.LOCALHOST = exports.PUNCTUATION = exports.DOT = exports.COLON = exports.AT = exports.DOMAIN = exports.Base = undefined; var _createTokenClass = __webpack_require__(8); var _class = __webpack_require__(0); /****************************************************************************** Text Tokens Tokens composed of strings ******************************************************************************/ /** Abstract class used for manufacturing text tokens. Pass in the value this token represents @class TextToken @abstract */ var TextToken = (0, _createTokenClass.createTokenClass)(); TextToken.prototype = { toString: function toString() { return this.v + ''; } }; function inheritsToken(value) { var props = value ? { v: value } : {}; return (0, _class.inherits)(TextToken, (0, _createTokenClass.createTokenClass)(), props); } /** A valid domain token @class DOMAIN @extends TextToken */ var DOMAIN = inheritsToken(); /** @class AT @extends TextToken */ var AT = inheritsToken('@'); /** Represents a single colon `:` character @class COLON @extends TextToken */ var COLON = inheritsToken(':'); /** @class DOT @extends TextToken */ var DOT = inheritsToken('.'); /** A character class that can surround the URL, but which the URL cannot begin or end with. Does not include certain English punctuation like parentheses. @class PUNCTUATION @extends TextToken */ var PUNCTUATION = inheritsToken(); /** The word localhost (by itself) @class LOCALHOST @extends TextToken */ var LOCALHOST = inheritsToken(); /** Newline token @class NL @extends TextToken */ var NL = inheritsToken('\n'); /** @class NUM @extends TextToken */ var NUM = inheritsToken(); /** @class PLUS @extends TextToken */ var PLUS = inheritsToken('+'); /** @class POUND @extends TextToken */ var POUND = inheritsToken('#'); /** Represents a web URL protocol. Supported types include * `http:` * `https:` * `ftp:` * `ftps:` @class PROTOCOL @extends TextToken */ var PROTOCOL = inheritsToken(); /** Represents the start of the email URI protocol @class MAILTO @extends TextToken */ var MAILTO = inheritsToken('mailto:'); /** @class QUERY @extends TextToken */ var QUERY = inheritsToken('?'); /** @class SLASH @extends TextToken */ var SLASH = inheritsToken('/'); /** @class UNDERSCORE @extends TextToken */ var UNDERSCORE = inheritsToken('_'); /** One ore more non-whitespace symbol. @class SYM @extends TextToken */ var SYM = inheritsToken(); /** @class TLD @extends TextToken */ var TLD = inheritsToken(); /** Represents a string of consecutive whitespace characters @class WS @extends TextToken */ var WS = inheritsToken(); /** Opening/closing bracket classes */ var OPENBRACE = inheritsToken('{'); var OPENBRACKET = inheritsToken('['); var OPENANGLEBRACKET = inheritsToken('<'); var OPENPAREN = inheritsToken('('); var CLOSEBRACE = inheritsToken('}'); var CLOSEBRACKET = inheritsToken(']'); var CLOSEANGLEBRACKET = inheritsToken('>'); var CLOSEPAREN = inheritsToken(')'); var AMPERSAND = inheritsToken('&'); exports.Base = TextToken; exports.DOMAIN = DOMAIN; exports.AT = AT; exports.COLON = COLON; exports.DOT = DOT; exports.PUNCTUATION = PUNCTUATION; exports.LOCALHOST = LOCALHOST; exports.NL = NL; exports.NUM = NUM; exports.PLUS = PLUS; exports.POUND = POUND; exports.QUERY = QUERY; exports.PROTOCOL = PROTOCOL; exports.MAILTO = MAILTO; exports.SLASH = SLASH; exports.UNDERSCORE = UNDERSCORE; exports.SYM = SYM; exports.TLD = TLD; exports.WS = WS; exports.OPENBRACE = OPENBRACE; exports.OPENBRACKET = OPENBRACKET; exports.OPENANGLEBRACKET = OPENANGLEBRACKET; exports.OPENPAREN = OPENPAREN; exports.CLOSEBRACE = CLOSEBRACE; exports.CLOSEBRACKET = CLOSEBRACKET; exports.CLOSEANGLEBRACKET = CLOSEANGLEBRACKET; exports.CLOSEPAREN = CLOSEPAREN; exports.AMPERSAND = AMPERSAND; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* AUTO-GENERATED. DO NOT MODIFY. */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. JS Beautifier --------------- Written by Einar Lielmanis, <einar@beautifier.io> https://beautifier.io/ Originally converted to javascript by Vital, <vital76@gmail.com> "End braces on own line" added by Chris J. Shull, <chrisjshull@gmail.com> Parsing improvements for brace-less statements by Liam Newman <bitwiseman@beautifier.io> Usage: js_beautify(js_source_text); js_beautify(js_source_text, options); The options are: indent_size (default 4) - indentation size, indent_char (default space) - character to indent with, preserve_newlines (default true) - whether existing line breaks should be preserved, max_preserve_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk, jslint_happy (default false) - if true, then jslint-stricter mode is enforced. jslint_happy !jslint_happy --------------------------------- function () function() switch () { switch() { case 1: case 1: break; break; } } space_after_anon_function (default false) - should the space before an anonymous function's parens be added, "function()" vs "function ()", NOTE: This option is overridden by jslint_happy (i.e. if jslint_happy is true, space_after_anon_function is true by design) brace_style (default "collapse") - "collapse" | "expand" | "end-expand" | "none" | any of the former + ",preserve-inline" put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line, or attempt to keep them where they are. preserve-inline will try to preserve inline blocks of curly braces space_before_conditional (default true) - should the space before conditional statement be added, "if(true)" vs "if (true)", unescape_strings (default false) - should printable characters in strings encoded in \xNN notation be unescaped, "example" vs "\x65\x78\x61\x6d\x70\x6c\x65" wrap_line_length (default unlimited) - lines should wrap at next opportunity after this number of characters. NOTE: This is not a hard limit. Lines will continue until a point where a newline would be preserved if it were present. end_with_newline (default false) - end output with a newline e.g js_beautify(js_source_text, { 'indent_size': 1, 'indent_char': '\t' }); */ (function() { /* GENERATED_BUILD_OUTPUT */ var legacy_beautify_js; /******/ (function() { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ([ /* 0 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var Beautifier = (__webpack_require__(1).Beautifier), Options = (__webpack_require__(5).Options); function js_beautify(js_source_text, options) { var beautifier = new Beautifier(js_source_text, options); return beautifier.beautify(); } module.exports = js_beautify; module.exports.defaultOptions = function() { return new Options(); }; /***/ }), /* 1 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var Output = (__webpack_require__(2).Output); var Token = (__webpack_require__(3).Token); var acorn = __webpack_require__(4); var Options = (__webpack_require__(5).Options); var Tokenizer = (__webpack_require__(7).Tokenizer); var line_starters = (__webpack_require__(7).line_starters); var positionable_operators = (__webpack_require__(7).positionable_operators); var TOKEN = (__webpack_require__(7).TOKEN); function in_array(what, arr) { return arr.indexOf(what) !== -1; } function ltrim(s) { return s.replace(/^\s+/g, ''); } function generateMapFromStrings(list) { var result = {}; for (var x = 0; x < list.length; x++) { // make the mapped names underscored instead of dash result[list[x].replace(/-/g, '_')] = list[x]; } return result; } function reserved_word(token, word) { return token && token.type === TOKEN.RESERVED && token.text === word; } function reserved_array(token, words) { return token && token.type === TOKEN.RESERVED && in_array(token.text, words); } // Unsure of what they mean, but they work. Worth cleaning up in future. var special_words = ['case', 'return', 'do', 'if', 'throw', 'else', 'await', 'break', 'continue', 'async']; var validPositionValues = ['before-newline', 'after-newline', 'preserve-newline']; // Generate map from array var OPERATOR_POSITION = generateMapFromStrings(validPositionValues); var OPERATOR_POSITION_BEFORE_OR_PRESERVE = [OPERATOR_POSITION.before_newline, OPERATOR_POSITION.preserve_newline]; var MODE = { BlockStatement: 'BlockStatement', // 'BLOCK' Statement: 'Statement', // 'STATEMENT' ObjectLiteral: 'ObjectLiteral', // 'OBJECT', ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]', ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)', Conditional: 'Conditional', //'(COND-EXPRESSION)', Expression: 'Expression' //'(EXPRESSION)' }; function remove_redundant_indentation(output, frame) { // This implementation is effective but has some issues: // - can cause line wrap to happen too soon due to indent removal // after wrap points are calculated // These issues are minor compared to ugly indentation. if (frame.multiline_frame || frame.mode === MODE.ForInitializer || frame.mode === MODE.Conditional) { return; } // remove one indent from each line inside this section output.remove_indent(frame.start_line_index); } // we could use just string.split, but // IE doesn't like returning empty strings function split_linebreaks(s) { //return s.split(/\x0d\x0a|\x0a/); s = s.replace(acorn.allLineBreaks, '\n'); var out = [], idx = s.indexOf("\n"); while (idx !== -1) { out.push(s.substring(0, idx)); s = s.substring(idx + 1); idx = s.indexOf("\n"); } if (s.length) { out.push(s); } return out; } function is_array(mode) { return mode === MODE.ArrayLiteral; } function is_expression(mode) { return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]); } function all_lines_start_with(lines, c) { for (var i = 0; i < lines.length; i++) { var line = lines[i].trim(); if (line.charAt(0) !== c) { return false; } } return true; } function each_line_matches_indent(lines, indent) { var i = 0, len = lines.length, line; for (; i < len; i++) { line = lines[i]; // allow empty lines to pass through if (line && line.indexOf(indent) !== 0) { return false; } } return true; } function Beautifier(source_text, options) { options = options || {}; this._source_text = source_text || ''; this._output = null; this._tokens = null; this._last_last_text = null; this._flags = null; this._previous_flags = null; this._flag_store = null; this._options = new Options(options); } Beautifier.prototype.create_flags = function(flags_base, mode) { var next_indent_level = 0; if (flags_base) { next_indent_level = flags_base.indentation_level; if (!this._output.just_added_newline() && flags_base.line_indent_level > next_indent_level) { next_indent_level = flags_base.line_indent_level; } } var next_flags = { mode: mode, parent: flags_base, last_token: flags_base ? flags_base.last_token : new Token(TOKEN.START_BLOCK, ''), // last token text last_word: flags_base ? flags_base.last_word : '', // last TOKEN.WORD passed declaration_statement: false, declaration_assignment: false, multiline_frame: false, inline_frame: false, if_block: false, else_block: false, class_start_block: false, // class A { INSIDE HERE } or class B extends C { INSIDE HERE } do_block: false, do_while: false, import_block: false, in_case_statement: false, // switch(..){ INSIDE HERE } in_case: false, // we're on the exact line with "case 0:" case_body: false, // the indented case-action block case_block: false, // the indented case-action block is wrapped with {} indentation_level: next_indent_level, alignment: 0, line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level, start_line_index: this._output.get_line_number(), ternary_depth: 0 }; return next_flags; }; Beautifier.prototype._reset = function(source_text) { var baseIndentString = source_text.match(/^[\t ]*/)[0]; this._last_last_text = ''; // pre-last token text this._output = new Output(this._options, baseIndentString); // If testing the ignore directive, start with output disable set to true this._output.raw = this._options.test_output_raw; // Stack of parsing/formatting states, including MODE. // We tokenize, parse, and output in an almost purely a forward-only stream of token input // and formatted output. This makes the beautifier less accurate than full parsers // but also far more tolerant of syntax errors. // // For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type // MODE.BlockStatement on the the stack, even though it could be object literal. If we later // encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";", // most full parsers would die, but the beautifier gracefully falls back to // MODE.BlockStatement and continues on. this._flag_store = []; this.set_mode(MODE.BlockStatement); var tokenizer = new Tokenizer(source_text, this._options); this._tokens = tokenizer.tokenize(); return source_text; }; Beautifier.prototype.beautify = function() { // if disabled, return the input unchanged. if (this._options.disabled) { return this._source_text; } var sweet_code; var source_text = this._reset(this._source_text); var eol = this._options.eol; if (this._options.eol === 'auto') { eol = '\n'; if (source_text && acorn.lineBreak.test(source_text || '')) { eol = source_text.match(acorn.lineBreak)[0]; } } var current_token = this._tokens.next(); while (current_token) { this.handle_token(current_token); this._last_last_text = this._flags.last_token.text; this._flags.last_token = current_token; current_token = this._tokens.next(); } sweet_code = this._output.get_code(eol); return sweet_code; }; Beautifier.prototype.handle_token = function(current_token, preserve_statement_flags) { if (current_token.type === TOKEN.START_EXPR) { this.handle_start_expr(current_token); } else if (current_token.type === TOKEN.END_EXPR) { this.handle_end_expr(current_token); } else if (current_token.type === TOKEN.START_BLOCK) { this.handle_start_block(current_token); } else if (current_token.type === TOKEN.END_BLOCK) { this.handle_end_block(current_token); } else if (current_token.type === TOKEN.WORD) { this.handle_word(current_token); } else if (current_token.type === TOKEN.RESERVED) { this.handle_word(current_token); } else if (current_token.type === TOKEN.SEMICOLON) { this.handle_semicolon(current_token); } else if (current_token.type === TOKEN.STRING) { this.handle_string(current_token); } else if (current_token.type === TOKEN.EQUALS) { this.handle_equals(current_token); } else if (current_token.type === TOKEN.OPERATOR) { this.handle_operator(current_token); } else if (current_token.type === TOKEN.COMMA) { this.handle_comma(current_token); } else if (current_token.type === TOKEN.BLOCK_COMMENT) { this.handle_block_comment(current_token, preserve_statement_flags); } else if (current_token.type === TOKEN.COMMENT) { this.handle_comment(current_token, preserve_statement_flags); } else if (current_token.type === TOKEN.DOT) { this.handle_dot(current_token); } else if (current_token.type === TOKEN.EOF) { this.handle_eof(current_token); } else if (current_token.type === TOKEN.UNKNOWN) { this.handle_unknown(current_token, preserve_statement_flags); } else { this.handle_unknown(current_token, preserve_statement_flags); } }; Beautifier.prototype.handle_whitespace_and_comments = function(current_token, preserve_statement_flags) { var newlines = current_token.newlines; var keep_whitespace = this._options.keep_array_indentation && is_array(this._flags.mode); if (current_token.comments_before) { var comment_token = current_token.comments_before.next(); while (comment_token) { // The cleanest handling of inline comments is to treat them as though they aren't there. // Just continue formatting and the behavior should be logical. // Also ignore unknown tokens. Again, this should result in better behavior. this.handle_whitespace_and_comments(comment_token, preserve_statement_flags); this.handle_token(comment_token, preserve_statement_flags); comment_token = current_token.comments_before.next(); } } if (keep_whitespace) { for (var i = 0; i < newlines; i += 1) { this.print_newline(i > 0, preserve_statement_flags); } } else { if (this._options.max_preserve_newlines && newlines > this._options.max_preserve_newlines) { newlines = this._options.max_preserve_newlines; } if (this._options.preserve_newlines) { if (newlines > 1) { this.print_newline(false, preserve_statement_flags); for (var j = 1; j < newlines; j += 1) { this.print_newline(true, preserve_statement_flags); } } } } }; var newline_restricted_tokens = ['async', 'break', 'continue', 'return', 'throw', 'yield']; Beautifier.prototype.allow_wrap_or_preserved_newline = function(current_token, force_linewrap) { force_linewrap = (force_linewrap === undefined) ? false : force_linewrap; // Never wrap the first token on a line if (this._output.just_added_newline()) { return; } var shouldPreserveOrForce = (this._options.preserve_newlines && current_token.newlines) || force_linewrap; var operatorLogicApplies = in_array(this._flags.last_token.text, positionable_operators) || in_array(current_token.text, positionable_operators); if (operatorLogicApplies) { var shouldPrintOperatorNewline = ( in_array(this._flags.last_token.text, positionable_operators) && in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE) ) || in_array(current_token.text, positionable_operators); shouldPreserveOrForce = shouldPreserveOrForce && shouldPrintOperatorNewline; } if (shouldPreserveOrForce) { this.print_newline(false, true); } else if (this._options.wrap_line_length) { if (reserved_array(this._flags.last_token, newline_restricted_tokens)) { // These tokens should never have a newline inserted // between them and the following expression. return; } this._output.set_wrap_point(); } }; Beautifier.prototype.print_newline = function(force_newline, preserve_statement_flags) { if (!preserve_statement_flags) { if (this._flags.last_token.text !== ';' && this._flags.last_token.text !== ',' && this._flags.last_token.text !== '=' && (this._flags.last_token.type !== TOKEN.OPERATOR || this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) { var next_token = this._tokens.peek(); while (this._flags.mode === MODE.Statement && !(this._flags.if_block && reserved_word(next_token, 'else')) && !this._flags.do_block) { this.restore_mode(); } } } if (this._output.add_new_line(force_newline)) { this._flags.multiline_frame = true; } }; Beautifier.prototype.print_token_line_indentation = function(current_token) { if (this._output.just_added_newline()) { if (this._options.keep_array_indentation && current_token.newlines && (current_token.text === '[' || is_array(this._flags.mode))) { this._output.current_line.set_indent(-1); this._output.current_line.push(current_token.whitespace_before); this._output.space_before_token = false; } else if (this._output.set_indent(this._flags.indentation_level, this._flags.alignment)) { this._flags.line_indent_level = this._flags.indentation_level; } } }; Beautifier.prototype.print_token = function(current_token) { if (this._output.raw) { this._output.add_raw_token(current_token); return; } if (this._options.comma_first && current_token.previous && current_token.previous.type === TOKEN.COMMA && this._output.just_added_newline()) { if (this._output.previous_line.last() === ',') { var popped = this._output.previous_line.pop(); // if the comma was already at the start of the line, // pull back onto that line and reprint the indentation if (this._output.previous_line.is_empty()) { this._output.previous_line.push(popped); this._output.trim(true); this._output.current_line.pop(); this._output.trim(); } // add the comma in front of the next token this.print_token_line_indentation(current_token); this._output.add_token(','); this._output.space_before_token = true; } } this.print_token_line_indentation(current_token); this._output.non_breaking_space = true; this._output.add_token(current_token.text); if (this._output.previous_token_wrapped) { this._flags.multiline_frame = true; } }; Beautifier.prototype.indent = function() { this._flags.indentation_level += 1; this._output.set_indent(this._flags.indentation_level, this._flags.alignment); }; Beautifier.prototype.deindent = function() { if (this._flags.indentation_level > 0 && ((!this._flags.parent) || this._flags.indentation_level > this._flags.parent.indentation_level)) { this._flags.indentation_level -= 1; this._output.set_indent(this._flags.indentation_level, this._flags.alignment); } }; Beautifier.prototype.set_mode = function(mode) { if (this._flags) { this._flag_store.push(this._flags); this._previous_flags = this._flags; } else { this._previous_flags = this.create_flags(null, mode); } this._flags = this.create_flags(this._previous_flags, mode); this._output.set_indent(this._flags.indentation_level, this._flags.alignment); }; Beautifier.prototype.restore_mode = function() { if (this._flag_store.length > 0) { this._previous_flags = this._flags; this._flags = this._flag_store.pop(); if (this._previous_flags.mode === MODE.Statement) { remove_redundant_indentation(this._output, this._previous_flags); } this._output.set_indent(this._flags.indentation_level, this._flags.alignment); } }; Beautifier.prototype.start_of_object_property = function() { return this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement && ( (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || (reserved_array(this._flags.last_token, ['get', 'set']))); }; Beautifier.prototype.start_of_statement = function(current_token) { var start = false; start = start || reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD; start = start || reserved_word(this._flags.last_token, 'do'); start = start || (!(this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement)) && reserved_array(this._flags.last_token, newline_restricted_tokens) && !current_token.newlines; start = start || reserved_word(this._flags.last_token, 'else') && !(reserved_word(current_token, 'if') && !current_token.comments_before); start = start || (this._flags.last_token.type === TOKEN.END_EXPR && (this._previous_flags.mode === MODE.ForInitializer || this._previous_flags.mode === MODE.Conditional)); start = start || (this._flags.last_token.type === TOKEN.WORD && this._flags.mode === MODE.BlockStatement && !this._flags.in_case && !(current_token.text === '--' || current_token.text === '++') && this._last_last_text !== 'function' && current_token.type !== TOKEN.WORD && current_token.type !== TOKEN.RESERVED); start = start || (this._flags.mode === MODE.ObjectLiteral && ( (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || reserved_array(this._flags.last_token, ['get', 'set']))); if (start) { this.set_mode(MODE.Statement); this.indent(); this.handle_whitespace_and_comments(current_token, true); // Issue #276: // If starting a new statement with [if, for, while, do], push to a new line. // if (a) if (b) if(c) d(); else e(); else f(); if (!this.start_of_object_property()) { this.allow_wrap_or_preserved_newline(current_token, reserved_array(current_token, ['do', 'for', 'if', 'while'])); } return true; } return false; }; Beautifier.prototype.handle_start_expr = function(current_token) { // The conditional starts the statement if appropriate. if (!this.start_of_statement(current_token)) { this.handle_whitespace_and_comments(current_token); } var next_mode = MODE.Expression; if (current_token.text === '[') { if (this._flags.last_token.type === TOKEN.WORD || this._flags.last_token.text === ')') { // this is array index specifier, break immediately // a[x], fn()[x] if (reserved_array(this._flags.last_token, line_starters)) { this._output.space_before_token = true; } this.print_token(current_token); this.set_mode(next_mode); this.indent(); if (this._options.space_in_paren) { this._output.space_before_token = true; } return; } next_mode = MODE.ArrayLiteral; if (is_array(this._flags.mode)) { if (this._flags.last_token.text === '[' || (this._flags.last_token.text === ',' && (this._last_last_text === ']' || this._last_last_text === '}'))) { // ], [ goes to new line // }, [ goes to new line if (!this._options.keep_array_indentation) { this.print_newline(); } } } if (!in_array(this._flags.last_token.type, [TOKEN.START_EXPR, TOKEN.END_EXPR, TOKEN.WORD, TOKEN.OPERATOR, TOKEN.DOT])) { this._output.space_before_token = true; } } else { if (this._flags.last_token.type === TOKEN.RESERVED) { if (this._flags.last_token.text === 'for') { this._output.space_before_token = this._options.space_before_conditional; next_mode = MODE.ForInitializer; } else if (in_array(this._flags.last_token.text, ['if', 'while', 'switch'])) { this._output.space_before_token = this._options.space_before_conditional; next_mode = MODE.Conditional; } else if (in_array(this._flags.last_word, ['await', 'async'])) { // Should be a space between await and an IIFE, or async and an arrow function this._output.space_before_token = true; } else if (this._flags.last_token.text === 'import' && current_token.whitespace_before === '') { this._output.space_before_token = false; } else if (in_array(this._flags.last_token.text, line_starters) || this._flags.last_token.text === 'catch') { this._output.space_before_token = true; } } else if (this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) { // Support of this kind of newline preservation. // a = (b && // (c || d)); if (!this.start_of_object_property()) { this.allow_wrap_or_preserved_newline(current_token); } } else if (this._flags.last_token.type === TOKEN.WORD) { this._output.space_before_token = false; // function name() vs function name () // function* name() vs function* name () // async name() vs async name () // In ES6, you can also define the method properties of an object // var obj = {a: function() {}} // It can be abbreviated // var obj = {a() {}} // var obj = { a() {}} vs var obj = { a () {}} // var obj = { * a() {}} vs var obj = { * a () {}} var peek_back_two = this._tokens.peek(-3); if (this._options.space_after_named_function && peek_back_two) { // peek starts at next character so -1 is current token var peek_back_three = this._tokens.peek(-4); if (reserved_array(peek_back_two, ['async', 'function']) || (peek_back_two.text === '*' && reserved_array(peek_back_three, ['async', 'function']))) { this._output.space_before_token = true; } else if (this._flags.mode === MODE.ObjectLiteral) { if ((peek_back_two.text === '{' || peek_back_two.text === ',') || (peek_back_two.text === '*' && (peek_back_three.text === '{' || peek_back_three.text === ','))) { this._output.space_before_token = true; } } else if (this._flags.parent && this._flags.parent.class_start_block) { this._output.space_before_token = true; } } } else { // Support preserving wrapped arrow function expressions // a.b('c', // () => d.e // ) this.allow_wrap_or_preserved_newline(current_token); } // function() vs function () // yield*() vs yield* () // function*() vs function* () if ((this._flags.last_token.type === TOKEN.RESERVED && (this._flags.last_word === 'function' || this._flags.last_word === 'typeof')) || (this._flags.last_token.text === '*' && (in_array(this._last_last_text, ['function', 'yield']) || (this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) { this._output.space_before_token = this._options.space_after_anon_function; } } if (this._flags.last_token.text === ';' || this._flags.last_token.type === TOKEN.START_BLOCK) { this.print_newline(); } else if (this._flags.last_token.type === TOKEN.END_EXPR || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.END_BLOCK || this._flags.last_token.text === '.' || this._flags.last_token.type === TOKEN.COMMA) { // do nothing on (( and )( and ][ and ]( and .( // TODO: Consider whether forcing this is required. Review failing tests when removed. this.allow_wrap_or_preserved_newline(current_token, current_token.newlines); } this.print_token(current_token); this.set_mode(next_mode); if (this._options.space_in_paren) { this._output.space_before_token = true; } // In all cases, if we newline while inside an expression it should be indented. this.indent(); }; Beautifier.prototype.handle_end_expr = function(current_token) { // statements inside expressions are not valid syntax, but... // statements must all be closed when their container closes while (this._flags.mode === MODE.Statement) { this.restore_mode(); } this.handle_whitespace_and_comments(current_token); if (this._flags.multiline_frame) { this.allow_wrap_or_preserved_newline(current_token, current_token.text === ']' && is_array(this._flags.mode) && !this._options.keep_array_indentation); } if (this._options.space_in_paren) { if (this._flags.last_token.type === TOKEN.START_EXPR && !this._options.space_in_empty_paren) { // () [] no inner space in empty parens like these, ever, ref #320 this._output.trim(); this._output.space_before_token = false; } else { this._output.space_before_token = true; } } this.deindent(); this.print_token(current_token); this.restore_mode(); remove_redundant_indentation(this._output, this._previous_flags); // do {} while () // no statement required after if (this._flags.do_while && this._previous_flags.mode === MODE.Conditional) { this._previous_flags.mode = MODE.Expression; this._flags.do_block = false; this._flags.do_while = false; } }; Beautifier.prototype.handle_start_block = function(current_token) { this.handle_whitespace_and_comments(current_token); // Check if this is should be treated as a ObjectLiteral var next_token = this._tokens.peek(); var second_token = this._tokens.peek(1); if (this._flags.last_word === 'switch' && this._flags.last_token.type === TOKEN.END_EXPR) { this.set_mode(MODE.BlockStatement); this._flags.in_case_statement = true; } else if (this._flags.case_body) { this.set_mode(MODE.BlockStatement); } else if (second_token && ( (in_array(second_token.text, [':', ',']) && in_array(next_token.type, [TOKEN.STRING, TOKEN.WORD, TOKEN.RESERVED])) || (in_array(next_token.text, ['get', 'set', '...']) && in_array(second_token.type, [TOKEN.WORD, TOKEN.RESERVED])) )) { // We don't support TypeScript,but we didn't break it for a very long time. // We'll try to keep not breaking it. if (in_array(this._last_last_text, ['class', 'interface']) && !in_array(second_token.text, [':', ','])) { this.set_mode(MODE.BlockStatement); } else { this.set_mode(MODE.ObjectLiteral); } } else if (this._flags.last_token.type === TOKEN.OPERATOR && this._flags.last_token.text === '=>') { // arrow function: (param1, paramN) => { statements } this.set_mode(MODE.BlockStatement); } else if (in_array(this._flags.last_token.type, [TOKEN.EQUALS, TOKEN.START_EXPR, TOKEN.COMMA, TOKEN.OPERATOR]) || reserved_array(this._flags.last_token, ['return', 'throw', 'import', 'default']) ) { // Detecting shorthand function syntax is difficult by scanning forward, // so check the surrounding context. // If the block is being returned, imported, export default, passed as arg, // assigned with = or assigned in a nested object, treat as an ObjectLiteral. this.set_mode(MODE.ObjectLiteral); } else { this.set_mode(MODE.BlockStatement); } if (this._flags.last_token) { if (reserved_array(this._flags.last_token.previous, ['class', 'extends'])) { this._flags.class_start_block = true; } } var empty_braces = !next_token.comments_before && next_token.text === '}'; var empty_anonymous_function = empty_braces && this._flags.last_word === 'function' && this._flags.last_token.type === TOKEN.END_EXPR; if (this._options.brace_preserve_inline) // check for inline, set inline_frame if so { // search forward for a newline wanted inside this block var index = 0; var check_token = null; this._flags.inline_frame = true; do { index += 1; check_token = this._tokens.peek(index - 1); if (check_token.newlines) { this._flags.inline_frame = false; break; } } while (check_token.type !== TOKEN.EOF && !(check_token.type === TOKEN.END_BLOCK && check_token.opened === current_token)); } if ((this._options.brace_style === "expand" || (this._options.brace_style === "none" && current_token.newlines)) && !this._flags.inline_frame) { if (this._flags.last_token.type !== TOKEN.OPERATOR && (empty_anonymous_function || this._flags.last_token.type === TOKEN.EQUALS || (reserved_array(this._flags.last_token, special_words) && this._flags.last_token.text !== 'else'))) { this._output.space_before_token = true; } else { this.print_newline(false, true); } } else { // collapse || inline_frame if (is_array(this._previous_flags.mode) && (this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.COMMA)) { if (this._flags.last_token.type === TOKEN.COMMA || this._options.space_in_paren) { this._output.space_before_token = true; } if (this._flags.last_token.type === TOKEN.COMMA || (this._flags.last_token.type === TOKEN.START_EXPR && this._flags.inline_frame)) { this.allow_wrap_or_preserved_newline(current_token); this._previous_flags.multiline_frame = this._previous_flags.multiline_frame || this._flags.multiline_frame; this._flags.multiline_frame = false; } } if (this._flags.last_token.type !== TOKEN.OPERATOR && this._flags.last_token.type !== TOKEN.START_EXPR) { if (in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.SEMICOLON]) && !this._flags.inline_frame) { this.print_newline(); } else { this._output.space_before_token = true; } } } this.print_token(current_token); this.indent(); // Except for specific cases, open braces are followed by a new line. if (!empty_braces && !(this._options.brace_preserve_inline && this._flags.inline_frame)) { this.print_newline(); } }; Beautifier.prototype.handle_end_block = function(current_token) { // statements must all be closed when their container closes this.handle_whitespace_and_comments(current_token); while (this._flags.mode === MODE.Statement) { this.restore_mode(); } var empty_braces = this._flags.last_token.type === TOKEN.START_BLOCK; if (this._flags.inline_frame && !empty_braces) { // try inline_frame (only set if this._options.braces-preserve-inline) first this._output.space_before_token = true; } else if (this._options.brace_style === "expand") { if (!empty_braces) { this.print_newline(); } } else { // skip {} if (!empty_braces) { if (is_array(this._flags.mode) && this._options.keep_array_indentation) { // we REALLY need a newline here, but newliner would skip that this._options.keep_array_indentation = false; this.print_newline(); this._options.keep_array_indentation = true; } else { this.print_newline(); } } } this.restore_mode(); this.print_token(current_token); }; Beautifier.prototype.handle_word = function(current_token) { if (current_token.type === TOKEN.RESERVED) { if (in_array(current_token.text, ['set', 'get']) && this._flags.mode !== MODE.ObjectLiteral) { current_token.type = TOKEN.WORD; } else if (current_token.text === 'import' && in_array(this._tokens.peek().text, ['(', '.'])) { current_token.type = TOKEN.WORD; } else if (in_array(current_token.text, ['as', 'from']) && !this._flags.import_block) { current_token.type = TOKEN.WORD; } else if (this._flags.mode === MODE.ObjectLiteral) { var next_token = this._tokens.peek(); if (next_token.text === ':') { current_token.type = TOKEN.WORD; } } } if (this.start_of_statement(current_token)) { // The conditional starts the statement if appropriate. if (reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD) { this._flags.declaration_statement = true; } } else if (current_token.newlines && !is_expression(this._flags.mode) && (this._flags.last_token.type !== TOKEN.OPERATOR || (this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) && this._flags.last_token.type !== TOKEN.EQUALS && (this._options.preserve_newlines || !reserved_array(this._flags.last_token, ['var', 'let', 'const', 'set', 'get']))) { this.handle_whitespace_and_comments(current_token); this.print_newline(); } else { this.handle_whitespace_and_comments(current_token); } if (this._flags.do_block && !this._flags.do_while) { if (reserved_word(current_token, 'while')) { // do {} ## while () this._output.space_before_token = true; this.print_token(current_token); this._output.space_before_token = true; this._flags.do_while = true; return; } else { // do {} should always have while as the next word. // if we don't see the expected while, recover this.print_newline(); this._flags.do_block = false; } } // if may be followed by else, or not // Bare/inline ifs are tricky // Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e(); if (this._flags.if_block) { if (!this._flags.else_block && reserved_word(current_token, 'else')) { this._flags.else_block = true; } else { while (this._flags.mode === MODE.Statement) { this.restore_mode(); } this._flags.if_block = false; this._flags.else_block = false; } } if (this._flags.in_case_statement && reserved_array(current_token, ['case', 'default'])) { this.print_newline(); if (!this._flags.case_block && (this._flags.case_body || this._options.jslint_happy)) { // switch cases following one another this.deindent(); } this._flags.case_body = false; this.print_token(current_token); this._flags.in_case = true; return; } if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) { if (!this.start_of_object_property() && !( // start of object property is different for numeric values with +/- prefix operators in_array(this._flags.last_token.text, ['+', '-']) && this._last_last_text === ':' && this._flags.parent.mode === MODE.ObjectLiteral)) { this.allow_wrap_or_preserved_newline(current_token); } } if (reserved_word(current_token, 'function')) { if (in_array(this._flags.last_token.text, ['}', ';']) || (this._output.just_added_newline() && !(in_array(this._flags.last_token.text, ['(', '[', '{', ':', '=', ',']) || this._flags.last_token.type === TOKEN.OPERATOR))) { // make sure there is a nice clean space of a