diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d053bbb2..0a65cacd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,15 @@ +# 1.4.3 + +[link](https://github.com/jlongster/prettier/compare/1.4.2...1.4.3) + +* Fix support for node 4 (#1988) +* Fix website on iOS Safari (#1970) + +Formatting change: +* Position JSX whitespace (`{" "}`) at the end of lines (#1964) + +Lots of small fixes, mainly for TypeScript. + # 1.4.2 [link](https://github.com/jlongster/prettier/compare/1.4.1...1.4.2) diff --git a/docs/index.js b/docs/index.js index 72b2d54e1..0f31b13b8 100644 --- a/docs/index.js +++ b/docs/index.js @@ -337,9 +337,14 @@ function hasSpaces(text, index, opts) { } 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.range) { return node.range[0]; } @@ -352,15 +357,19 @@ function locStart$1(node) { } function locEnd$1(node) { + var loc = void 0; if (node.range) { - return node.range[1]; + loc = node.range[1]; + } else if (typeof node.end === "number") { + loc = node.end; + } else if (node.source) { + loc = lineColumnToIndex(node.source.end, node.source.input.css); } - if (typeof node.end === "number") { - return node.end; - } - if (node.source) { - return lineColumnToIndex(node.source.end, node.source.input.css); + + if (node.typeAnnotation) { + return Math.max(loc, locEnd$1(node.typeAnnotation)); } + return loc; } // Super inefficient, needs to be cached. @@ -762,6 +771,13 @@ 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(node, comment) { @@ -1232,7 +1248,7 @@ var comments$1 = { }; var name = "prettier"; -var version$1 = "1.4.2"; +var version$1 = "1.4.3"; var description = "Prettier is an opinionated JavaScript formatter"; var bin = { "prettier": "./bin/prettier.js" }; var repository = "prettier/prettier"; @@ -1240,7 +1256,7 @@ var author = "James Long"; var license = "MIT"; var main = "./index.js"; var dependencies = {}; -var devDependencies = { "babel-cli": "6.24.1", "babel-code-frame": "7.0.0-alpha.12", "babel-preset-es2015": "6.24.1", "babylon": "7.0.0-beta.10", "chalk": "1.1.3", "cross-spawn": "5.1.0", "diff": "3.2.0", "eslint": "3.19.0", "eslint-plugin-prettier": "2.1.1", "esutils": "2.0.2", "flow-parser": "0.47.0", "get-stdin": "5.0.1", "glob": "7.1.2", "graphql": "0.10.1", "jest": "20.0.0", "jest-validate": "20.0.3", "minimist": "1.2.0", "mkdirp": "^0.5.1", "postcss": "^6.0.1", "postcss-less": "^1.0.0", "postcss-media-query-parser": "0.2.3", "postcss-scss": "1.0.0", "postcss-selector-parser": "2.2.3", "postcss-values-parser": "git://github.com/shellscape/postcss-values-parser.git#5e351360479116f3fe309602cdd15b0a233bc29f", "prettier": "1.4.0", "rimraf": "2.6.1", "rollup": "0.41.1", "rollup-plugin-commonjs": "7.0.0", "rollup-plugin-json": "2.1.0", "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.1.1", "typescript": "2.3.4", "typescript-eslint-parser": "git://github.com/eslint/typescript-eslint-parser.git#806251524424e3ad91e750da0f76b8de25ed0b42", "uglify-es": "3.0.15", "webpack": "2.6.1" }; +var devDependencies = { "babel-cli": "6.24.1", "babel-code-frame": "7.0.0-alpha.12", "babel-preset-es2015": "6.24.1", "babylon": "7.0.0-beta.10", "chalk": "1.1.3", "cross-spawn": "5.1.0", "diff": "3.2.0", "eslint": "3.19.0", "eslint-plugin-prettier": "2.1.1", "esutils": "2.0.2", "flow-parser": "0.47.0", "get-stdin": "5.0.1", "glob": "7.1.2", "graphql": "0.10.1", "jest": "20.0.0", "jest-validate": "20.0.3", "minimist": "1.2.0", "mkdirp": "^0.5.1", "postcss": "^6.0.1", "postcss-less": "^1.0.0", "postcss-media-query-parser": "0.2.3", "postcss-scss": "1.0.0", "postcss-selector-parser": "2.2.3", "postcss-values-parser": "git://github.com/shellscape/postcss-values-parser.git#5e351360479116f3fe309602cdd15b0a233bc29f", "prettier": "1.4.2", "rimraf": "2.6.1", "rollup": "0.41.1", "rollup-plugin-commonjs": "7.0.0", "rollup-plugin-json": "2.1.0", "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.1.1", "typescript": "2.3.4", "typescript-eslint-parser": "git://github.com/eslint/typescript-eslint-parser.git#806251524424e3ad91e750da0f76b8de25ed0b42", "uglify-es": "3.0.15", "webpack": "2.6.1" }; var scripts = { "test": "jest", "test-integration": "jest tests_integration", "lint": "eslint .", "build": "./scripts/build/build.sh" }; var jest = { "setupFiles": ["/tests_config/run_spec.js"], "snapshotSerializers": ["/tests_config/raw-serializer.js"], "testRegex": "jsfmt\\.spec\\.js$|__tests__/.*\\.js$", "testPathIgnorePatterns": ["tests/new_react", "tests/more_react"] }; var _package = { @@ -1448,10 +1464,18 @@ FastPath$1.prototype.needsParens = function () { switch (node.type) { case "CallExpression": - if (parent.type === "NewExpression" && parent.callee === node) { - return true; + { + var firstParentNotMemberExpression = parent; + var i = 0; + while (firstParentNotMemberExpression && firstParentNotMemberExpression.type === "MemberExpression") { + firstParentNotMemberExpression = this.getParentNode(++i); + } + + if (firstParentNotMemberExpression.type === "NewExpression" && firstParentNotMemberExpression.callee === this.getParentNode(i - 1)) { + return true; + } + return false; } - return false; case "SpreadElement": case "SpreadProperty": @@ -2403,6 +2427,7 @@ var docBuilders$4 = docBuilders$1; var concat$3 = docBuilders$4.concat; var join$3 = docBuilders$4.join; var hardline$3 = docBuilders$4.hardline; +var line$2 = docBuilders$4.line; var softline$2 = docBuilders$4.softline; var group$2 = docBuilders$4.group; var indent$3 = docBuilders$4.indent; @@ -2425,7 +2450,11 @@ function genericPrint$1(path, options, print) { } case "OperationDefinition": { - return concat$3([n.name === null ? "" : concat$3([n.operation, " "]), path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$2(concat$3(["(", indent$3(concat$3([softline$2, join$3(concat$3([",", ifBreak$2("", " "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ") "])) : n.name ? " " : "", path.call(print, "selectionSet")]); + return concat$3([n.name === null ? "" : n.operation, n.name ? concat$3([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$2(concat$3(["(", indent$3(concat$3([softline$2, join$3(concat$3([",", ifBreak$2("", " "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? n.name === null ? "" : " " : "", path.call(print, "selectionSet")]); + } + case "FragmentDefinition": + { + return concat$3(["fragment ", path.call(print, "name"), " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); } case "SelectionSet": { @@ -2433,7 +2462,7 @@ function genericPrint$1(path, options, print) { } case "Field": { - return group$2(concat$3([path.call(print, "name"), n.arguments.length > 0 ? group$2(concat$3(["(", indent$3(concat$3([softline$2, join$3(concat$3([",", ifBreak$2("", " "), softline$2]), path.map(print, "arguments"))])), softline$2, ")"])) : "", n.selectionSet ? " " : "", path.call(print, "selectionSet")])); + return group$2(concat$3([n.alias ? concat$3([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$2(concat$3(["(", indent$3(concat$3([softline$2, join$3(concat$3([",", ifBreak$2("", " "), softline$2]), path.map(print, "arguments"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")])); } case "Name": { @@ -2453,6 +2482,10 @@ function genericPrint$1(path, options, print) { { return n.value ? "true" : "false"; } + case "NullValue": + { + return "null"; + } case "Variable": { return concat$3(["$", path.call(print, "name")]); @@ -2461,11 +2494,21 @@ function genericPrint$1(path, options, print) { { return group$2(concat$3(["[", indent$3(concat$3([softline$2, join$3(concat$3([",", ifBreak$2("", " "), softline$2]), path.map(print, "values"))])), softline$2, "]"])); } + case "ObjectValue": + { + return group$2(concat$3(["{", n.fields.length > 0 ? " " : "", indent$3(concat$3([softline$2, join$3(concat$3([",", ifBreak$2("", " "), softline$2]), path.map(print, "fields"))])), softline$2, ifBreak$2("", n.fields.length > 0 ? " " : ""), "}"])); + } + case "ObjectField": case "Argument": { return concat$3([path.call(print, "name"), ": ", path.call(print, "value")]); } + case "Directive": + { + return concat$3(["@", path.call(print, "name"), n.arguments.length > 0 ? group$2(concat$3(["(", indent$3(concat$3([softline$2, join$3(concat$3([",", ifBreak$2("", " "), softline$2]), path.map(print, "arguments"))])), softline$2, ")"])) : ""]); + } + case "NamedType": { return path.call(print, "name"); @@ -2476,18 +2519,41 @@ function genericPrint$1(path, options, print) { return concat$3([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$3([" = ", path.call(print, "defaultValue")]) : ""]); } + case "FragmentSpread": + { + return concat$3(["...", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "InlineFragment": + { + return concat$3(["...", n.typeCondition ? concat$3([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); + } + + case "UnionTypeDefinition": + { + return group$2(concat$3(["union ", path.call(print, "name"), " =", ifBreak$2("", " "), indent$3(concat$3([ifBreak$2(concat$3([line$2, " "])), join$3(concat$3([line$2, "| "]), path.map(print, "types"))]))])); + } + default: throw new Error("unknown graphql type: " + JSON.stringify(n.kind)); } } +function printDirectives(path, print, n) { + if (n.directives.length === 0) { + return ""; + } + + return concat$3([" ", group$2(indent$3(concat$3([softline$2, join$3(concat$3([ifBreak$2("", " "), softline$2]), path.map(print, "directives"))])))]); +} + var printerGraphql = genericPrint$1; var util$6 = util$2; var docBuilders$5 = docBuilders$1; var concat$4 = docBuilders$5.concat; var join$4 = docBuilders$5.join; -var line$2 = docBuilders$5.line; +var line$3 = docBuilders$5.line; var hardline$4 = docBuilders$5.hardline; var softline$3 = docBuilders$5.softline; var group$3 = docBuilders$5.group; @@ -2532,7 +2598,13 @@ function genericPrint$2(path, options, print) { } case "css-decl": { - return concat$4([n.raws.before.replace(/[\s;]/g, ""), n.prop, ": ", path.call(print, "value"), n.important ? " !important" : "", n.nodes ? concat$4([" {", indent$4(concat$4([softline$3, printNodeSequence(path, options, print)])), softline$3, "}"]) : ";"]); + // When the following less construct &:extend(.foo); is parsed with scss, + // it will put a space after `:` and break it. Ideally we should parse + // less files with less, but we can hardcode this to work with scss as + // well. + var isValueExtend = n.value.type === "value-root" && n.value.group.type === "value-value" && n.value.group.group.type === "value-func" && n.value.group.group.value === "extend"; + + return concat$4([n.raws.before.replace(/[\s;]/g, ""), n.prop, ":", isValueExtend ? "" : " ", path.call(print, "value"), n.important ? " !important" : "", n.nodes ? concat$4([" {", indent$4(concat$4([softline$3, printNodeSequence(path, options, print)])), softline$3, "}"]) : ";"]); } case "css-atrule": { @@ -2598,7 +2670,7 @@ function genericPrint$2(path, options, print) { // postcss-selector-parser case "selector-root": { - return group$3(join$4(concat$4([",", line$2]), path.map(print, "nodes"))); + return group$3(join$4(concat$4([",", line$3]), path.map(print, "nodes"))); } case "selector-comment": { @@ -2628,7 +2700,7 @@ function genericPrint$2(path, options, print) { { if (n.value === "+" || n.value === ">" || n.value === "~") { var parent = path.getParentNode(); - var leading = parent.type === "selector-selector" && parent.nodes[0] === n ? "" : line$2; + var leading = parent.type === "selector-selector" && parent.nodes[0] === n ? "" : line$3; return concat$4([leading, n.value, " "]); } return n.value; @@ -2664,7 +2736,7 @@ function genericPrint$2(path, options, print) { if (n.groups[i + 1].type === "value-operator" && ["+", "-", "/", "*", "%"].indexOf(n.groups[i + 1].value) !== -1) { _parts.push(" "); } else { - _parts.push(line$2); + _parts.push(line$3); } } } @@ -2681,10 +2753,10 @@ function genericPrint$2(path, options, print) { } if (!n.open) { - return group$3(indent$4(join$4(concat$4([",", line$2]), path.map(print, "groups")))); + return group$3(indent$4(join$4(concat$4([",", line$3]), path.map(print, "groups")))); } - return group$3(concat$4([n.open ? path.call(print, "open") : "", indent$4(concat$4([softline$3, join$4(concat$4([",", line$2]), path.map(print, "groups"))])), softline$3, n.close ? path.call(print, "close") : ""])); + return group$3(concat$4([n.open ? path.call(print, "open") : "", indent$4(concat$4([softline$3, join$4(concat$4([",", line$3]), path.map(print, "groups"))])), softline$3, n.close ? path.call(print, "close") : ""])); } case "value-value": { @@ -2697,7 +2769,7 @@ function genericPrint$2(path, options, print) { case "value-paren": { if (n.raws.before !== "") { - return concat$4([line$2, n.value]); + return concat$4([line$3, n.value]); } return n.value; } @@ -2834,7 +2906,6 @@ function genericPrint(path, options, printPath, args) { return options.originalText.slice(util$4.locStart(node), util$4.locEnd(node)); } - var parts = []; var needsParens = false; var linesWithoutParens = getPrintFunction(options)(path, options, printPath, args); @@ -2842,6 +2913,7 @@ function genericPrint(path, options, printPath, args) { 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. @@ -2855,12 +2927,11 @@ function genericPrint(path, options, printPath, args) { prefix = ""; } - // #1817 if (node.decorators.length === 1 && node.type !== "ClassDeclaration" && node.type !== "MethodDefinition" && node.type !== "ClassMethod" && (decorator.type === "Identifier" || decorator.type === "MemberExpression" || decorator.type === "CallExpression" && (decorator.arguments.length === 0 || decorator.arguments.length === 1 && (isStringLiteral(decorator.arguments[0]) || decorator.arguments[0].type === "Identifier" || decorator.arguments[0].type === "MemberExpression")))) { - separator = " "; + separator = line$1; } - parts.push(prefix, printPath(decoratorPath), separator); + decorators.push(prefix, printPath(decoratorPath), separator); }, "decorators"); } else if (util$4.isExportDeclaration(node) && node.declaration && node.declaration.decorators) { // Export declarations are responsible for printing any decorators @@ -2868,7 +2939,7 @@ function genericPrint(path, options, printPath, args) { path.each(function (decoratorPath) { var decorator = decoratorPath.getValue(); var prefix = decorator.type === "Decorator" || decorator.type === "TSDecorator" ? "" : "@"; - parts.push(prefix, printPath(decoratorPath), line$1); + decorators.push(prefix, printPath(decoratorPath), hardline$2); }, "declaration", "decorators"); } else { // Nodes with decorators can't have parentheses, so we can avoid @@ -2884,6 +2955,7 @@ function genericPrint(path, options, printPath, args) { node.needsParens = needsParens; } + var parts = []; if (needsParens) { parts.unshift("("); } @@ -2894,6 +2966,9 @@ function genericPrint(path, options, printPath, args) { parts.push(")"); } + if (decorators.length > 0) { + return group$1(concat$2(decorators.concat(parts))); + } return concat$2(parts); } @@ -3045,7 +3120,7 @@ function genericPrintNoParens(path, options, print, args) { parts.push("declare "); } parts.push(printFunctionDeclaration(path, print, options)); - if (n.type === "TSNamespaceFunctionDeclaration" && !n.body) { + if (!n.body) { parts.push(semi); } return concat$2(parts); @@ -3750,15 +3825,7 @@ function genericPrintNoParens(path, options, print, args) { if (consequent.length > 0) { var cons = path.call(function (consequentPath) { - return join$2(hardline$2, consequentPath.map(function (p, i) { - if (n.consequent[i].type === "EmptyStatement") { - return null; - } - var shouldAddLine = i !== n.consequent.length - 1 && util$4.isNextLineEmpty(options.originalText, p.getValue()); - return concat$2([print(p), shouldAddLine ? hardline$2 : ""]); - }).filter(function (e) { - return e !== null; - })); + return printStatementSequence(consequentPath, options, print); }, "consequent"); parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$2([" ", cons]) : indent$2(concat$2([hardline$2, cons]))); @@ -4452,7 +4519,7 @@ function genericPrintNoParens(path, options, print, args) { if (n.typeAnnotation) { parts.push(": ", path.call(print, "typeAnnotation")); } - return concat$2(parts); + return group$1(concat$2(parts)); case "TSNamespaceExportDeclaration": if (n.declaration) { // Temporary fix until https://github.com/eslint/typescript-eslint-parser/issues/263 @@ -5233,7 +5300,8 @@ function printMemberChain(path, options, print) { var printedGroups = groups.map(printGroup); var oneLine = concat$2(printedGroups); - var flatGroups = groups.slice(0, shouldMerge ? 3 : 2).reduce(function (res, group) { + var cutoff = shouldMerge ? 3 : 2; + var flatGroups = groups.slice(0, cutoff).reduce(function (res, group) { return res.concat(group); }, []); @@ -5241,11 +5309,11 @@ function printMemberChain(path, options, print) { 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 <= (shouldMerge ? 3 : 2) && !hasComment && + if (groups.length <= cutoff && !hasComment && // (a || b).map() should be break before .map() instead of || groups[0][0].node.type !== "LogicalExpression") { return group$1(oneLine); @@ -5770,7 +5838,7 @@ function isLastStatement(path) { return true; } var node = path.getValue(); - var body = parent.body.filter(function (stmt) { + var body = (parent.body || parent.consequent).filter(function (stmt) { return stmt.type !== "EmptyStatement"; }); return body && body[body.length - 1] === node; @@ -5853,7 +5921,7 @@ function classPropMayCauseASIProblems(path) { // this isn't actually possible yet with most parsers available today // so isn't properly tested yet. - if (name === "static" || name === "get" || name === "set") { + if ((name === "static" || name === "get" || name === "set") && !node.typeAnnotation) { return true; } } @@ -5963,16 +6031,22 @@ function isNodeStartingWithDeclare(node, options) { } function shouldHugType(node) { - if (node.type === "ObjectTypeAnnotation") { + if (node.type === "ObjectTypeAnnotation" || node.type === "TSTypeLiteral") { return true; } if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") { - var count = node.types.filter(function (n) { + var voidCount = node.types.filter(function (n) { return n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "Literal" && n.value === null; }).length; - if (node.types.length - 1 === count) { + 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; } } @@ -9781,15 +9855,15 @@ function parse(text, opts) { var parseFunction = void 0; if (opts.parser === "flow") { - parseFunction = eval("require")("./src/parser-flow"); + parseFunction = eval("require")("./parser-flow"); } else if (opts.parser === "graphql") { - parseFunction = eval("require")("./src/parser-graphql"); + parseFunction = eval("require")("./parser-graphql"); } else if (opts.parser === "typescript") { - parseFunction = eval("require")("./src/parser-typescript"); + parseFunction = eval("require")("./parser-typescript"); } else if (opts.parser === "postcss") { - parseFunction = eval("require")("./src/parser-postcss"); + parseFunction = eval("require")("./parser-postcss"); } else { - parseFunction = eval("require")("./src/parser-babylon"); + parseFunction = eval("require")("./parser-babylon"); } try { diff --git a/docs/parser-postcss.js b/docs/parser-postcss.js index 15a608808..498cb5c7c 100644 --- a/docs/parser-postcss.js +++ b/docs/parser-postcss.js @@ -103,216 +103,216 @@ var UNIVERSAL = exports.UNIVERSAL = 'universal'; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Node = __webpack_require__(4); - -class Container extends Node { - - constructor (opts) { - super(opts); - - if (!this.nodes) { - this.nodes = []; - } - } - - push (child) { - child.parent = this; - this.nodes.push(child); - return this; - } - - each (callback) { - if (!this.lastEach) this.lastEach = 0; - if (!this.indexes) this.indexes = { }; - - this.lastEach += 1; - - let id = this.lastEach, - index, - result; - - this.indexes[id] = 0; - - if (!this.nodes) return undefined; - - while (this.indexes[id] < this.nodes.length) { - index = this.indexes[id]; - result = callback(this.nodes[index], index); - if (result === false) break; - - this.indexes[id] += 1; - } - - delete this.indexes[id]; - - return result; - } - - walk (callback) { - return this.each((child, i) => { - let result = callback(child, i); - if (result !== false && child.walk) { - result = child.walk(callback); - } - return result; - }); - } - - walkType (type, callback) { - if (!type || !callback) { - throw new Error('Parameters {type} and {callback} are required.'); - } - - // allow users to pass a constructor, or node type string; eg. Word. - type = type.name && type.prototype ? type.name : type; - - return this.walk((node, index) => { - if (node.type === type) { - return callback.call(this, node, index); - } - }); - } - - append (node) { - node.parent = this; - this.nodes.push(node); - return this; - } - - prepend (node) { - node.parent = this; - this.nodes.unshift(node); - return this; - } - - cleanRaws (keepBetween) { - super.cleanRaws(keepBetween); - if (this.nodes) { - for (let node of this.nodes) node.cleanRaws(keepBetween); - } - } - - insertAfter (oldNode, newNode) { - let oldIndex = this.index(oldNode), - index; - - this.nodes.splice(oldIndex + 1, 0, newNode); - - for (let id in this.indexes) { - index = this.indexes[id]; - if (oldIndex <= index) { - this.indexes[id] = index + this.nodes.length; - } - } - - return this; - } - - insertBefore (oldNode, newNode) { - let oldIndex = this.index(oldNode), - index; - - this.nodes.splice(oldIndex, 0, newNode); - - for (let id in this.indexes) { - index = this.indexes[id]; - if (oldIndex <= index) { - this.indexes[id] = index + this.nodes.length; - } - } - - return this; - } - - removeChild (child) { - child = this.index(child); - this.nodes[child].parent = undefined; - this.nodes.splice(child, 1); - - let index; - for (let id in this.indexes) { - index = this.indexes[id]; - if (index >= child) { - this.indexes[id] = index - 1; - } - } - - return this; - } - - removeAll () { - for (let node of this.nodes) node.parent = undefined; - this.nodes = []; - return this; - } - - every (condition) { - return this.nodes.every(condition); - } - - some (condition) { - return this.nodes.some(condition); - } - - index (child) { - if (typeof child === 'number') { - return child; - } - else { - return this.nodes.indexOf(child); - } - } - - get first () { - if (!this.nodes) return undefined; - return this.nodes[0]; - } - - get last () { - if (!this.nodes) return undefined; - return this.nodes[this.nodes.length - 1]; - } - - toString () { - let result = this.nodes.map(String).join(''); - - if (this.value) { - result = this.value + result; - } - - if (this.raws.before) { - result = this.raws.before + result; - } - - if (this.raws.after) { - result += this.raws.after; - } - - return result; - } -} - -Container.registerWalker = (constructor) => { - let walkerName = 'walk' + constructor.name; - - // plural sugar - if (walkerName.lastIndexOf('s') !== walkerName.length - 1) { - walkerName += 's'; - } - - if (Container.prototype[walkerName]) { - return; - } - - // we need access to `this` so we can't use an arrow function - Container.prototype[walkerName] = function (callback) { - return this.walkType(constructor, callback); - }; -}; - -module.exports = Container; + + +const Node = __webpack_require__(4); + +class Container extends Node { + + constructor (opts) { + super(opts); + + if (!this.nodes) { + this.nodes = []; + } + } + + push (child) { + child.parent = this; + this.nodes.push(child); + return this; + } + + each (callback) { + if (!this.lastEach) this.lastEach = 0; + if (!this.indexes) this.indexes = { }; + + this.lastEach += 1; + + let id = this.lastEach, + index, + result; + + this.indexes[id] = 0; + + if (!this.nodes) return undefined; + + while (this.indexes[id] < this.nodes.length) { + index = this.indexes[id]; + result = callback(this.nodes[index], index); + if (result === false) break; + + this.indexes[id] += 1; + } + + delete this.indexes[id]; + + return result; + } + + walk (callback) { + return this.each((child, i) => { + let result = callback(child, i); + if (result !== false && child.walk) { + result = child.walk(callback); + } + return result; + }); + } + + walkType (type, callback) { + if (!type || !callback) { + throw new Error('Parameters {type} and {callback} are required.'); + } + + // allow users to pass a constructor, or node type string; eg. Word. + type = type.name && type.prototype ? type.name : type; + + return this.walk((node, index) => { + if (node.type === type) { + return callback.call(this, node, index); + } + }); + } + + append (node) { + node.parent = this; + this.nodes.push(node); + return this; + } + + prepend (node) { + node.parent = this; + this.nodes.unshift(node); + return this; + } + + cleanRaws (keepBetween) { + super.cleanRaws(keepBetween); + if (this.nodes) { + for (let node of this.nodes) node.cleanRaws(keepBetween); + } + } + + insertAfter (oldNode, newNode) { + let oldIndex = this.index(oldNode), + index; + + this.nodes.splice(oldIndex + 1, 0, newNode); + + for (let id in this.indexes) { + index = this.indexes[id]; + if (oldIndex <= index) { + this.indexes[id] = index + this.nodes.length; + } + } + + return this; + } + + insertBefore (oldNode, newNode) { + let oldIndex = this.index(oldNode), + index; + + this.nodes.splice(oldIndex, 0, newNode); + + for (let id in this.indexes) { + index = this.indexes[id]; + if (oldIndex <= index) { + this.indexes[id] = index + this.nodes.length; + } + } + + return this; + } + + removeChild (child) { + child = this.index(child); + this.nodes[child].parent = undefined; + this.nodes.splice(child, 1); + + let index; + for (let id in this.indexes) { + index = this.indexes[id]; + if (index >= child) { + this.indexes[id] = index - 1; + } + } + + return this; + } + + removeAll () { + for (let node of this.nodes) node.parent = undefined; + this.nodes = []; + return this; + } + + every (condition) { + return this.nodes.every(condition); + } + + some (condition) { + return this.nodes.some(condition); + } + + index (child) { + if (typeof child === 'number') { + return child; + } + else { + return this.nodes.indexOf(child); + } + } + + get first () { + if (!this.nodes) return undefined; + return this.nodes[0]; + } + + get last () { + if (!this.nodes) return undefined; + return this.nodes[this.nodes.length - 1]; + } + + toString () { + let result = this.nodes.map(String).join(''); + + if (this.value) { + result = this.value + result; + } + + if (this.raws.before) { + result = this.raws.before + result; + } + + if (this.raws.after) { + result += this.raws.after; + } + + return result; + } +} + +Container.registerWalker = (constructor) => { + let walkerName = 'walk' + constructor.name; + + // plural sugar + if (walkerName.lastIndexOf('s') !== walkerName.length - 1) { + walkerName += 's'; + } + + if (Container.prototype[walkerName]) { + return; + } + + // we need access to `this` so we can't use an arrow function + Container.prototype[walkerName] = function (callback) { + return this.walkType(constructor, callback); + }; +}; + +module.exports = Container; /***/ }), @@ -383,220 +383,220 @@ module.exports = exports['default']; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -let cloneNode = function (obj, parent) { - let cloned = new obj.constructor(); - - for (let i in obj) { - if (!obj.hasOwnProperty(i)) continue; - - let value = obj[i], - type = typeof value; - - if (i === 'parent' && type === 'object') { - if (parent) cloned[i] = parent; - } - else if (i === 'source') { - cloned[i] = value; - } - else if (value instanceof Array) { - cloned[i] = value.map(j => cloneNode(j, cloned)); - } - else if (i !== 'before' && i !== 'after' && i !== 'between' && i !== 'semicolon') { - if (type === 'object' && value !== null) value = cloneNode(value); - cloned[i] = value; - } - } - - return cloned; -}; - -module.exports = class Node { - - constructor (defaults) { - defaults = defaults || {}; - this.raws = { before: '', after: '' }; - - for (let name in defaults) { - this[name] = defaults[name]; - } - } - - remove () { - if (this.parent) { - this.parent.removeChild(this); - } - - this.parent = undefined; - - return this; - } - - toString () { - return [ - this.raws.before, - String(this.value), - this.raws.after - ].join(''); - } - - clone (overrides) { - overrides = overrides || {}; - - let cloned = cloneNode(this); - - for (let name in overrides) { - cloned[name] = overrides[name]; - } - - return cloned; - } - - cloneBefore (overrides) { - overrides = overrides || {}; - - let cloned = this.clone(overrides); - - this.parent.insertBefore(this, cloned); - return cloned; - } - - cloneAfter (overrides) { - overrides = overrides || {}; - - let cloned = this.clone(overrides); - - this.parent.insertAfter(this, cloned); - return cloned; - } - - replaceWith () { - let nodes = Array.prototype.slice.call(arguments); - - if (this.parent) { - for (let node of nodes) { - this.parent.insertBefore(this, node); - } - - this.remove(); - } - - return this; - } - - moveTo (container) { - this.cleanRaws(this.root() === container.root()); - this.remove(); - - container.append(this); - - return this; - } - - moveBefore (node) { - this.cleanRaws(this.root() === node.root()); - this.remove(); - - node.parent.insertBefore(node, this); - - return this; - } - - moveAfter (node) { - this.cleanRaws(this.root() === node.root()); - this.remove(); - node.parent.insertAfter(node, this); - return this; - } - - next () { - let index = this.parent.index(this); - - return this.parent.nodes[index + 1]; - } - - prev () { - let index = this.parent.index(this); - - return this.parent.nodes[index - 1]; - } - - toJSON () { - let fixed = { }; - - for (let name in this) { - if (!this.hasOwnProperty(name)) continue; - if (name === 'parent') continue; - let value = this[name]; - - if (value instanceof Array) { - fixed[name] = value.map(i => { - if (typeof i === 'object' && i.toJSON) { - return i.toJSON(); - } - else { - return i; - } - }); - } - else if (typeof value === 'object' && value.toJSON) { - fixed[name] = value.toJSON(); - } - else { - fixed[name] = value; - } - } - - return fixed; - } - - root () { - let result = this; - - while (result.parent) result = result.parent; - - return result; - } - - cleanRaws (keepBetween) { - delete this.raws.before; - delete this.raws.after; - if (!keepBetween) delete this.raws.between; - } - - positionInside (index) { - let string = this.toString(), - column = this.source.start.column, - line = this.source.start.line; - - for (let i = 0; i < index; i++) { - if (string[i] === '\n') { - column = 1; - line += 1; - } - else { - column += 1; - } - } - - return { line, column }; - } - - positionBy (opts) { - let pos = this.source.start; - - if (opts.index) { - pos = this.positionInside(opts.index); - } - else if (opts.word) { - let index = this.toString().indexOf(opts.word); - if (index !== -1) pos = this.positionInside(index); - } - - return pos; - } -}; + + +let cloneNode = function (obj, parent) { + let cloned = new obj.constructor(); + + for (let i in obj) { + if (!obj.hasOwnProperty(i)) continue; + + let value = obj[i], + type = typeof value; + + if (i === 'parent' && type === 'object') { + if (parent) cloned[i] = parent; + } + else if (i === 'source') { + cloned[i] = value; + } + else if (value instanceof Array) { + cloned[i] = value.map(j => cloneNode(j, cloned)); + } + else if (i !== 'before' && i !== 'after' && i !== 'between' && i !== 'semicolon') { + if (type === 'object' && value !== null) value = cloneNode(value); + cloned[i] = value; + } + } + + return cloned; +}; + +module.exports = class Node { + + constructor (defaults) { + defaults = defaults || {}; + this.raws = { before: '', after: '' }; + + for (let name in defaults) { + this[name] = defaults[name]; + } + } + + remove () { + if (this.parent) { + this.parent.removeChild(this); + } + + this.parent = undefined; + + return this; + } + + toString () { + return [ + this.raws.before, + String(this.value), + this.raws.after + ].join(''); + } + + clone (overrides) { + overrides = overrides || {}; + + let cloned = cloneNode(this); + + for (let name in overrides) { + cloned[name] = overrides[name]; + } + + return cloned; + } + + cloneBefore (overrides) { + overrides = overrides || {}; + + let cloned = this.clone(overrides); + + this.parent.insertBefore(this, cloned); + return cloned; + } + + cloneAfter (overrides) { + overrides = overrides || {}; + + let cloned = this.clone(overrides); + + this.parent.insertAfter(this, cloned); + return cloned; + } + + replaceWith () { + let nodes = Array.prototype.slice.call(arguments); + + if (this.parent) { + for (let node of nodes) { + this.parent.insertBefore(this, node); + } + + this.remove(); + } + + return this; + } + + moveTo (container) { + this.cleanRaws(this.root() === container.root()); + this.remove(); + + container.append(this); + + return this; + } + + moveBefore (node) { + this.cleanRaws(this.root() === node.root()); + this.remove(); + + node.parent.insertBefore(node, this); + + return this; + } + + moveAfter (node) { + this.cleanRaws(this.root() === node.root()); + this.remove(); + node.parent.insertAfter(node, this); + return this; + } + + next () { + let index = this.parent.index(this); + + return this.parent.nodes[index + 1]; + } + + prev () { + let index = this.parent.index(this); + + return this.parent.nodes[index - 1]; + } + + toJSON () { + let fixed = { }; + + for (let name in this) { + if (!this.hasOwnProperty(name)) continue; + if (name === 'parent') continue; + let value = this[name]; + + if (value instanceof Array) { + fixed[name] = value.map(i => { + if (typeof i === 'object' && i.toJSON) { + return i.toJSON(); + } + else { + return i; + } + }); + } + else if (typeof value === 'object' && value.toJSON) { + fixed[name] = value.toJSON(); + } + else { + fixed[name] = value; + } + } + + return fixed; + } + + root () { + let result = this; + + while (result.parent) result = result.parent; + + return result; + } + + cleanRaws (keepBetween) { + delete this.raws.before; + delete this.raws.after; + if (!keepBetween) delete this.raws.between; + } + + positionInside (index) { + let string = this.toString(), + column = this.source.start.column, + line = this.source.start.line; + + for (let i = 0; i < index; i++) { + if (string[i] === '\n') { + column = 1; + line += 1; + } + else { + column += 1; + } + } + + return { line, column }; + } + + positionBy (opts) { + let pos = this.source.start; + + if (opts.index) { + pos = this.positionInside(opts.index); + } + else if (opts.word) { + let index = this.toString().indexOf(opts.word); + if (index !== -1) pos = this.positionInside(index); + } + + return pos; + } +}; /***/ }), @@ -11685,32 +11685,32 @@ module.exports = exports['default']; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); - -class AtWord extends Container { - constructor (opts) { - super(opts); - this.type = 'atword'; - } - - toString () { - let quote = this.quoted ? this.raws.quote : ''; - return [ - this.raws.before, - '@', - // we can't use String() here because it'll try using itself - // as the constructor - String.prototype.toString.call(this.value), - this.raws.after - ].join(''); - } -} - -Container.registerWalker(AtWord); - -module.exports = AtWord; + + +const Container = __webpack_require__(1); + +class AtWord extends Container { + constructor (opts) { + super(opts); + this.type = 'atword'; + } + + toString () { + let quote = this.quoted ? this.raws.quote : ''; + return [ + this.raws.before, + '@', + // we can't use String() here because it'll try using itself + // as the constructor + String.prototype.toString.call(this.value), + this.raws.after + ].join(''); + } +} + +Container.registerWalker(AtWord); + +module.exports = AtWord; /***/ }), @@ -11718,21 +11718,21 @@ module.exports = AtWord; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); -const Node = __webpack_require__(4); - -class Colon extends Node { - constructor (opts) { - super(opts); - this.type = 'colon'; - } -} - -Container.registerWalker(Colon); - -module.exports = Colon; + + +const Container = __webpack_require__(1); +const Node = __webpack_require__(4); + +class Colon extends Node { + constructor (opts) { + super(opts); + this.type = 'colon'; + } +} + +Container.registerWalker(Colon); + +module.exports = Colon; /***/ }), @@ -11740,21 +11740,21 @@ module.exports = Colon; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); -const Node = __webpack_require__(4); - -class Comma extends Node { - constructor (opts) { - super(opts); - this.type = 'comma'; - } -} - -Container.registerWalker(Comma); - -module.exports = Comma; + + +const Container = __webpack_require__(1); +const Node = __webpack_require__(4); + +class Comma extends Node { + constructor (opts) { + super(opts); + this.type = 'comma'; + } +} + +Container.registerWalker(Comma); + +module.exports = Comma; /***/ }), @@ -11762,31 +11762,31 @@ module.exports = Comma; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); -const Node = __webpack_require__(4); - -class Comment extends Node { - constructor (opts) { - super(opts); - this.type = 'comment'; - } - - toString () { - return [ - this.raws.before, - '/*', - String(this.value), - '*/', - this.raws.after - ].join(''); - } -} - -Container.registerWalker(Comment); - -module.exports = Comment; + + +const Container = __webpack_require__(1); +const Node = __webpack_require__(4); + +class Comment extends Node { + constructor (opts) { + super(opts); + this.type = 'comment'; + } + + toString () { + return [ + this.raws.before, + '/*', + String(this.value), + '*/', + this.raws.after + ].join(''); + } +} + +Container.registerWalker(Comment); + +module.exports = Comment; /***/ }), @@ -11794,22 +11794,22 @@ module.exports = Comment; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); - -class FunctionNode extends Container { - constructor (opts) { - super(opts); - this.type = 'func'; - // start off at -1 so we know there haven't been any parens added - this.unbalanced = -1; - } -} - -Container.registerWalker(FunctionNode); - -module.exports = FunctionNode; + + +const Container = __webpack_require__(1); + +class FunctionNode extends Container { + constructor (opts) { + super(opts); + this.type = 'func'; + // start off at -1 so we know there haven't been any parens added + this.unbalanced = -1; + } +} + +Container.registerWalker(FunctionNode); + +module.exports = FunctionNode; /***/ }), @@ -11817,31 +11817,31 @@ module.exports = FunctionNode; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); -const Node = __webpack_require__(4); - -class NumberNode extends Node { - constructor (opts) { - super(opts); - this.type = 'number'; - this.unit = opts.unit || ''; - } - - toString () { - return [ - this.raws.before, - String(this.value), - this.unit, - this.raws.after - ].join(''); - } -} - -Container.registerWalker(NumberNode); - -module.exports = NumberNode; + + +const Container = __webpack_require__(1); +const Node = __webpack_require__(4); + +class NumberNode extends Node { + constructor (opts) { + super(opts); + this.type = 'number'; + this.unit = opts.unit || ''; + } + + toString () { + return [ + this.raws.before, + String(this.value), + this.unit, + this.raws.after + ].join(''); + } +} + +Container.registerWalker(NumberNode); + +module.exports = NumberNode; /***/ }), @@ -11849,21 +11849,21 @@ module.exports = NumberNode; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); -const Node = __webpack_require__(4); - -class Operator extends Node { - constructor (opts) { - super(opts); - this.type = 'operator'; - } -} - -Container.registerWalker(Operator); - -module.exports = Operator; + + +const Container = __webpack_require__(1); +const Node = __webpack_require__(4); + +class Operator extends Node { + constructor (opts) { + super(opts); + this.type = 'operator'; + } +} + +Container.registerWalker(Operator); + +module.exports = Operator; /***/ }), @@ -11871,22 +11871,22 @@ module.exports = Operator; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); -const Node = __webpack_require__(4); - -class Parenthesis extends Node { - constructor (opts) { - super(opts); - this.type = 'paren'; - this.parenType = ''; - } -} - -Container.registerWalker(Parenthesis); - -module.exports = Parenthesis; + + +const Container = __webpack_require__(1); +const Node = __webpack_require__(4); + +class Parenthesis extends Node { + constructor (opts) { + super(opts); + this.type = 'paren'; + this.parenType = ''; + } +} + +Container.registerWalker(Parenthesis); + +module.exports = Parenthesis; /***/ }), @@ -11894,34 +11894,34 @@ module.exports = Parenthesis; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); -const Node = __webpack_require__(4); - -class StringNode extends Node { - constructor (opts) { - super(opts); - this.type = 'string'; - } - - toString () { - let quote = this.quoted ? this.raws.quote : ''; - return [ - this.raws.before, - quote, - // we can't use String() here because it'll try using itself - // as the constructor - this.value + '', - quote, - this.raws.after - ].join(''); - } -} - -Container.registerWalker(StringNode); - -module.exports = StringNode; + + +const Container = __webpack_require__(1); +const Node = __webpack_require__(4); + +class StringNode extends Node { + constructor (opts) { + super(opts); + this.type = 'string'; + } + + toString () { + let quote = this.quoted ? this.raws.quote : ''; + return [ + this.raws.before, + quote, + // we can't use String() here because it'll try using itself + // as the constructor + this.value + '', + quote, + this.raws.after + ].join(''); + } +} + +Container.registerWalker(StringNode); + +module.exports = StringNode; /***/ }), @@ -11929,17 +11929,17 @@ module.exports = StringNode; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); - -module.exports = class Value extends Container { - constructor (opts) { - super(opts); - this.type = 'value'; - this.unbalanced = 0; - } -}; + + +const Container = __webpack_require__(1); + +module.exports = class Value extends Container { + constructor (opts) { + super(opts); + this.type = 'value'; + this.unbalanced = 0; + } +}; /***/ }), @@ -11947,21 +11947,21 @@ module.exports = class Value extends Container { /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); -const Node = __webpack_require__(4); - -class Word extends Node { - constructor (opts) { - super(opts); - this.type = 'word'; - } -} - -Container.registerWalker(Word); - -module.exports = Word; + + +const Container = __webpack_require__(1); +const Node = __webpack_require__(4); + +class Word extends Node { + constructor (opts) { + super(opts); + this.type = 'word'; + } +} + +Container.registerWalker(Word); + +module.exports = Word; /***/ }), @@ -14800,74 +14800,74 @@ module.exports = exports['default']; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Parser = __webpack_require__(135); -const AtWord = __webpack_require__(56); -const Colon = __webpack_require__(57); -const Comma = __webpack_require__(58); -const Comment = __webpack_require__(59); -const Func = __webpack_require__(60); -const Num = __webpack_require__(61); -const Operator = __webpack_require__(62); -const Paren = __webpack_require__(63); -const Str = __webpack_require__(64); -const Value = __webpack_require__(65); -const Word = __webpack_require__(66); - -let parser = function (source, options) { - return new Parser(source, options); -}; - -parser.atword = function (opts) { - return new AtWord(opts); -}; - -parser.colon = function (opts) { - opts.value = opts.value || ':'; - return new Colon(opts); -}; - -parser.comma = function (opts) { - opts.value = opts.value || ','; - return new Comma(opts); -}; - -parser.comment = function (opts) { - return new Comment(opts); -}; - -parser.func = function (opts) { - return new Func(opts); -}; - -parser.number = function (opts) { - return new Num(opts); -}; - -parser.operator = function (opts) { - return new Operator(opts); -}; - -parser.paren = function (opts) { - opts.value = opts.value || '('; - return new Paren(opts); -}; - -parser.string = function (opts) { - opts.quote = opts.quote || '\''; - return new Str(opts); -}; - -parser.value = function (opts) { - return new Value(opts); -}; - -parser.word = function (opts) { - return new Word(opts); -}; - -module.exports = parser; + + +const Parser = __webpack_require__(135); +const AtWord = __webpack_require__(56); +const Colon = __webpack_require__(57); +const Comma = __webpack_require__(58); +const Comment = __webpack_require__(59); +const Func = __webpack_require__(60); +const Num = __webpack_require__(61); +const Operator = __webpack_require__(62); +const Paren = __webpack_require__(63); +const Str = __webpack_require__(64); +const Value = __webpack_require__(65); +const Word = __webpack_require__(66); + +let parser = function (source, options) { + return new Parser(source, options); +}; + +parser.atword = function (opts) { + return new AtWord(opts); +}; + +parser.colon = function (opts) { + opts.value = opts.value || ':'; + return new Colon(opts); +}; + +parser.comma = function (opts) { + opts.value = opts.value || ','; + return new Comma(opts); +}; + +parser.comment = function (opts) { + return new Comment(opts); +}; + +parser.func = function (opts) { + return new Func(opts); +}; + +parser.number = function (opts) { + return new Num(opts); +}; + +parser.operator = function (opts) { + return new Operator(opts); +}; + +parser.paren = function (opts) { + opts.value = opts.value || '('; + return new Paren(opts); +}; + +parser.string = function (opts) { + opts.quote = opts.quote || '\''; + return new Str(opts); +}; + +parser.value = function (opts) { + return new Value(opts); +}; + +parser.word = function (opts) { + return new Word(opts); +}; + +module.exports = parser; /***/ }), @@ -14875,18 +14875,18 @@ module.exports = parser; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -function createError(message, loc) { - // Construct an error similar to the ones thrown by Babylon. - const error = new SyntaxError( - message + " (" + loc.start.line + ":" + loc.start.column + ")" - ); - error.loc = loc; - return error; -} - -module.exports = createError; + + +function createError(message, loc) { + // Construct an error similar to the ones thrown by Babylon. + const error = new SyntaxError( + message + " (" + loc.start.line + ":" + loc.start.column + ")" + ); + error.loc = loc; + return error; +} + +module.exports = createError; /***/ }), @@ -20068,25 +20068,25 @@ module.exports = exports['default']; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -class ParserError extends Error { - constructor(message) { - super(message); - - this.name = this.constructor.name; - this.message = message || 'An error ocurred while parsing.'; - - if (typeof Error.captureStackTrace === 'function') { - Error.captureStackTrace(this, this.constructor); - } - else { - this.stack = (new Error(message)).stack; - } - } -} - -module.exports = ParserError; + + +class ParserError extends Error { + constructor(message) { + super(message); + + this.name = this.constructor.name; + this.message = message || 'An error ocurred while parsing.'; + + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, this.constructor); + } + else { + this.stack = (new Error(message)).stack; + } + } +} + +module.exports = ParserError; /***/ }), @@ -20094,25 +20094,25 @@ module.exports = ParserError; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -class TokenizeError extends Error { - constructor(message) { - super(message); - - this.name = this.constructor.name; - this.message = message || 'An error ocurred while tokzenizing.'; - - if (typeof Error.captureStackTrace === 'function') { - Error.captureStackTrace(this, this.constructor); - } - else { - this.stack = (new Error(message)).stack; - } - } -} - -module.exports = TokenizeError; + + +class TokenizeError extends Error { + constructor(message) { + super(message); + + this.name = this.constructor.name; + this.message = message || 'An error ocurred while tokzenizing.'; + + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, this.constructor); + } + else { + this.stack = (new Error(message)).stack; + } + } +} + +module.exports = TokenizeError; /***/ }), @@ -20120,547 +20120,547 @@ module.exports = TokenizeError; /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Root = __webpack_require__(136); -const Value = __webpack_require__(65); - -const AtWord = __webpack_require__(56); -const Colon = __webpack_require__(57); -const Comma = __webpack_require__(58); -const Comment = __webpack_require__(59); -const Func = __webpack_require__(60); -const Numbr = __webpack_require__(61); -const Operator = __webpack_require__(62); -const Paren = __webpack_require__(63); -const Str = __webpack_require__(64); -const Word = __webpack_require__(66); - -const tokenize = __webpack_require__(137); - -const flatten = __webpack_require__(31); -const indexesOf = __webpack_require__(32); -const uniq = __webpack_require__(79); -const ParserError = __webpack_require__(133); - -function sortAscending (list) { - return list.sort((a, b) => a - b); -} - -module.exports = class Parser { - constructor (input, options) { - const defaults = { loose: false }; - - // cache needs to be an array for values with more than 1 level of function nesting - this.cache = []; - this.input = input; - this.options = Object.assign({}, defaults, options); - this.position = 0; - // we'll use this to keep track of the paren balance - this.unbalanced = 0; - this.root = new Root(); - - let value = new Value(); - - this.root.append(value); - - this.current = value; - this.tokens = tokenize(input, this.options); - } - - parse () { - return this.loop(); - } - - colon () { - let token = this.currToken; - - this.newNode(new Colon({ - value: token[1], - source: { - start: { - line: token[2], - column: token[3] - }, - end: { - line: token[4], - column: token[5] - } - }, - sourceIndex: token[6] - })); - - this.position ++; - } - - comma () { - let token = this.currToken; - - this.newNode(new Comma({ - value: token[1], - source: { - start: { - line: token[2], - column: token[3] - }, - end: { - line: token[4], - column: token[5] - } - }, - sourceIndex: token[6] - })); - - this.position ++; - } - - comment () { - let node = new Comment({ - value: this.currToken[1].replace(/\/\*|\*\//g, ''), - source: { - start: { - line: this.currToken[2], - column: this.currToken[3] - }, - end: { - line: this.currToken[4], - column: this.currToken[5] - } - }, - sourceIndex: this.currToken[6] - }); - - this.newNode(node); - this.position++; - } - - error (message, token) { - throw new ParserError(message + ` at line: ${token[2]}, column ${token[3]}`); - } - - loop () { - while (this.position < this.tokens.length) { - this.parseTokens(); - } - - if (!this.current.last && this.spaces) { - this.current.raws.before += this.spaces; - } - else if (this.spaces) { - this.current.last.raws.after += this.spaces; - } - - this.spaces = ''; - - return this.root; - } - - operator () { - - // if a +|- operator is followed by a non-word character (. is allowed) and - // is preceded by a non-word character. (5+5) - let char = this.currToken[1], - node; - - if (char === '+' || char === '-') { - // only inspect if the operator is not the first token, and we're only - // within a calc() function: the only spec-valid place for math expressions - if (!this.options.loose) { - if (this.position > 0) { - if (this.current.type === 'func' && this.current.value === 'calc') { - // allow operators to be proceeded by spaces and opening parens - if (this.prevToken[0] !== 'space' && this.prevToken[0] !== '(') { - this.error('Syntax Error', this.currToken); - } - // valid: calc(1 - +2) - // invalid: calc(1 -+2) - else if (this.nextToken[0] !== 'space' && this.nextToken[0] !== 'word') { - this.error('Syntax Error', this.currToken); - } - // valid: calc(1 - +2) - // valid: calc(-0.5 + 2) - // invalid: calc(1 -2) - else if (this.nextToken[0] === 'word' && this.current.last.type !== 'operator' && - this.current.last.value !== '(') { - this.error('Syntax Error', this.currToken); - } - } - // if we're not in a function and someone has doubled up on operators, - // or they're trying to perform a calc outside of a calc - // eg. +-4px or 5+ 5, throw an error - else if (this.nextToken[0] === 'space' - || this.nextToken[0] === 'operator' - || this.prevToken[0] === 'operator') { - this.error('Syntax Error', this.currToken); - } - } - } - - if (!this.options.loose) { - if (this.nextToken[0] === 'word') { - return this.word(); - } - } - else { - if ((!this.current.nodes.length || (this.current.last && this.current.last.type === 'operator')) && this.nextToken[0] === 'word') { - return this.word(); - } - } - } - - node = new Operator({ - value: this.currToken[1], - source: { - start: { - line: this.currToken[2], - column: this.currToken[3] - }, - end: { - line: this.currToken[2], - column: this.currToken[3] - } - }, - sourceIndex: this.currToken[4] - }); - - this.position ++; - - return this.newNode(node); - } - - parseTokens () { - switch (this.currToken[0]) { - case 'space': - this.space(); - break; - case 'colon': - this.colon(); - break; - case 'comma': - this.comma(); - break; - case 'comment': - this.comment(); - break; - case '(': - this.parenOpen(); - break; - case ')': - this.parenClose(); - break; - case 'atword': - case 'word': - this.word(); - break; - case 'operator': - this.operator(); - break; - case 'string': - this.string(); - break; - default: - this.word(); - break; - } - } - - parenOpen () { - let unbalanced = 1, - pos = this.position + 1, - token = this.currToken, - last; - - // check for balanced parens - while (pos < this.tokens.length && unbalanced) { - let tkn = this.tokens[pos]; - - if (tkn[0] === '(') { - unbalanced++; - } - if (tkn[0] === ')') { - unbalanced--; - } - pos ++; - } - - if (unbalanced) { - this.error('Expected closing parenthesis', token); - } - - // ok, all parens are balanced. continue on - - last = this.current.last; - - if (last && last.type === 'func' && last.unbalanced < 0) { - last.unbalanced = 0; // ok we're ready to add parens now - this.current = last; - } - - this.current.unbalanced ++; - - this.newNode(new Paren({ - value: token[1], - source: { - start: { - line: token[2], - column: token[3] - }, - end: { - line: token[4], - column: token[5] - } - }, - sourceIndex: token[6] - })); - - this.position ++; - - // url functions get special treatment, and anything between the function - // parens get treated as one word, if the contents aren't not a string. - if (this.current.type === 'func' && this.current.unbalanced && - this.current.value === 'url' && this.currToken[0] !== 'string' && - this.currToken[0] !== ')' && !this.options.loose) { - - let nextToken = this.nextToken, - value = this.currToken[1], - start = { - line: this.currToken[2], - column: this.currToken[3] - }; - - while (nextToken && nextToken[0] !== ')' && this.current.unbalanced) { - this.position ++; - value += this.currToken[1]; - nextToken = this.nextToken; - } - - if (this.position !== this.tokens.length - 1) { - // skip the following word definition, or it'll be a duplicate - this.position ++; - - this.newNode(new Word({ - value, - source: { - start, - end: { - line: this.currToken[4], - column: this.currToken[5] - } - }, - sourceIndex: this.currToken[6] - })); - } - } - } - - parenClose () { - let token = this.currToken; - - this.newNode(new Paren({ - value: token[1], - source: { - start: { - line: token[2], - column: token[3] - }, - end: { - line: token[4], - column: token[5] - } - }, - sourceIndex: token[6] - })); - - this.position ++; - - if (this.position >= this.tokens.length - 1 && !this.current.unbalanced) { - return; - } - - this.current.unbalanced --; - - if (this.current.unbalanced < 0) { - this.error('Expected opening parenthesis', token); - } - - if (!this.current.unbalanced && this.cache.length) { - this.current = this.cache.pop(); - } - } - - space () { - let token = this.currToken; - // Handle space before and after the selector - if (this.position === (this.tokens.length - 1) || this.nextToken[0] === ',' || this.nextToken[0] === ')') { - this.current.last.raws.after += token[1]; - this.position ++; - } - else { - this.spaces = token[1]; - this.position ++; - } - } - - splitWord () { - let nextToken = this.nextToken, - word = this.currToken[1], - rNumber = /^[\+\-]?((\d+(\.\d*)?)|(\.\d+))/, - - // treat css-like groupings differently so they can be inspected, - // but don't address them as anything but a word, but allow hex values - // to pass through. - rNoFollow = /^(?!\#([a-z0-9]+))[\#\{\}]/gi, - - hasAt, indices; - - if (!rNoFollow.test(word)) { - while (nextToken && nextToken[0] === 'word') { - this.position ++; - - let current = this.currToken[1]; - word += current; - - nextToken = this.nextToken; - } - } - - hasAt = indexesOf(word, '@'); - indices = sortAscending(uniq(flatten([[0], hasAt]))); - - indices.forEach((ind, i) => { - let index = indices[i + 1] || word.length, - value = word.slice(ind, index), - node; - - if (~hasAt.indexOf(ind)) { - node = new AtWord({ - value: value.slice(1), - source: { - start: { - line: this.currToken[2], - column: this.currToken[3] + ind - }, - end: { - line: this.currToken[4], - column: this.currToken[3] + (index - 1) - } - }, - sourceIndex: this.currToken[6] + indices[i] - }); - } - else if (rNumber.test(this.currToken[1])) { - let unit = value.replace(rNumber, ''); - - node = new Numbr({ - value: value.replace(unit, ''), - source: { - start: { - line: this.currToken[2], - column: this.currToken[3] + ind - }, - end: { - line: this.currToken[4], - column: this.currToken[3] + (index - 1) - } - }, - sourceIndex: this.currToken[6] + indices[i], - unit - }); - } - else { - node = new (nextToken && nextToken[0] === '(' ? Func : Word)({ - value, - source: { - start: { - line: this.currToken[2], - column: this.currToken[3] + ind - }, - end: { - line: this.currToken[4], - column: this.currToken[3] + (index - 1) - } - }, - sourceIndex: this.currToken[6] + indices[i] - }); - - if (node.constructor.name === 'Word') { - node.isHex = /^#(.+)/.test(value); - node.isColor = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value); - } - else { - this.cache.push(this.current); - } - } - - this.newNode(node); - - }); - - this.position ++; - } - - string () { - let token = this.currToken, - value = this.currToken[1], - rQuote = /^(\"|\')/, - quoted = rQuote.test(value), - quote = '', - node; - - if (quoted) { - quote = value.match(rQuote)[0]; - // set value to the string within the quotes - // quotes are stored in raws - value = value.slice(1, value.length - 1); - } - - node = new Str({ - value, - source: { - start: { - line: token[2], - column: token[3] - }, - end: { - line: token[4], - column: token[5] - } - }, - sourceIndex: token[6], - quoted - }); - - node.raws.quote = quote; - - this.newNode(node); - this.position++; - } - - word () { - return this.splitWord(); - } - - newNode (node) { - if (this.spaces) { - node.raws.before += this.spaces; - this.spaces = ''; - } - - return this.current.append(node); - } - - get currToken () { - return this.tokens[this.position]; - } - - get nextToken () { - return this.tokens[this.position + 1]; - } - - get prevToken () { - return this.tokens[this.position - 1]; - } -}; + + +const Root = __webpack_require__(136); +const Value = __webpack_require__(65); + +const AtWord = __webpack_require__(56); +const Colon = __webpack_require__(57); +const Comma = __webpack_require__(58); +const Comment = __webpack_require__(59); +const Func = __webpack_require__(60); +const Numbr = __webpack_require__(61); +const Operator = __webpack_require__(62); +const Paren = __webpack_require__(63); +const Str = __webpack_require__(64); +const Word = __webpack_require__(66); + +const tokenize = __webpack_require__(137); + +const flatten = __webpack_require__(31); +const indexesOf = __webpack_require__(32); +const uniq = __webpack_require__(79); +const ParserError = __webpack_require__(133); + +function sortAscending (list) { + return list.sort((a, b) => a - b); +} + +module.exports = class Parser { + constructor (input, options) { + const defaults = { loose: false }; + + // cache needs to be an array for values with more than 1 level of function nesting + this.cache = []; + this.input = input; + this.options = Object.assign({}, defaults, options); + this.position = 0; + // we'll use this to keep track of the paren balance + this.unbalanced = 0; + this.root = new Root(); + + let value = new Value(); + + this.root.append(value); + + this.current = value; + this.tokens = tokenize(input, this.options); + } + + parse () { + return this.loop(); + } + + colon () { + let token = this.currToken; + + this.newNode(new Colon({ + value: token[1], + source: { + start: { + line: token[2], + column: token[3] + }, + end: { + line: token[4], + column: token[5] + } + }, + sourceIndex: token[6] + })); + + this.position ++; + } + + comma () { + let token = this.currToken; + + this.newNode(new Comma({ + value: token[1], + source: { + start: { + line: token[2], + column: token[3] + }, + end: { + line: token[4], + column: token[5] + } + }, + sourceIndex: token[6] + })); + + this.position ++; + } + + comment () { + let node = new Comment({ + value: this.currToken[1].replace(/\/\*|\*\//g, ''), + source: { + start: { + line: this.currToken[2], + column: this.currToken[3] + }, + end: { + line: this.currToken[4], + column: this.currToken[5] + } + }, + sourceIndex: this.currToken[6] + }); + + this.newNode(node); + this.position++; + } + + error (message, token) { + throw new ParserError(message + ` at line: ${token[2]}, column ${token[3]}`); + } + + loop () { + while (this.position < this.tokens.length) { + this.parseTokens(); + } + + if (!this.current.last && this.spaces) { + this.current.raws.before += this.spaces; + } + else if (this.spaces) { + this.current.last.raws.after += this.spaces; + } + + this.spaces = ''; + + return this.root; + } + + operator () { + + // if a +|- operator is followed by a non-word character (. is allowed) and + // is preceded by a non-word character. (5+5) + let char = this.currToken[1], + node; + + if (char === '+' || char === '-') { + // only inspect if the operator is not the first token, and we're only + // within a calc() function: the only spec-valid place for math expressions + if (!this.options.loose) { + if (this.position > 0) { + if (this.current.type === 'func' && this.current.value === 'calc') { + // allow operators to be proceeded by spaces and opening parens + if (this.prevToken[0] !== 'space' && this.prevToken[0] !== '(') { + this.error('Syntax Error', this.currToken); + } + // valid: calc(1 - +2) + // invalid: calc(1 -+2) + else if (this.nextToken[0] !== 'space' && this.nextToken[0] !== 'word') { + this.error('Syntax Error', this.currToken); + } + // valid: calc(1 - +2) + // valid: calc(-0.5 + 2) + // invalid: calc(1 -2) + else if (this.nextToken[0] === 'word' && this.current.last.type !== 'operator' && + this.current.last.value !== '(') { + this.error('Syntax Error', this.currToken); + } + } + // if we're not in a function and someone has doubled up on operators, + // or they're trying to perform a calc outside of a calc + // eg. +-4px or 5+ 5, throw an error + else if (this.nextToken[0] === 'space' + || this.nextToken[0] === 'operator' + || this.prevToken[0] === 'operator') { + this.error('Syntax Error', this.currToken); + } + } + } + + if (!this.options.loose) { + if (this.nextToken[0] === 'word') { + return this.word(); + } + } + else { + if ((!this.current.nodes.length || (this.current.last && this.current.last.type === 'operator')) && this.nextToken[0] === 'word') { + return this.word(); + } + } + } + + node = new Operator({ + value: this.currToken[1], + source: { + start: { + line: this.currToken[2], + column: this.currToken[3] + }, + end: { + line: this.currToken[2], + column: this.currToken[3] + } + }, + sourceIndex: this.currToken[4] + }); + + this.position ++; + + return this.newNode(node); + } + + parseTokens () { + switch (this.currToken[0]) { + case 'space': + this.space(); + break; + case 'colon': + this.colon(); + break; + case 'comma': + this.comma(); + break; + case 'comment': + this.comment(); + break; + case '(': + this.parenOpen(); + break; + case ')': + this.parenClose(); + break; + case 'atword': + case 'word': + this.word(); + break; + case 'operator': + this.operator(); + break; + case 'string': + this.string(); + break; + default: + this.word(); + break; + } + } + + parenOpen () { + let unbalanced = 1, + pos = this.position + 1, + token = this.currToken, + last; + + // check for balanced parens + while (pos < this.tokens.length && unbalanced) { + let tkn = this.tokens[pos]; + + if (tkn[0] === '(') { + unbalanced++; + } + if (tkn[0] === ')') { + unbalanced--; + } + pos ++; + } + + if (unbalanced) { + this.error('Expected closing parenthesis', token); + } + + // ok, all parens are balanced. continue on + + last = this.current.last; + + if (last && last.type === 'func' && last.unbalanced < 0) { + last.unbalanced = 0; // ok we're ready to add parens now + this.current = last; + } + + this.current.unbalanced ++; + + this.newNode(new Paren({ + value: token[1], + source: { + start: { + line: token[2], + column: token[3] + }, + end: { + line: token[4], + column: token[5] + } + }, + sourceIndex: token[6] + })); + + this.position ++; + + // url functions get special treatment, and anything between the function + // parens get treated as one word, if the contents aren't not a string. + if (this.current.type === 'func' && this.current.unbalanced && + this.current.value === 'url' && this.currToken[0] !== 'string' && + this.currToken[0] !== ')' && !this.options.loose) { + + let nextToken = this.nextToken, + value = this.currToken[1], + start = { + line: this.currToken[2], + column: this.currToken[3] + }; + + while (nextToken && nextToken[0] !== ')' && this.current.unbalanced) { + this.position ++; + value += this.currToken[1]; + nextToken = this.nextToken; + } + + if (this.position !== this.tokens.length - 1) { + // skip the following word definition, or it'll be a duplicate + this.position ++; + + this.newNode(new Word({ + value, + source: { + start, + end: { + line: this.currToken[4], + column: this.currToken[5] + } + }, + sourceIndex: this.currToken[6] + })); + } + } + } + + parenClose () { + let token = this.currToken; + + this.newNode(new Paren({ + value: token[1], + source: { + start: { + line: token[2], + column: token[3] + }, + end: { + line: token[4], + column: token[5] + } + }, + sourceIndex: token[6] + })); + + this.position ++; + + if (this.position >= this.tokens.length - 1 && !this.current.unbalanced) { + return; + } + + this.current.unbalanced --; + + if (this.current.unbalanced < 0) { + this.error('Expected opening parenthesis', token); + } + + if (!this.current.unbalanced && this.cache.length) { + this.current = this.cache.pop(); + } + } + + space () { + let token = this.currToken; + // Handle space before and after the selector + if (this.position === (this.tokens.length - 1) || this.nextToken[0] === ',' || this.nextToken[0] === ')') { + this.current.last.raws.after += token[1]; + this.position ++; + } + else { + this.spaces = token[1]; + this.position ++; + } + } + + splitWord () { + let nextToken = this.nextToken, + word = this.currToken[1], + rNumber = /^[\+\-]?((\d+(\.\d*)?)|(\.\d+))/, + + // treat css-like groupings differently so they can be inspected, + // but don't address them as anything but a word, but allow hex values + // to pass through. + rNoFollow = /^(?!\#([a-z0-9]+))[\#\{\}]/gi, + + hasAt, indices; + + if (!rNoFollow.test(word)) { + while (nextToken && nextToken[0] === 'word') { + this.position ++; + + let current = this.currToken[1]; + word += current; + + nextToken = this.nextToken; + } + } + + hasAt = indexesOf(word, '@'); + indices = sortAscending(uniq(flatten([[0], hasAt]))); + + indices.forEach((ind, i) => { + let index = indices[i + 1] || word.length, + value = word.slice(ind, index), + node; + + if (~hasAt.indexOf(ind)) { + node = new AtWord({ + value: value.slice(1), + source: { + start: { + line: this.currToken[2], + column: this.currToken[3] + ind + }, + end: { + line: this.currToken[4], + column: this.currToken[3] + (index - 1) + } + }, + sourceIndex: this.currToken[6] + indices[i] + }); + } + else if (rNumber.test(this.currToken[1])) { + let unit = value.replace(rNumber, ''); + + node = new Numbr({ + value: value.replace(unit, ''), + source: { + start: { + line: this.currToken[2], + column: this.currToken[3] + ind + }, + end: { + line: this.currToken[4], + column: this.currToken[3] + (index - 1) + } + }, + sourceIndex: this.currToken[6] + indices[i], + unit + }); + } + else { + node = new (nextToken && nextToken[0] === '(' ? Func : Word)({ + value, + source: { + start: { + line: this.currToken[2], + column: this.currToken[3] + ind + }, + end: { + line: this.currToken[4], + column: this.currToken[3] + (index - 1) + } + }, + sourceIndex: this.currToken[6] + indices[i] + }); + + if (node.constructor.name === 'Word') { + node.isHex = /^#(.+)/.test(value); + node.isColor = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value); + } + else { + this.cache.push(this.current); + } + } + + this.newNode(node); + + }); + + this.position ++; + } + + string () { + let token = this.currToken, + value = this.currToken[1], + rQuote = /^(\"|\')/, + quoted = rQuote.test(value), + quote = '', + node; + + if (quoted) { + quote = value.match(rQuote)[0]; + // set value to the string within the quotes + // quotes are stored in raws + value = value.slice(1, value.length - 1); + } + + node = new Str({ + value, + source: { + start: { + line: token[2], + column: token[3] + }, + end: { + line: token[4], + column: token[5] + } + }, + sourceIndex: token[6], + quoted + }); + + node.raws.quote = quote; + + this.newNode(node); + this.position++; + } + + word () { + return this.splitWord(); + } + + newNode (node) { + if (this.spaces) { + node.raws.before += this.spaces; + this.spaces = ''; + } + + return this.current.append(node); + } + + get currToken () { + return this.tokens[this.position]; + } + + get nextToken () { + return this.tokens[this.position + 1]; + } + + get prevToken () { + return this.tokens[this.position - 1]; + } +}; /***/ }), @@ -20668,16 +20668,16 @@ module.exports = class Parser { /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const Container = __webpack_require__(1); - -module.exports = class Root extends Container { - constructor (opts) { - super(opts); - this.type = 'root'; - } -}; + + +const Container = __webpack_require__(1); + +module.exports = class Root extends Container { + constructor (opts) { + super(opts); + this.type = 'root'; + } +}; /***/ }), @@ -20685,331 +20685,331 @@ module.exports = class Root extends Container { /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const openBracket = '{'.charCodeAt(0); -const closeBracket = '}'.charCodeAt(0); -const openParen = '('.charCodeAt(0); -const closeParen = ')'.charCodeAt(0); -const singleQuote = '\''.charCodeAt(0); -const doubleQuote = '"'.charCodeAt(0); -const backslash = '\\'.charCodeAt(0); -const slash = '/'.charCodeAt(0); -const comma = ','.charCodeAt(0); -const colon = ':'.charCodeAt(0); -const asterisk = '*'.charCodeAt(0); -const minus = '-'.charCodeAt(0); -const plus = '+'.charCodeAt(0); -const pound = '#'.charCodeAt(0); -const newline = '\n'.charCodeAt(0); -const space = ' '.charCodeAt(0); -const feed = '\f'.charCodeAt(0); -const tab = '\t'.charCodeAt(0); -const cr = '\r'.charCodeAt(0); -const at = '@'.charCodeAt(0); -const atEnd = /[ \n\t\r\{\(\)'"\\;,/]/g; -const wordEnd = /[ \n\t\r\(\)\{\}\*:;@!&'"\+\|~>,\[\]\\]|\/(?=\*)/g; -const wordEndNum = /[ \n\t\r\(\)\{\}\*:;@!&'"\-\+\|~>,\[\]\\]|\//g; -const alphaNum = /^[a-z0-9]/i; - -const util = __webpack_require__(155); -const TokenizeError = __webpack_require__(134); - -module.exports = function tokenize (input, options) { - - options = options || {}; - - let tokens = [], - css = input.valueOf(), - length = css.length, - offset = -1, - line = 1, - pos = 0, - - code, next, quote, lines, last, content, escape, nextLine, nextOffset, - escaped, escapePos, nextChar; - - function unclosed (what) { - let message = util.format('Unclosed %s at line: %d, column: %d, token: %d', what, line, pos - offset, pos); - throw new TokenizeError(message); - } - - while (pos < length) { - code = css.charCodeAt(pos); - - if (code === newline) { - offset = pos; - line += 1; - } - - switch (code) { - case newline: - case space: - case tab: - case cr: - case feed: - next = pos; - do { - next += 1; - code = css.charCodeAt(next); - if (code === newline) { - offset = next; - line += 1; - } - } while (code === space || - code === newline || - code === tab || - code === cr || - code === feed); - - tokens.push(['space', css.slice(pos, next), - line, pos - offset, - line, next - offset, - pos - ]); - - pos = next - 1; - break; - - case colon: - next = pos + 1; - tokens.push(['colon', css.slice(pos, next), - line, pos - offset, - line, next - offset, - pos - ]); - - pos = next - 1; - break; - - case comma: - next = pos + 1; - tokens.push(['comma', css.slice(pos, next), - line, pos - offset, - line, next - offset, - pos - ]); - - pos = next - 1; - break; - - case openBracket: - tokens.push(['{', '{', - line, pos - offset, - line, next - offset, - pos - ]); - break; - - case closeBracket: - tokens.push(['}', '}', - line, pos - offset, - line, next - offset, - pos - ]); - break; - - case openParen: - tokens.push(['(', '(', - line, pos - offset, - line, next - offset, - pos - ]); - break; - - case closeParen: - tokens.push([')', ')', - line, pos - offset, - line, next - offset, - pos - ]); - break; - - case singleQuote: - case doubleQuote: - quote = code === singleQuote ? '\'' : '"'; - next = pos; - do { - escaped = false; - next = css.indexOf(quote, next + 1); - if (next === -1) { - unclosed('quote', quote); - } - escapePos = next; - while (css.charCodeAt(escapePos - 1) === backslash) { - escapePos -= 1; - escaped = !escaped; - } - } while (escaped); - - tokens.push(['string', css.slice(pos, next + 1), - line, pos - offset, - line, next - offset, - pos - ]); - pos = next; - break; - - case at: - atEnd.lastIndex = pos + 1; - atEnd.test(css); - - if (atEnd.lastIndex === 0) { - next = css.length - 1; - } - else { - next = atEnd.lastIndex - 2; - } - - tokens.push(['atword', css.slice(pos, next + 1), - line, pos - offset, - line, next - offset, - pos - ]); - pos = next; - break; - - case backslash: - next = pos; - code = css.charCodeAt(next + 1); - - if (escape && (code !== slash && code !== space && - code !== newline && code !== tab && - code !== cr && code !== feed)) { - next += 1; - } - - tokens.push(['word', css.slice(pos, next + 1), - line, pos - offset, - line, next - offset, - pos - ]); - - pos = next; - break; - - case plus: - case minus: - case asterisk: - next = pos + 1; - nextChar = css.slice(pos + 1, next + 1); - - let prevChar = css.slice(pos - 1, pos); - - // if the operator is immediately followed by a word character, then we - // have a prefix of some kind, and should fall-through. eg. -webkit - - // look for --* for custom variables - if (code === minus && nextChar.charCodeAt(0) === minus) { - next++; - - tokens.push(['word', css.slice(pos, next), - line, pos - offset, - line, next - offset, - pos - ]); - - pos = next - 1; - break; - } - - tokens.push(['operator', css.slice(pos, next), - line, pos - offset, - line, next - offset, - pos - ]); - - pos = next - 1; - break; - - default: - if (code === slash && css.charCodeAt(pos + 1) === asterisk) { - next = css.indexOf('*/', pos + 2) + 1; - if (next === 0) { - unclosed('comment', '*/'); - } - - content = css.slice(pos, next + 1); - lines = content.split('\n'); - last = lines.length - 1; - - if (last > 0) { - nextLine = line + last; - nextOffset = next - lines[last].length; - } - else { - nextLine = line; - nextOffset = offset; - } - - tokens.push(['comment', content, - line, pos - offset, - nextLine, next - nextOffset, - pos - ]); - - offset = nextOffset; - line = nextLine; - pos = next; - - } - else if (code === pound && !alphaNum.test(css.slice(pos + 1, pos + 2))) { - next = pos + 1; - - tokens.push(['#', css.slice(pos, next), - line, pos - offset, - line, next - offset, - pos - ]); - - pos = next - 1; - } - // catch a regular slash, that isn't a comment - else if (code === slash) { - next = pos + 1; - - tokens.push(['operator', css.slice(pos, next), - line, pos - offset, - line, next - offset, - pos - ]); - - pos = next - 1; - } - else { - let regex = wordEnd; - - // we're dealing with a word that starts with a number - // those get treated differently - if (code >= 48 && code <= 57) { - regex = wordEndNum; - } - - regex.lastIndex = pos + 1; - regex.test(css); - - if (regex.lastIndex === 0) { - next = css.length - 1; - } - else { - next = regex.lastIndex - 2; - } - - tokens.push(['word', css.slice(pos, next + 1), - line, pos - offset, - line, next - offset, - pos - ]); - pos = next; - } - break; - } - - pos ++; - } - - return tokens; -}; + + +const openBracket = '{'.charCodeAt(0); +const closeBracket = '}'.charCodeAt(0); +const openParen = '('.charCodeAt(0); +const closeParen = ')'.charCodeAt(0); +const singleQuote = '\''.charCodeAt(0); +const doubleQuote = '"'.charCodeAt(0); +const backslash = '\\'.charCodeAt(0); +const slash = '/'.charCodeAt(0); +const comma = ','.charCodeAt(0); +const colon = ':'.charCodeAt(0); +const asterisk = '*'.charCodeAt(0); +const minus = '-'.charCodeAt(0); +const plus = '+'.charCodeAt(0); +const pound = '#'.charCodeAt(0); +const newline = '\n'.charCodeAt(0); +const space = ' '.charCodeAt(0); +const feed = '\f'.charCodeAt(0); +const tab = '\t'.charCodeAt(0); +const cr = '\r'.charCodeAt(0); +const at = '@'.charCodeAt(0); +const atEnd = /[ \n\t\r\{\(\)'"\\;,/]/g; +const wordEnd = /[ \n\t\r\(\)\{\}\*:;@!&'"\+\|~>,\[\]\\]|\/(?=\*)/g; +const wordEndNum = /[ \n\t\r\(\)\{\}\*:;@!&'"\-\+\|~>,\[\]\\]|\//g; +const alphaNum = /^[a-z0-9]/i; + +const util = __webpack_require__(155); +const TokenizeError = __webpack_require__(134); + +module.exports = function tokenize (input, options) { + + options = options || {}; + + let tokens = [], + css = input.valueOf(), + length = css.length, + offset = -1, + line = 1, + pos = 0, + + code, next, quote, lines, last, content, escape, nextLine, nextOffset, + escaped, escapePos, nextChar; + + function unclosed (what) { + let message = util.format('Unclosed %s at line: %d, column: %d, token: %d', what, line, pos - offset, pos); + throw new TokenizeError(message); + } + + while (pos < length) { + code = css.charCodeAt(pos); + + if (code === newline) { + offset = pos; + line += 1; + } + + switch (code) { + case newline: + case space: + case tab: + case cr: + case feed: + next = pos; + do { + next += 1; + code = css.charCodeAt(next); + if (code === newline) { + offset = next; + line += 1; + } + } while (code === space || + code === newline || + code === tab || + code === cr || + code === feed); + + tokens.push(['space', css.slice(pos, next), + line, pos - offset, + line, next - offset, + pos + ]); + + pos = next - 1; + break; + + case colon: + next = pos + 1; + tokens.push(['colon', css.slice(pos, next), + line, pos - offset, + line, next - offset, + pos + ]); + + pos = next - 1; + break; + + case comma: + next = pos + 1; + tokens.push(['comma', css.slice(pos, next), + line, pos - offset, + line, next - offset, + pos + ]); + + pos = next - 1; + break; + + case openBracket: + tokens.push(['{', '{', + line, pos - offset, + line, next - offset, + pos + ]); + break; + + case closeBracket: + tokens.push(['}', '}', + line, pos - offset, + line, next - offset, + pos + ]); + break; + + case openParen: + tokens.push(['(', '(', + line, pos - offset, + line, next - offset, + pos + ]); + break; + + case closeParen: + tokens.push([')', ')', + line, pos - offset, + line, next - offset, + pos + ]); + break; + + case singleQuote: + case doubleQuote: + quote = code === singleQuote ? '\'' : '"'; + next = pos; + do { + escaped = false; + next = css.indexOf(quote, next + 1); + if (next === -1) { + unclosed('quote', quote); + } + escapePos = next; + while (css.charCodeAt(escapePos - 1) === backslash) { + escapePos -= 1; + escaped = !escaped; + } + } while (escaped); + + tokens.push(['string', css.slice(pos, next + 1), + line, pos - offset, + line, next - offset, + pos + ]); + pos = next; + break; + + case at: + atEnd.lastIndex = pos + 1; + atEnd.test(css); + + if (atEnd.lastIndex === 0) { + next = css.length - 1; + } + else { + next = atEnd.lastIndex - 2; + } + + tokens.push(['atword', css.slice(pos, next + 1), + line, pos - offset, + line, next - offset, + pos + ]); + pos = next; + break; + + case backslash: + next = pos; + code = css.charCodeAt(next + 1); + + if (escape && (code !== slash && code !== space && + code !== newline && code !== tab && + code !== cr && code !== feed)) { + next += 1; + } + + tokens.push(['word', css.slice(pos, next + 1), + line, pos - offset, + line, next - offset, + pos + ]); + + pos = next; + break; + + case plus: + case minus: + case asterisk: + next = pos + 1; + nextChar = css.slice(pos + 1, next + 1); + + let prevChar = css.slice(pos - 1, pos); + + // if the operator is immediately followed by a word character, then we + // have a prefix of some kind, and should fall-through. eg. -webkit + + // look for --* for custom variables + if (code === minus && nextChar.charCodeAt(0) === minus) { + next++; + + tokens.push(['word', css.slice(pos, next), + line, pos - offset, + line, next - offset, + pos + ]); + + pos = next - 1; + break; + } + + tokens.push(['operator', css.slice(pos, next), + line, pos - offset, + line, next - offset, + pos + ]); + + pos = next - 1; + break; + + default: + if (code === slash && css.charCodeAt(pos + 1) === asterisk) { + next = css.indexOf('*/', pos + 2) + 1; + if (next === 0) { + unclosed('comment', '*/'); + } + + content = css.slice(pos, next + 1); + lines = content.split('\n'); + last = lines.length - 1; + + if (last > 0) { + nextLine = line + last; + nextOffset = next - lines[last].length; + } + else { + nextLine = line; + nextOffset = offset; + } + + tokens.push(['comment', content, + line, pos - offset, + nextLine, next - nextOffset, + pos + ]); + + offset = nextOffset; + line = nextLine; + pos = next; + + } + else if (code === pound && !alphaNum.test(css.slice(pos + 1, pos + 2))) { + next = pos + 1; + + tokens.push(['#', css.slice(pos, next), + line, pos - offset, + line, next - offset, + pos + ]); + + pos = next - 1; + } + // catch a regular slash, that isn't a comment + else if (code === slash) { + next = pos + 1; + + tokens.push(['operator', css.slice(pos, next), + line, pos - offset, + line, next - offset, + pos + ]); + + pos = next - 1; + } + else { + let regex = wordEnd; + + // we're dealing with a word that starts with a number + // those get treated differently + if (code >= 48 && code <= 57) { + regex = wordEndNum; + } + + regex.lastIndex = pos + 1; + regex.test(css); + + if (regex.lastIndex === 0) { + next = css.length - 1; + } + else { + next = regex.lastIndex - 2; + } + + tokens.push(['word', css.slice(pos, next + 1), + line, pos - offset, + line, next - offset, + pos + ]); + pos = next; + } + break; + } + + pos ++; + } + + return tokens; +}; /***/ }), @@ -24883,230 +24883,230 @@ module.exports = function(module) { /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -const createError = __webpack_require__(86); - -function parseSelector(selector) { - const selectorParser = __webpack_require__(84); - let result; - selectorParser(result_ => { - result = result_; - }).process(selector); - return addTypePrefix(result, "selector-"); -} - -function parseValueNodes(nodes) { - let parenGroup = { - open: null, - close: null, - groups: [], - type: "paren_group" - }; - const parenGroupStack = [parenGroup]; - const rootParenGroup = parenGroup; - let commaGroup = { - groups: [], - type: "comma_group" - }; - const commaGroupStack = [commaGroup]; - - for (let i = 0; i < nodes.length; ++i) { - const node = nodes[i]; - if (node.type === "paren" && node.value === "(") { - parenGroup = { - open: node, - close: null, - groups: [], - type: "paren_group" - }; - parenGroupStack.push(parenGroup); - - commaGroup = { - groups: [], - type: "comma_group" - }; - commaGroupStack.push(commaGroup); - } else if (node.type === "paren" && node.value === ")") { - if (commaGroup.groups.length) { - parenGroup.groups.push(commaGroup); - } - parenGroup.close = node; - - if (commaGroupStack.length === 1) { - throw new Error("Unbalanced parenthesis"); - } - - commaGroupStack.pop(); - commaGroup = commaGroupStack[commaGroupStack.length - 1]; - commaGroup.groups.push(parenGroup); - - parenGroupStack.pop(); - parenGroup = parenGroupStack[parenGroupStack.length - 1]; - } else if (node.type === "comma") { - parenGroup.groups.push(commaGroup); - commaGroup = { - groups: [], - type: "comma_group" - }; - commaGroupStack[commaGroupStack.length - 1] = commaGroup; - } else { - commaGroup.groups.push(node); - } - } - if (commaGroup.groups.length > 0) { - parenGroup.groups.push(commaGroup); - } - return rootParenGroup; -} - -function flattenGroups(node) { - if ( - node.type === "paren_group" && - !node.open && - !node.close && - node.groups.length === 1 - ) { - return flattenGroups(node.groups[0]); - } - - if (node.type === "comma_group" && node.groups.length === 1) { - return flattenGroups(node.groups[0]); - } - - if (node.type === "paren_group" || node.type === "comma_group") { - return Object.assign({}, node, { groups: node.groups.map(flattenGroups) }); - } - - return node; -} - -function addTypePrefix(node, prefix) { - if (node && typeof node === "object") { - delete node.parent; - for (const key in node) { - addTypePrefix(node[key], prefix); - if (key === "type" && typeof node[key] === "string") { - if (!node[key].startsWith(prefix)) { - node[key] = prefix + node[key]; - } - } - } - } - return node; -} - -function addMissingType(node) { - if (node && typeof node === "object") { - delete node.parent; - for (const key in node) { - addMissingType(node[key]); - } - if (!Array.isArray(node) && node.value && !node.type) { - node.type = "unknown"; - } - } - return node; -} - -function parseNestedValue(node) { - if (node && typeof node === "object") { - delete node.parent; - for (const key in node) { - parseNestedValue(node[key]); - if (key === "nodes") { - node.group = flattenGroups(parseValueNodes(node[key])); - delete node[key]; - } - } - } - return node; -} - -function parseValue(value) { - const valueParser = __webpack_require__(85); - const result = valueParser(value, { loose: true }).parse(); - const parsedResult = parseNestedValue(result); - return addTypePrefix(parsedResult, "value-"); -} - -function parseMediaQuery(value) { - const mediaParser = __webpack_require__(82).default; - const result = addMissingType(mediaParser(value)); - return addTypePrefix(result, "media-"); -} - -function parseNestedCSS(node) { - if (node && typeof node === "object") { - delete node.parent; - for (const key in node) { - parseNestedCSS(node[key]); - } - if (typeof node.selector === "string") { - const selector = node.raws.selector - ? node.raws.selector.raw - : node.selector; - - try { - node.selector = parseSelector(selector); - } catch (e) { - // Fail silently. It's better to print it as is than to try and parse it - node.selector = selector; - } - } - if (node.type && typeof node.value === "string") { - try { - node.value = parseValue(node.value); - } catch (e) { - throw createError( - "(postcss-values-parser) " + e.toString(), - node.source - ); - } - } - if (node.type === "css-atrule" && typeof node.params === "string") { - node.params = parseMediaQuery(node.params); - } - } - return node; -} - -function parseWithParser(parser, text) { - let result; - try { - result = parser.parse(text); - } catch (e) { - if (typeof e.line !== "number") { - throw e; - } - throw createError("(postcss) " + e.name + " " + e.reason, { start: e }); - } - const prefixedResult = addTypePrefix(result, "css-"); - const parsedResult = parseNestedCSS(prefixedResult); - return parsedResult; -} - -function requireParser(isSCSS) { - if (isSCSS) { - return __webpack_require__(83); - } - return __webpack_require__(81); -} - -function parse(text) { - const isLikelySCSS = !!text.match(/(\w\s*: [^}:]+|#){|\@import url/); - try { - return parseWithParser(requireParser(isLikelySCSS), text); - } catch (e) { - try { - return parseWithParser(requireParser(!isLikelySCSS), text); - } catch (e2) { - throw e; - } - } -} - -module.exports = parse; + + +const createError = __webpack_require__(86); + +function parseSelector(selector) { + const selectorParser = __webpack_require__(84); + let result; + selectorParser(result_ => { + result = result_; + }).process(selector); + return addTypePrefix(result, "selector-"); +} + +function parseValueNodes(nodes) { + let parenGroup = { + open: null, + close: null, + groups: [], + type: "paren_group" + }; + const parenGroupStack = [parenGroup]; + const rootParenGroup = parenGroup; + let commaGroup = { + groups: [], + type: "comma_group" + }; + const commaGroupStack = [commaGroup]; + + for (let i = 0; i < nodes.length; ++i) { + const node = nodes[i]; + if (node.type === "paren" && node.value === "(") { + parenGroup = { + open: node, + close: null, + groups: [], + type: "paren_group" + }; + parenGroupStack.push(parenGroup); + + commaGroup = { + groups: [], + type: "comma_group" + }; + commaGroupStack.push(commaGroup); + } else if (node.type === "paren" && node.value === ")") { + if (commaGroup.groups.length) { + parenGroup.groups.push(commaGroup); + } + parenGroup.close = node; + + if (commaGroupStack.length === 1) { + throw new Error("Unbalanced parenthesis"); + } + + commaGroupStack.pop(); + commaGroup = commaGroupStack[commaGroupStack.length - 1]; + commaGroup.groups.push(parenGroup); + + parenGroupStack.pop(); + parenGroup = parenGroupStack[parenGroupStack.length - 1]; + } else if (node.type === "comma") { + parenGroup.groups.push(commaGroup); + commaGroup = { + groups: [], + type: "comma_group" + }; + commaGroupStack[commaGroupStack.length - 1] = commaGroup; + } else { + commaGroup.groups.push(node); + } + } + if (commaGroup.groups.length > 0) { + parenGroup.groups.push(commaGroup); + } + return rootParenGroup; +} + +function flattenGroups(node) { + if ( + node.type === "paren_group" && + !node.open && + !node.close && + node.groups.length === 1 + ) { + return flattenGroups(node.groups[0]); + } + + if (node.type === "comma_group" && node.groups.length === 1) { + return flattenGroups(node.groups[0]); + } + + if (node.type === "paren_group" || node.type === "comma_group") { + return Object.assign({}, node, { groups: node.groups.map(flattenGroups) }); + } + + return node; +} + +function addTypePrefix(node, prefix) { + if (node && typeof node === "object") { + delete node.parent; + for (const key in node) { + addTypePrefix(node[key], prefix); + if (key === "type" && typeof node[key] === "string") { + if (!node[key].startsWith(prefix)) { + node[key] = prefix + node[key]; + } + } + } + } + return node; +} + +function addMissingType(node) { + if (node && typeof node === "object") { + delete node.parent; + for (const key in node) { + addMissingType(node[key]); + } + if (!Array.isArray(node) && node.value && !node.type) { + node.type = "unknown"; + } + } + return node; +} + +function parseNestedValue(node) { + if (node && typeof node === "object") { + delete node.parent; + for (const key in node) { + parseNestedValue(node[key]); + if (key === "nodes") { + node.group = flattenGroups(parseValueNodes(node[key])); + delete node[key]; + } + } + } + return node; +} + +function parseValue(value) { + const valueParser = __webpack_require__(85); + const result = valueParser(value, { loose: true }).parse(); + const parsedResult = parseNestedValue(result); + return addTypePrefix(parsedResult, "value-"); +} + +function parseMediaQuery(value) { + const mediaParser = __webpack_require__(82).default; + const result = addMissingType(mediaParser(value)); + return addTypePrefix(result, "media-"); +} + +function parseNestedCSS(node) { + if (node && typeof node === "object") { + delete node.parent; + for (const key in node) { + parseNestedCSS(node[key]); + } + if (typeof node.selector === "string") { + const selector = node.raws.selector + ? node.raws.selector.raw + : node.selector; + + try { + node.selector = parseSelector(selector); + } catch (e) { + // Fail silently. It's better to print it as is than to try and parse it + node.selector = selector; + } + } + if (node.type && typeof node.value === "string") { + try { + node.value = parseValue(node.value); + } catch (e) { + throw createError( + "(postcss-values-parser) " + e.toString(), + node.source + ); + } + } + if (node.type === "css-atrule" && typeof node.params === "string") { + node.params = parseMediaQuery(node.params); + } + } + return node; +} + +function parseWithParser(parser, text) { + let result; + try { + result = parser.parse(text); + } catch (e) { + if (typeof e.line !== "number") { + throw e; + } + throw createError("(postcss) " + e.name + " " + e.reason, { start: e }); + } + const prefixedResult = addTypePrefix(result, "css-"); + const parsedResult = parseNestedCSS(prefixedResult); + return parsedResult; +} + +function requireParser(isSCSS) { + if (isSCSS) { + return __webpack_require__(83); + } + return __webpack_require__(81); +} + +function parse(text) { + const isLikelySCSS = !!text.match(/(\w\s*: [^}:]+|#){|\@import url/); + try { + return parseWithParser(requireParser(isLikelySCSS), text); + } catch (e) { + try { + return parseWithParser(requireParser(!isLikelySCSS), text); + } catch (e2) { + throw e; + } + } +} + +module.exports = parse; /***/ }), diff --git a/docs/parser-typescript.js b/docs/parser-typescript.js index bf4782c0a..fe916377c 100644 --- a/docs/parser-typescript.js +++ b/docs/parser-typescript.js @@ -232,9 +232,9 @@ var process = { uptime: uptime }; -var __dirname = '/Users/vjeux/random/prettier/dist/src'; +var __dirname = '/Users/vjeux/random/prettier/dist'; -var __filename = '/Users/vjeux/random/prettier/dist/src/parser-typescript.js'; +var __filename = '/Users/vjeux/random/prettier/dist/parser-typescript.js'; var browser$1 = true; diff --git a/index.js b/index.js index e95465356..7e9a996fb 100644 --- a/index.js +++ b/index.js @@ -6,7 +6,7 @@ const printAstToDoc = require("./src/printer").printAstToDoc; const util = require("./src/util"); const printDocToString = require("./src/doc-printer").printDocToString; const normalizeOptions = require("./src/options").normalize; -const parser = require("./parser"); +const parser = require("./src/parser"); const printDocToDebug = require("./src/doc-debug").printDocToDebug; function guessLineEnding(text) { diff --git a/package.json b/package.json index a892a63f1..06639f52d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "prettier", - "version": "1.4.2", + "version": "1.4.3", "description": "Prettier is an opinionated JavaScript formatter", "bin": { "prettier": "./bin/prettier.js" diff --git a/scripts/build/build.sh b/scripts/build/build.sh index ba169cebe..f752f39f9 100755 --- a/scripts/build/build.sh +++ b/scripts/build/build.sh @@ -29,11 +29,11 @@ node_modules/.bin/rollup -c scripts/build/rollup.parser.config.js --environment echo 'Bundling lib postcss...'; # PostCSS has dependency cycles and won't work correctly with rollup :( -./node_modules/.bin/webpack src/parser-postcss.js dist/src/parser-postcss.js +./node_modules/.bin/webpack --hide-modules src/parser-postcss.js dist/parser-postcss.js # Prepend module.exports = -echo "module.exports =" > dist/src/parser-postcss.js.tmp -cat dist/src/parser-postcss.js >> dist/src/parser-postcss.js.tmp -mv dist/src/parser-postcss.js.tmp dist/src/parser-postcss.js +echo "module.exports =" > dist/parser-postcss.js.tmp +cat dist/parser-postcss.js >> dist/parser-postcss.js.tmp +mv dist/parser-postcss.js.tmp dist/parser-postcss.js echo; @@ -44,20 +44,20 @@ cp dist/index.js docs/index.js node_modules/babel-cli/bin/babel.js dist/index.js --out-file docs/index.js --presets=es2015 echo 'Bundling docs babylon...'; -node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:src/parser-babylon.js +node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:parser-babylon.js node_modules/babel-cli/bin/babel.js docs/parser-babylon.js --out-file docs/parser-babylon.js --presets=es2015 echo 'Bundling docs flow...'; -node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:src/parser-flow.js +node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:parser-flow.js echo 'Bundling docs graphql...'; -node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:src/parser-graphql.js +node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:parser-graphql.js echo 'Bundling docs typescript...'; -node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:src/parser-typescript.js +node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:parser-typescript.js echo 'Bundling docs postcss...'; -node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:src/parser-postcss.js +node_modules/.bin/rollup -c scripts/build/rollup.docs.config.js --environment filepath:parser-postcss.js echo; @@ -68,3 +68,15 @@ sed -i '' -e 's/eval("require")/require/g' dist/index.js dist/bin/prettier.js echo 'Copy package.json' cp package.json dist/ + +echo 'Done!' +echo; +echo 'How to test against dist:' +echo ' 1) Open tests_config/run_spec.js' +echo ' 2) add `dist/` to the require' +echo ' 3) yarn test' +echo " 4) Don't forget to revert tests_config/run_spec.js" +echo; +echo 'How to publish:' +echo ' 1) IMPORTANT!!! Go to dist/' +echo ' 2) npm publish' diff --git a/scripts/build/rollup.parser.config.js b/scripts/build/rollup.parser.config.js index 0f9e84399..0f1999d52 100644 --- a/scripts/build/rollup.parser.config.js +++ b/scripts/build/rollup.parser.config.js @@ -9,7 +9,7 @@ const parser = process.env.parser; export default Object.assign(baseConfig, { entry: 'src/parser-' + parser + '.js', - dest: 'dist/src/parser-' + parser + '.js', + dest: 'dist/parser-' + parser + '.js', format: 'cjs', plugins: [ parser === 'typescript' diff --git a/parser.js b/src/parser.js similarity index 67% rename from parser.js rename to src/parser.js index 50a66dd92..c1789b410 100644 --- a/parser.js +++ b/src/parser.js @@ -4,15 +4,15 @@ function parse(text, opts) { let parseFunction; if (opts.parser === "flow") { - parseFunction = eval("require")("./src/parser-flow"); + parseFunction = eval("require")("./parser-flow"); } else if (opts.parser === "graphql") { - parseFunction = eval("require")("./src/parser-graphql"); + parseFunction = eval("require")("./parser-graphql"); } else if (opts.parser === "typescript") { - parseFunction = eval("require")("./src/parser-typescript"); + parseFunction = eval("require")("./parser-typescript"); } else if (opts.parser === "postcss") { - parseFunction = eval("require")("./src/parser-postcss"); + parseFunction = eval("require")("./parser-postcss"); } else { - parseFunction = eval("require")("./src/parser-babylon"); + parseFunction = eval("require")("./parser-babylon"); } try { diff --git a/tests_config/run_spec.js b/tests_config/run_spec.js index ab3f68958..72578dae0 100644 --- a/tests_config/run_spec.js +++ b/tests_config/run_spec.js @@ -3,7 +3,7 @@ const fs = require("fs"); const extname = require("path").extname; const prettier = require("../"); // change to ../dist/ to "test in prod" -const parser = require("../parser"); +const parser = require("../src/parser"); const massageAST = require("../src/clean-ast.js").massageAST; const AST_COMPARE = process.env["AST_COMPARE"];