added nvim coc config files minus node modules

This commit is contained in:
tomit4 2021-09-25 02:14:00 -07:00
parent baac0fdd4f
commit fc51cf5a4a
19405 changed files with 6211125 additions and 0 deletions

View file

@ -0,0 +1,41 @@
## 0.16.0
* added support for PostCSS 5.2+
* fixes output adding superfluous spaces in comments
### PLEASE NOTE
This will be the last version of PostCSS-LESS supporting Node 4.x.
## 0.15.0
* reversed parsing of semicolon after mixin without body fix
* added [shrinkwrap](https://docs.npmjs.com/cli/shrinkwrap) file
## 0.14.0
* fixed parsing of semicolon after mixin without body
## 0.13.0
* set the default stringifier for Rule
## 0.3.0
* Merged in webschik's changes
* cleanup of various files (license, readme, gulp file)
* added a number of new tests to capture integration failures
* resolved remaining integration failures
* further linting cleanup (eslint strict)
## 0.2.0
* Cleanup of source and build files (eslint standards)
* fixing issue with @ inside of a string in parens
* new dist folder for npm with minified source files
## 0.1.3
* Fix ES2015 module export.
## 0.1.2
* Fix interpolation inside string.
## 0.1.1
* Fix `url()` parsing.
## 0.1
* Initial release.

View file

@ -0,0 +1,24 @@
The MIT License (MIT)
Copyright (c) 2013 Andrey Sitnik <andrey@sitnik.ru>
Copyright (c) 2016 Denys Kniazevych <webschik@gmail.com>
Copyright (c) 2016 Pat Sissons <patricksissons@gmail.com>
Copyright (c) 2017 Andrew Powell <andrew@shellscape.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,248 @@
[PostCSS]: https://github.com/postcss/postcss
[PostCSS-SCSS]: https://github.com/postcss/postcss-scss
[LESS]: http://lesless.org
[Autoprefixer]: https://github.com/postcss/autoprefixer
[Stylelint]: http://stylelint.io/
# PostCSS LESS Syntax [![Build Status](https://img.shields.io/travis/shellscape/postcss-less.svg?branch=develop)](https://travis-ci.org/shellscape/postcss-less) [![npm Version](https://img.shields.io/npm/v/postcss-less.svg)](https://www.npmjs.com/package/postcss-less)
[PostCSS] Syntax for parsing [LESS]
<img align="right" width="95" height="95"
title="Philosopher's stone, logo of PostCSS"
src="http://postcss.github.io/postcss/logo.svg">
Please note: poscss-less is not a LESS compiler. For compiling LESS, please use
the official toolset for LESS.
## Getting Started
First thing's first, install the module:
```
npm install postcss-less --save-dev
```
## LESS Transformations
The most common use of `postcss-less` is for applying PostCSS transformations
directly to LESS source. eg. ia theme written in LESS which uses [Autoprefixer]
to add appropriate vendor prefixes.
```js
const syntax = require('postcss-less');
postcss(plugins)
.process(lessText, { syntax: syntax })
.then(function (result) {
result.content // LESS with transformations
});
```
## Inline Comments
Parsing of single-line comments in CSS is also supported.
```less
:root {
// Main theme color
--color: red;
}
```
Note that you don't need a custom stringifier to handle the output; the default
stringifier will automatically convert single line comments into block comments.
If you need to support inline comments, please use a [custom PostCSSLess stringifier](#stringifier).
## Rule Node
[PostCSS Rule Node](https://github.com/postcss/postcss/blob/master/docs/api.md#rule-node)
### rule.empty
Determines whether or not a rule contains declarations.
_Note: Previously `ruleWithoutBody`. This is a breaking change from v0.16.0 to v1.0.0._
```js
import postCssLess from 'postcss-less';
const less = `
.class2 {
&:extend(.class1);
.mixin-name(@param1, @param2);
}
`;
const root = postCssLess.parse(less);
root.first.nodes[0].empty // => true for &:extend
root.first.nodes[1].empty // => true for calling of mixin
```
### rule.extend
Determines whether or not a rule is [nested](http://lesscss.org/features/#extend-feature-extend-inside-ruleset).
_Note: Previously `extendRule`. This is a breaking change from v0.16.0 to v1.0.0._
```js
import postCssLess from 'postcss-less';
const less = `
.class2 {
&:extend(.class1);
}
`;
const root = postCssLess.parse(less);
root.first.nodes[0].extend // => true
```
### rule.important
Determines whether or not a rule is marked as [important](http://lesscss.org/features/#mixins-feature-the-important-keyword).
_Note: This is a breaking change from v0.16.0 to v1.0.0._
```js
import postCssLess from 'postcss-less';
const less = `
.class {
.mixin !important;
}
`;
const root = postCssLess.parse(less);
root.first.nodes[0].important // => true
root.first.nodes[0].selector // => '.mixin'
```
### rule.mixin
Determines whether or not a rule is a [mixin](http://lesscss.org/features/#mixins-feature).
```js
import postCssLess from 'postcss-less';
const less = `
.class2 {
.mixin-name;
}
`;
const root = postCssLess.parse(less);
root.first.nodes[0].mixin // => true
```
### rule.nodes
An `Array` of child nodes.
**Note** that `nodes` is `undefined` for rules that don't contain declarations.
```js
import postCssLess from 'postcss-less';
const less = `
.class2 {
&:extend(.class1);
.mixin-name(@param1, @param2);
}
`;
const root = postCssLess.parse(less);
root.first.nodes[0].nodes // => undefined for &:extend
root.first.nodes[1].nodes // => undefined for mixin
```
## Comment Node
[PostCSS Comment Node](https://github.com/postcss/postcss/blob/master/docs/api.md#comment-node)
### comment.inline
Determines whether or not a comment is inline.
```js
import postCssLess from 'postcss-less';
const root = postCssLess.parse('// Hello world');
root.first.inline // => true
```
### comment.block
Determines whether or not a comment is a block comment.
```js
import postCssLess from 'postcss-less';
const root = postCssLess.parse('/* Hello world */');
root.first.block // => true
```
### comment.raws.begin
Precending characters of a comment node. eg. `//` or `/*`.
### comment.raws.content
Raw content of the comment.
```js
import postCssLess from 'postcss-less';
const root = postCssLess.parse('// Hello world');
root.first.raws.content // => '// Hello world'
```
## Stringifying
To process LESS code without PostCSS transformations, custom stringifier
should be provided.
```js
import postcss from 'postcss';
import postcssLess from 'postcss-less';
import stringify from 'postcss-less/less-stringify';
const lessCode = `
// Non-css comment
.container {
.mixin-1();
.mixin-2;
.mixin-3 (@width: 100px) {
width: @width;
}
}
.rotation(@deg:5deg){
.transform(rotate(@deg));
}
`;
postcss()
.process(less, {
syntax: postcssLess,
stringifier: stringify
})
.then((result) => {
console.log(result.content); // this will be value of `lessCode` without changing comments or mixins
});
```
## Use Cases
* Lint LESS code with 3rd-party plugins.
* Apply PostCSS transformations (such as [Autoprefixer](https://github.com/postcss/autoprefixer)) directly to the LESS source code
## Contribution
Please, check our guidelines: [CONTRIBUTING.md](./CONTRIBUTING.md)
## Attribution
This module is based on the [postcss-scss](https://github.com/postcss/postcss-scss) library.
[![npm Downloads](https://img.shields.io/npm/dt/postcss-less.svg)](https://www.npmjs.com/package/postcss-less)
[![npm License](https://img.shields.io/npm/l/postcss-less.svg)](https://www.npmjs.com/package/postcss-less)
[![js-strict-standard-style](https://img.shields.io/badge/code%20style-strict-117D6B.svg)](https://github.com/keithamus/eslint-config-strict)

View file

@ -0,0 +1,37 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = findExtendRule;
var extendRuleKeyWords = ['&', ':', 'extend'];
var extendRuleKeyWordsCount = extendRuleKeyWords.length;
function findExtendRule(tokens) {
var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var stack = [];
var len = tokens.length;
var end = start;
while (end < len) {
var token = tokens[end];
if (extendRuleKeyWords.indexOf(token[1]) >= 0) {
stack.push(token[1]);
} else if (token[0] !== 'space') {
break;
}
end++;
}
for (var index = 0; index < extendRuleKeyWordsCount; index++) {
if (stack[index] !== extendRuleKeyWords[index]) {
return null;
}
}
return tokens.slice(start, end);
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function findExtendRule(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,d=[],r=e.length,n=t;n<r;){var u=e[n];if(extendRuleKeyWords.indexOf(u[1])>=0)d.push(u[1]);else if("space"!==u[0])break;n++}for(var l=0;l<extendRuleKeyWordsCount;l++)if(d[l]!==extendRuleKeyWords[l])return null;return e.slice(t,n)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=findExtendRule;var extendRuleKeyWords=["&",":","extend"],extendRuleKeyWordsCount=extendRuleKeyWords.length;module.exports=exports.default;

View file

@ -0,0 +1,56 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _rule = require('postcss/lib/rule');
var _rule2 = _interopRequireDefault(_rule);
var _lessStringify = require('./less-stringify');
var _lessStringify2 = _interopRequireDefault(_lessStringify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Import = function (_PostCssRule) {
_inherits(Import, _PostCssRule);
function Import(defaults) {
_classCallCheck(this, Import);
var _this = _possibleConstructorReturn(this, (Import.__proto__ || Object.getPrototypeOf(Import)).call(this, defaults));
_this.type = 'import';
return _this;
}
_createClass(Import, [{
key: 'toString',
value: function toString(stringifier) {
if (!stringifier) {
stringifier = {
stringify: _lessStringify2.default
};
}
return _get(Import.prototype.__proto__ || Object.getPrototypeOf(Import.prototype), 'toString', this).call(this, stringifier);
}
}]);
return Import;
}(_rule2.default);
exports.default = Import;
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),_get=function e(t,r,o){null===t&&(t=Function.prototype);var n=Object.getOwnPropertyDescriptor(t,r);if(void 0===n){var i=Object.getPrototypeOf(t);return null===i?void 0:e(i,r,o)}if("value"in n)return n.value;var u=n.get;if(void 0!==u)return u.call(o)},_rule=require("postcss/lib/rule"),_rule2=_interopRequireDefault(_rule),_lessStringify=require("./less-stringify"),_lessStringify2=_interopRequireDefault(_lessStringify),Import=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.type="import",r}return _inherits(t,e),_createClass(t,[{key:"toString",value:function(e){return e||(e={stringify:_lessStringify2.default}),_get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"toString",this).call(this,e)}}]),t}(_rule2.default);exports.default=Import,module.exports=exports.default;

View file

@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMixinToken;
var _globals = require('./tokenizer/globals');
var unpaddedFractionalNumbersPattern = /\.[0-9]/;
function isMixinToken(token) {
var symbol = token[1];
var firstSymbolCode = symbol ? symbol[0].charCodeAt(0) : null;
return (firstSymbolCode === _globals.dot || firstSymbolCode === _globals.hash) &&
// ignore hashes used for colors
_globals.hashColorPattern.test(symbol) === false &&
// ignore dots used for unpadded fractional numbers
unpaddedFractionalNumbersPattern.test(symbol) === false;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function isMixinToken(e){var t=e[1],r=t?t[0].charCodeAt(0):null;return(r===_globals.dot||r===_globals.hash)&&!1===_globals.hashColorPattern.test(t)&&!1===unpaddedFractionalNumbersPattern.test(t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=isMixinToken;var _globals=require("./tokenizer/globals"),unpaddedFractionalNumbersPattern=/\.[0-9]/;module.exports=exports.default;

View file

@ -0,0 +1,30 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = lessParse;
var _input = require('postcss/lib/input');
var _input2 = _interopRequireDefault(_input);
var _lessParser = require('./less-parser');
var _lessParser2 = _interopRequireDefault(_lessParser);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function lessParse(less, opts) {
var input = new _input2.default(less, opts);
var parser = new _lessParser2.default(input, opts);
// const parser = new Parser(input, opts);
parser.tokenize();
parser.loop();
return parser.root;
}
// import Parser from 'postcss/lib/parser';
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function lessParse(e,r){var s=new _input2.default(e,r),t=new _lessParser2.default(s,r);return t.tokenize(),t.loop(),t.root}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=lessParse;var _input=require("postcss/lib/input"),_input2=_interopRequireDefault(_input),_lessParser=require("./less-parser"),_lessParser2=_interopRequireDefault(_lessParser);module.exports=exports.default;

View file

@ -0,0 +1,464 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _comment = require('postcss/lib/comment');
var _comment2 = _interopRequireDefault(_comment);
var _import2 = require('./import');
var _import3 = _interopRequireDefault(_import2);
var _parser = require('postcss/lib/parser');
var _parser2 = _interopRequireDefault(_parser);
var _rule = require('./rule');
var _rule2 = _interopRequireDefault(_rule);
var _root = require('./root');
var _root2 = _interopRequireDefault(_root);
var _findExtendRule = require('./find-extend-rule');
var _findExtendRule2 = _interopRequireDefault(_findExtendRule);
var _isMixinToken = require('./is-mixin-token');
var _isMixinToken2 = _interopRequireDefault(_isMixinToken);
var _lessTokenize = require('./less-tokenize');
var _lessTokenize2 = _interopRequireDefault(_lessTokenize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var blockCommentEndPattern = /\*\/$/;
var LessParser = function (_Parser) {
_inherits(LessParser, _Parser);
function LessParser(input) {
_classCallCheck(this, LessParser);
var _this = _possibleConstructorReturn(this, (LessParser.__proto__ || Object.getPrototypeOf(LessParser)).call(this, input));
_this.root = new _root2.default();
_this.current = _this.root;
_this.root.source = { input: input, start: { line: 1, column: 1 } };
return _this;
}
_createClass(LessParser, [{
key: 'atrule',
value: function atrule(token) {
if (token[1] === '@import') {
this.import(token);
} else {
_get(LessParser.prototype.__proto__ || Object.getPrototypeOf(LessParser.prototype), 'atrule', this).call(this, token);
}
}
}, {
key: 'comment',
value: function comment(token) {
var node = new _comment2.default();
var content = token[1];
var text = content.slice(2).replace(blockCommentEndPattern, '');
this.init(node, token[2], token[3]);
node.source.end = {
line: token[4],
column: token[5]
};
node.raws.content = content;
node.raws.begin = content[0] + content[1];
node.inline = token[6] === 'inline';
node.block = !node.inline;
if (/^\s*$/.test(text)) {
node.text = '';
node.raws.left = text;
node.raws.right = '';
} else {
var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
node.text = match[2];
// Add extra spaces to generate a comment in a common style /*[space][text][space]*/
node.raws.left = match[1] || ' ';
node.raws.right = match[3] || ' ';
}
}
/**
* @description Create a Declaration
* @param options {{start: number}}
*/
}, {
key: 'createDeclaration',
value: function createDeclaration(options) {
this.decl(this.tokens.slice(options.start, this.pos + 1));
}
/**
* @description Create a Rule node
* @param options {{start: number, params: Array}}
*/
}, {
key: 'createRule',
value: function createRule(options) {
var semi = this.tokens[this.pos][0] === ';';
var end = this.pos + (options.empty && semi ? 2 : 1);
var tokens = this.tokens.slice(options.start, end);
var node = this.rule(tokens);
/**
* By default in PostCSS `Rule.params` is `undefined`.
* To preserve compability with PostCSS:
* - Don't set empty params for a Rule.
* - Set params for a Rule only if it can be a mixin or &:extend rule.
*/
if (options.params[0] && (options.mixin || options.extend)) {
this.raw(node, 'params', options.params);
}
if (options.empty) {
// if it's an empty mixin or extend, it must have a semicolon
// (that's the only way we get to this point)
if (semi) {
node.raws.semicolon = this.semicolon = true;
node.selector = node.selector.replace(/;$/, '');
}
if (options.extend) {
node.extend = true;
}
if (options.mixin) {
node.mixin = true;
}
/**
* @description Mark mixin without declarations.
* @type {boolean}
*/
node.empty = true;
// eslint-disable-next-line
delete this.current.nodes;
if (/!\s*important/i.test(node.selector)) {
node.important = true;
if (/\s*!\s*important/i.test(node.selector)) {
node.raws.important = node.selector.match(/(\s*!\s*important)/i)[1];
}
node.selector = node.selector.replace(/\s*!\s*important/i, '');
}
// rules don't have trailing semicolons in vanilla css, so they get
// added to this.spaces by the parser loop, so don't step back.
if (!semi) {
this.pos--;
}
this.end(this.tokens[this.pos]);
}
}
}, {
key: 'end',
value: function end(token) {
var node = this.current;
// if a Rule contains other Rules (mixins, extends) and those have
// semicolons, assert that the parent Rule has a semicolon
if (node.nodes && node.nodes.length && node.last.raws.semicolon && !node.last.nodes) {
this.semicolon = true;
}
_get(LessParser.prototype.__proto__ || Object.getPrototypeOf(LessParser.prototype), 'end', this).call(this, token);
}
}, {
key: 'import',
value: function _import(token) {
/* eslint complexity: 0 */
var last = false,
open = false,
end = { line: 0, column: 0 };
var directives = [];
var node = new _import3.default();
node.name = token[1].slice(1);
this.init(node, token[2], token[3]);
this.pos += 1;
while (this.pos < this.tokens.length) {
var tokn = this.tokens[this.pos];
if (tokn[0] === ';') {
end = { line: tokn[2], column: tokn[3] };
node.raws.semicolon = true;
break;
} else if (tokn[0] === '{') {
open = true;
break;
} else if (tokn[0] === '}') {
this.end(tokn);
break;
} else if (tokn[0] === 'brackets') {
if (node.urlFunc) {
node.importPath = tokn[1].replace(/[()]/g, '');
} else {
directives.push(tokn);
}
} else if (tokn[0] === 'space') {
if (directives.length) {
node.raws.between = tokn[1];
} else if (node.urlFunc) {
node.raws.beforeUrl = tokn[1];
} else if (node.importPath) {
if (node.urlFunc) {
node.raws.afterUrl = tokn[1];
} else {
node.raws.after = tokn[1];
}
} else {
node.raws.afterName = tokn[1];
}
} else if (tokn[0] === 'word' && tokn[1] === 'url') {
node.urlFunc = true;
} else {
if (tokn[0] !== '(' && tokn[0] !== ')') {
node.importPath = tokn[1];
}
}
if (this.pos === this.tokens.length) {
last = true;
break;
}
this.pos += 1;
}
if (node.raws.between && !node.raws.afterName) {
node.raws.afterName = node.raws.between;
node.raws.between = '';
}
node.source.end = end;
if (directives.length) {
this.raw(node, 'directives', directives);
if (last) {
token = directives[directives.length - 1];
node.source.end = { line: token[4], column: token[5] };
this.spaces = node.raws.between;
node.raws.between = '';
}
} else {
node.directives = '';
}
if (open) {
node.nodes = [];
this.current = node;
}
}
/* eslint-disable max-statements, complexity */
}, {
key: 'other',
value: function other() {
var brackets = [];
var params = [];
var start = this.pos;
var end = false,
colon = false,
bracket = null;
// we need pass "()" as spaces
// However we can override method Parser.loop, but it seems less maintainable
if (this.tokens[start][0] === 'brackets') {
this.spaces += this.tokens[start][1];
return;
}
var mixin = (0, _isMixinToken2.default)(this.tokens[start]);
var extend = Boolean((0, _findExtendRule2.default)(this.tokens, start));
while (this.pos < this.tokens.length) {
var token = this.tokens[this.pos];
var type = token[0];
if (type === '(' || type === '[') {
if (!bracket) {
bracket = token;
}
brackets.push(type === '(' ? ')' : ']');
} else if (brackets.length === 0) {
if (type === ';') {
var foundEndOfRule = this.ruleEnd({
start: start,
params: params,
colon: colon,
mixin: mixin,
extend: extend
});
if (foundEndOfRule) {
return;
}
break;
} else if (type === '{') {
this.createRule({ start: start, params: params, mixin: mixin });
return;
} else if (type === '}') {
this.pos -= 1;
end = true;
break;
} else if (type === ':') {
colon = true;
}
} else if (type === brackets[brackets.length - 1]) {
brackets.pop();
if (brackets.length === 0) {
bracket = null;
}
}
// we don't want to add params for pseudo-selectors that utilize parens (#56)
// if ((extend || !colon) && (brackets.length > 0 || type === 'brackets' || params[0])) {
// params.push(token);
// }
// we don't want to add params for pseudo-selectors that utilize parens (#56) or bracket selectors (#96)
if ((extend || !colon) && (brackets.length > 0 || type === 'brackets' || params[0]) && brackets[0] !== ']') {
params.push(token);
}
this.pos += 1;
}
if (this.pos === this.tokens.length) {
this.pos -= 1;
end = true;
}
if (brackets.length > 0) {
this.unclosedBracket(bracket);
}
// dont process an end of rule if there's only one token and it's unknown (#64)
if (end && this.tokens.length > 1) {
// Handle the case where the there is only a single token in the end rule.
if (start === this.pos) {
this.pos += 1;
}
var _foundEndOfRule = this.ruleEnd({
start: start,
params: params,
colon: colon,
mixin: mixin,
extend: extend,
isEndOfBlock: true
});
if (_foundEndOfRule) {
return;
}
}
this.unknownWord(start);
}
}, {
key: 'rule',
value: function rule(tokens) {
tokens.pop();
var node = new _rule2.default();
this.init(node, tokens[0][2], tokens[0][3]);
//node.raws.between = this.spacesFromEnd(tokens);
node.raws.between = this.spacesAndCommentsFromEnd(tokens);
this.raw(node, 'selector', tokens);
this.current = node;
return node;
}
}, {
key: 'ruleEnd',
value: function ruleEnd(options) {
var start = options.start;
if (options.extend || options.mixin) {
this.createRule(Object.assign(options, { empty: true }));
return true;
}
if (options.colon) {
if (options.isEndOfBlock) {
while (this.pos > start) {
var token = this.tokens[this.pos][0];
if (token !== 'space' && token !== 'comment') {
break;
}
this.pos -= 1;
}
}
this.createDeclaration({ start: start });
return true;
}
return false;
}
}, {
key: 'tokenize',
value: function tokenize() {
this.tokens = (0, _lessTokenize2.default)(this.input);
}
/* eslint-enable max-statements, complexity */
}]);
return LessParser;
}(_parser2.default);
exports.default = LessParser;
module.exports = exports['default'];

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,101 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _stringifier = require('postcss/lib/stringifier');
var _stringifier2 = _interopRequireDefault(_stringifier);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var LessStringifier = function (_Stringifier) {
_inherits(LessStringifier, _Stringifier);
function LessStringifier() {
_classCallCheck(this, LessStringifier);
return _possibleConstructorReturn(this, (LessStringifier.__proto__ || Object.getPrototypeOf(LessStringifier)).apply(this, arguments));
}
_createClass(LessStringifier, [{
key: 'comment',
value: function comment(node) {
this.builder(node.raws.content, node);
}
}, {
key: 'import',
value: function _import(node) {
this.builder('@' + node.name);
this.builder((node.raws.afterName || '') + (node.directives || '') + (node.raws.between || '') + (node.urlFunc ? 'url(' : '') + (node.raws.beforeUrl || '') + (node.importPath || '') + (node.raws.afterUrl || '') + (node.urlFunc ? ')' : '') + (node.raws.after || ''));
if (node.raws.semicolon) {
this.builder(';');
}
}
}, {
key: 'rule',
value: function rule(node) {
_get(LessStringifier.prototype.__proto__ || Object.getPrototypeOf(LessStringifier.prototype), 'rule', this).call(this, node);
if (node.empty && node.raws.semicolon) {
if (node.important) {
if (node.raws.important) {
this.builder(node.raws.important);
} else {
this.builder(' !important');
}
}
if (node.raws.semicolon) {
this.builder(';');
}
}
}
}, {
key: 'block',
value: function block(node, start) {
var empty = node.empty;
var between = this.raw(node, 'between', 'beforeOpen');
var after = '';
if (empty) {
this.builder(start + between, node, 'start');
} else {
this.builder(start + between + '{', node, 'start');
}
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, 'after');
} else {
after = this.raw(node, 'after', 'emptyBody');
}
if (after) {
this.builder(after);
}
if (!empty) {
this.builder('}', node, 'end');
}
}
}]);
return LessStringifier;
}(_stringifier2.default);
exports.default = LessStringifier;
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),_get=function e(t,r,i){null===t&&(t=Function.prototype);var n=Object.getOwnPropertyDescriptor(t,r);if(void 0===n){var o=Object.getPrototypeOf(t);return null===o?void 0:e(o,r,i)}if("value"in n)return n.value;var s=n.get;if(void 0!==s)return s.call(i)},_stringifier=require("postcss/lib/stringifier"),_stringifier2=_interopRequireDefault(_stringifier),LessStringifier=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"comment",value:function(e){this.builder(e.raws.content,e)}},{key:"import",value:function(e){this.builder("@"+e.name),this.builder((e.raws.afterName||"")+(e.directives||"")+(e.raws.between||"")+(e.urlFunc?"url(":"")+(e.raws.beforeUrl||"")+(e.importPath||"")+(e.raws.afterUrl||"")+(e.urlFunc?")":"")+(e.raws.after||"")),e.raws.semicolon&&this.builder(";")}},{key:"rule",value:function(e){_get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"rule",this).call(this,e),e.empty&&e.raws.semicolon&&(e.important&&(e.raws.important?this.builder(e.raws.important):this.builder(" !important")),e.raws.semicolon&&this.builder(";"))}},{key:"block",value:function(e,t){var r=e.empty,i=this.raw(e,"between","beforeOpen"),n="";r?this.builder(t+i,e,"start"):this.builder(t+i+"{",e,"start"),e.nodes&&e.nodes.length?(this.body(e),n=this.raw(e,"after")):n=this.raw(e,"after","emptyBody"),n&&this.builder(n),r||this.builder("}",e,"end")}}]),t}(_stringifier2.default);exports.default=LessStringifier,module.exports=exports.default;

View file

@ -0,0 +1,19 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = lessStringify;
var _lessStringifier = require('./less-stringifier');
var _lessStringifier2 = _interopRequireDefault(_lessStringifier);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function lessStringify(node, builder) {
var str = new _lessStringifier2.default(builder);
str.stringify(node);
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function lessStringify(e,i){new _lessStringifier2.default(i).stringify(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=lessStringify;var _lessStringifier=require("./less-stringifier"),_lessStringifier2=_interopRequireDefault(_lessStringifier);module.exports=exports.default;

View file

@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _lessParse = require('./less-parse');
var _lessParse2 = _interopRequireDefault(_lessParse);
var _lessStringify = require('./less-stringify');
var _lessStringify2 = _interopRequireDefault(_lessStringify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = { parse: _lessParse2.default, stringify: _lessStringify2.default };
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0});var _lessParse=require("./less-parse"),_lessParse2=_interopRequireDefault(_lessParse),_lessStringify=require("./less-stringify"),_lessStringify2=_interopRequireDefault(_lessStringify);exports.default={parse:_lessParse2.default,stringify:_lessStringify2.default},module.exports=exports.default;

View file

@ -0,0 +1,54 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = lessTokenize;
var _globals = require('./tokenizer/globals');
var _tokenizeSymbol = require('./tokenizer/tokenize-symbol');
var _tokenizeSymbol2 = _interopRequireDefault(_tokenizeSymbol);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function lessTokenize(input) {
var state = {
input: input,
tokens: [],
css: input.css.valueOf(),
offset: -1,
line: 1,
pos: 0
};
state.length = state.css.length;
while (state.pos < state.length) {
state.symbolCode = state.css.charCodeAt(state.pos);
state.symbol = state.css[state.pos];
state.nextPos = null;
state.escaped = null;
state.lines = null;
state.lastLine = null;
state.cssPart = null;
state.escape = null;
state.nextLine = null;
state.nextOffset = null;
state.escapePos = null;
state.token = null;
if (state.symbolCode === _globals.newline) {
state.offset = state.pos;
state.line += 1;
}
(0, _tokenizeSymbol2.default)(state);
state.pos++;
}
return state.tokens;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function lessTokenize(e){var l={input:e,tokens:[],css:e.css.valueOf(),offset:-1,line:1,pos:0};for(l.length=l.css.length;l.pos<l.length;)l.symbolCode=l.css.charCodeAt(l.pos),l.symbol=l.css[l.pos],l.nextPos=null,l.escaped=null,l.lines=null,l.lastLine=null,l.cssPart=null,l.escape=null,l.nextLine=null,l.nextOffset=null,l.escapePos=null,l.token=null,l.symbolCode===_globals.newline&&(l.offset=l.pos,l.line+=1),(0,_tokenizeSymbol2.default)(l),l.pos++;return l.tokens}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=lessTokenize;var _globals=require("./tokenizer/globals"),_tokenizeSymbol=require("./tokenizer/tokenize-symbol"),_tokenizeSymbol2=_interopRequireDefault(_tokenizeSymbol);module.exports=exports.default;

View file

@ -0,0 +1,53 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _root = require('postcss/lib/root');
var _root2 = _interopRequireDefault(_root);
var _lessStringify = require('./less-stringify');
var _lessStringify2 = _interopRequireDefault(_lessStringify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Root = function (_PostCssRoot) {
_inherits(Root, _PostCssRoot);
function Root() {
_classCallCheck(this, Root);
return _possibleConstructorReturn(this, (Root.__proto__ || Object.getPrototypeOf(Root)).apply(this, arguments));
}
_createClass(Root, [{
key: 'toString',
value: function toString(stringifier) {
if (!stringifier) {
stringifier = {
stringify: _lessStringify2.default
};
}
return _get(Root.prototype.__proto__ || Object.getPrototypeOf(Root.prototype), 'toString', this).call(this, stringifier);
}
}]);
return Root;
}(_root2.default);
exports.default = Root;
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),_get=function e(t,r,o){null===t&&(t=Function.prototype);var n=Object.getOwnPropertyDescriptor(t,r);if(void 0===n){var i=Object.getPrototypeOf(t);return null===i?void 0:e(i,r,o)}if("value"in n)return n.value;var u=n.get;if(void 0!==u)return u.call(o)},_root=require("postcss/lib/root"),_root2=_interopRequireDefault(_root),_lessStringify=require("./less-stringify"),_lessStringify2=_interopRequireDefault(_lessStringify),Root=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"toString",value:function(e){return e||(e={stringify:_lessStringify2.default}),_get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"toString",this).call(this,e)}}]),t}(_root2.default);exports.default=Root,module.exports=exports.default;

View file

@ -0,0 +1,53 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _rule = require('postcss/lib/rule');
var _rule2 = _interopRequireDefault(_rule);
var _lessStringify = require('./less-stringify');
var _lessStringify2 = _interopRequireDefault(_lessStringify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Rule = function (_PostCssRule) {
_inherits(Rule, _PostCssRule);
function Rule() {
_classCallCheck(this, Rule);
return _possibleConstructorReturn(this, (Rule.__proto__ || Object.getPrototypeOf(Rule)).apply(this, arguments));
}
_createClass(Rule, [{
key: 'toString',
value: function toString(stringifier) {
if (!stringifier) {
stringifier = {
stringify: _lessStringify2.default
};
}
return _get(Rule.prototype.__proto__ || Object.getPrototypeOf(Rule.prototype), 'toString', this).call(this, stringifier);
}
}]);
return Rule;
}(_rule2.default);
exports.default = Rule;
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),_get=function e(t,r,o){null===t&&(t=Function.prototype);var n=Object.getOwnPropertyDescriptor(t,r);if(void 0===n){var i=Object.getPrototypeOf(t);return null===i?void 0:e(i,r,o)}if("value"in n)return n.value;var u=n.get;if(void 0!==u)return u.call(o)},_rule=require("postcss/lib/rule"),_rule2=_interopRequireDefault(_rule),_lessStringify=require("./less-stringify"),_lessStringify2=_interopRequireDefault(_lessStringify),Rule=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"toString",value:function(e){return e||(e={stringify:_lessStringify2.default}),_get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"toString",this).call(this,e)}}]),t}(_rule2.default);exports.default=Rule,module.exports=exports.default;

View file

@ -0,0 +1,38 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = findEndOfEscaping;
var _globals = require('./globals');
/**
* @param state
* @returns {number}
*/
function findEndOfEscaping(state) {
var openQuotesCount = 0,
quoteCode = -1;
for (var i = state.pos + 1; i < state.length; i++) {
var symbolCode = state.css.charCodeAt(i);
var prevSymbolCode = state.css.charCodeAt(i - 1);
if (prevSymbolCode !== _globals.backslash && (symbolCode === _globals.singleQuote || symbolCode === _globals.doubleQuote || symbolCode === _globals.backTick)) {
if (quoteCode === -1) {
quoteCode = symbolCode;
openQuotesCount++;
} else if (symbolCode === quoteCode) {
openQuotesCount--;
if (!openQuotesCount) {
return i;
}
}
}
}
return -1;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function findEndOfEscaping(e){for(var s=0,l=-1,o=e.pos+1;o<e.length;o++){var a=e.css.charCodeAt(o);if(e.css.charCodeAt(o-1)!==_globals.backslash&&(a===_globals.singleQuote||a===_globals.doubleQuote||a===_globals.backTick))if(-1===l)l=a,s++;else if(a===l&&!--s)return o}return-1}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=findEndOfEscaping;var _globals=require("./globals");module.exports=exports.default;

View file

@ -0,0 +1,46 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = findEndOfExpression;
var _globals = require('./globals');
function findEndOfExpression(css, length, i) {
var openedParenthesisBlocks = 0,
openedCurlyBlocks = 0;
for (; i < length; ++i) {
var symbolCode = css[i].charCodeAt(0);
// find the on of escaped expression
if (!openedParenthesisBlocks && !openedCurlyBlocks && (symbolCode === _globals.semicolon || symbolCode === _globals.closedCurlyBracket)) {
return i - 1;
}
switch (symbolCode) {
case _globals.openedCurlyBracket:
openedCurlyBlocks++;
break;
case _globals.closedCurlyBracket:
openedCurlyBlocks--;
break;
case _globals.openedParenthesis:
openedParenthesisBlocks++;
break;
case _globals.closedParenthesis:
openedParenthesisBlocks--;
break;
default:
break;
}
}
return -1;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function findEndOfExpression(e,s,r){for(var l=0,a=0;r<s;++r){var o=e[r].charCodeAt(0);if(!(l||a||o!==_globals.semicolon&&o!==_globals.closedCurlyBracket))return r-1;switch(o){case _globals.openedCurlyBracket:a++;break;case _globals.closedCurlyBracket:a--;break;case _globals.openedParenthesis:l++;break;case _globals.closedParenthesis:l--}}return-1}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=findEndOfExpression;var _globals=require("./globals");module.exports=exports.default;

View file

@ -0,0 +1,36 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var singleQuote = exports.singleQuote = '\''.charCodeAt(0);
var doubleQuote = exports.doubleQuote = '"'.charCodeAt(0);
var backslash = exports.backslash = '\\'.charCodeAt(0);
var backTick = exports.backTick = '`'.charCodeAt(0);
var slash = exports.slash = '/'.charCodeAt(0);
var newline = exports.newline = '\n'.charCodeAt(0);
var space = exports.space = ' '.charCodeAt(0);
var feed = exports.feed = '\f'.charCodeAt(0);
var tab = exports.tab = '\t'.charCodeAt(0);
var carriageReturn = exports.carriageReturn = '\r'.charCodeAt(0);
var openedParenthesis = exports.openedParenthesis = '('.charCodeAt(0);
var closedParenthesis = exports.closedParenthesis = ')'.charCodeAt(0);
var openedCurlyBracket = exports.openedCurlyBracket = '{'.charCodeAt(0);
var closedCurlyBracket = exports.closedCurlyBracket = '}'.charCodeAt(0);
var openSquareBracket = exports.openSquareBracket = '['.charCodeAt(0);
var closeSquareBracket = exports.closeSquareBracket = ']'.charCodeAt(0);
var semicolon = exports.semicolon = ';'.charCodeAt(0);
var asterisk = exports.asterisk = '*'.charCodeAt(0);
var colon = exports.colon = ':'.charCodeAt(0);
var comma = exports.comma = ','.charCodeAt(0);
var dot = exports.dot = '.'.charCodeAt(0);
var atRule = exports.atRule = '@'.charCodeAt(0);
var tilde = exports.tilde = '~'.charCodeAt(0);
var hash = exports.hash = '#'.charCodeAt(0);
var atEndPattern = exports.atEndPattern = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g;
var wordEndPattern = exports.wordEndPattern = /[ \n\t\r\f\(\)\{\}:,;@!'"\\\]\[#]|\/(?=\*)/g;
var badBracketPattern = exports.badBracketPattern = /.[\\\/\("'\n]/;
var variablePattern = exports.variablePattern = /^@[^:\(\{]+:/;
var hashColorPattern = exports.hashColorPattern = /^#[0-9a-fA-F]{6}$|^#[0-9a-fA-F]{3}$/;

View file

@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var singleQuote=exports.singleQuote="'".charCodeAt(0),doubleQuote=exports.doubleQuote='"'.charCodeAt(0),backslash=exports.backslash="\\".charCodeAt(0),backTick=exports.backTick="`".charCodeAt(0),slash=exports.slash="/".charCodeAt(0),newline=exports.newline="\n".charCodeAt(0),space=exports.space=" ".charCodeAt(0),feed=exports.feed="\f".charCodeAt(0),tab=exports.tab="\t".charCodeAt(0),carriageReturn=exports.carriageReturn="\r".charCodeAt(0),openedParenthesis=exports.openedParenthesis="(".charCodeAt(0),closedParenthesis=exports.closedParenthesis=")".charCodeAt(0),openedCurlyBracket=exports.openedCurlyBracket="{".charCodeAt(0),closedCurlyBracket=exports.closedCurlyBracket="}".charCodeAt(0),openSquareBracket=exports.openSquareBracket="[".charCodeAt(0),closeSquareBracket=exports.closeSquareBracket="]".charCodeAt(0),semicolon=exports.semicolon=";".charCodeAt(0),asterisk=exports.asterisk="*".charCodeAt(0),colon=exports.colon=":".charCodeAt(0),comma=exports.comma=",".charCodeAt(0),dot=exports.dot=".".charCodeAt(0),atRule=exports.atRule="@".charCodeAt(0),tilde=exports.tilde="~".charCodeAt(0),hash=exports.hash="#".charCodeAt(0),atEndPattern=exports.atEndPattern=/[ \n\t\r\f\{\(\)'"\\;\/\[\]#]/g,wordEndPattern=exports.wordEndPattern=/[ \n\t\r\f\(\)\{\}:,;@!'"\\\]\[#]|\/(?=\*)/g,badBracketPattern=exports.badBracketPattern=/.[\\\/\("'\n]/,variablePattern=exports.variablePattern=/^@[^:\(\{]+:/,hashColorPattern=exports.hashColorPattern=/^#[0-9a-fA-F]{6}$|^#[0-9a-fA-F]{3}$/;

View file

@ -0,0 +1,17 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isEscaping;
var _globals = require('./globals');
var nextSymbolVariants = [_globals.backTick, _globals.doubleQuote, _globals.singleQuote];
function isEscaping(state) {
var nextSymbolCode = state.css.charCodeAt(state.pos + 1);
return state.symbolCode === _globals.tilde && nextSymbolVariants.indexOf(nextSymbolCode) >= 0;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function isEscaping(e){var s=e.css.charCodeAt(e.pos+1);return e.symbolCode===_globals.tilde&&nextSymbolVariants.indexOf(s)>=0}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=isEscaping;var _globals=require("./globals"),nextSymbolVariants=[_globals.backTick,_globals.doubleQuote,_globals.singleQuote];module.exports=exports.default;

View file

@ -0,0 +1,73 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeAtRule;
var _globals = require('./globals');
var _unclosed = require('./unclosed');
var _unclosed2 = _interopRequireDefault(_unclosed);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function tokenizeAtRule(state) {
// it's an interpolation
if (state.css.charCodeAt(state.pos + 1) === _globals.openedCurlyBracket) {
state.nextPos = state.css.indexOf('}', state.pos + 2);
if (state.nextPos === -1) {
(0, _unclosed2.default)(state, 'interpolation');
}
state.cssPart = state.css.slice(state.pos, state.nextPos + 1);
state.lines = state.cssPart.split('\n');
state.lastLine = state.lines.length - 1;
if (state.lastLine > 0) {
state.nextLine = state.line + state.lastLine;
state.nextOffset = state.nextPos - state.lines[state.lastLine].length;
} else {
state.nextLine = state.line;
state.nextOffset = state.offset;
}
state.tokens.push(['word', state.cssPart, state.line, state.pos - state.offset, state.nextLine, state.nextPos - state.nextOffset]);
state.offset = state.nextOffset;
state.line = state.nextLine;
} else {
_globals.atEndPattern.lastIndex = state.pos + 1;
_globals.atEndPattern.test(state.css);
if (_globals.atEndPattern.lastIndex === 0) {
state.nextPos = state.css.length - 1;
} else {
state.nextPos = _globals.atEndPattern.lastIndex - 2;
}
state.cssPart = state.css.slice(state.pos, state.nextPos + 1);
state.token = 'at-word';
// check if it's a variable
if (_globals.variablePattern.test(state.cssPart)) {
_globals.wordEndPattern.lastIndex = state.pos + 1;
_globals.wordEndPattern.test(state.css);
if (_globals.wordEndPattern.lastIndex === 0) {
state.nextPos = state.css.length - 1;
} else {
state.nextPos = _globals.wordEndPattern.lastIndex - 2;
}
state.cssPart = state.css.slice(state.pos, state.nextPos + 1);
state.token = 'word';
}
state.tokens.push([state.token, state.cssPart, state.line, state.pos - state.offset, state.line, state.nextPos - state.offset]);
}
state.pos = state.nextPos;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function tokenizeAtRule(e){e.css.charCodeAt(e.pos+1)===_globals.openedCurlyBracket?(e.nextPos=e.css.indexOf("}",e.pos+2),-1===e.nextPos&&(0,_unclosed2.default)(e,"interpolation"),e.cssPart=e.css.slice(e.pos,e.nextPos+1),e.lines=e.cssPart.split("\n"),e.lastLine=e.lines.length-1,e.lastLine>0?(e.nextLine=e.line+e.lastLine,e.nextOffset=e.nextPos-e.lines[e.lastLine].length):(e.nextLine=e.line,e.nextOffset=e.offset),e.tokens.push(["word",e.cssPart,e.line,e.pos-e.offset,e.nextLine,e.nextPos-e.nextOffset]),e.offset=e.nextOffset,e.line=e.nextLine):(_globals.atEndPattern.lastIndex=e.pos+1,_globals.atEndPattern.test(e.css),0===_globals.atEndPattern.lastIndex?e.nextPos=e.css.length-1:e.nextPos=_globals.atEndPattern.lastIndex-2,e.cssPart=e.css.slice(e.pos,e.nextPos+1),e.token="at-word",_globals.variablePattern.test(e.cssPart)&&(_globals.wordEndPattern.lastIndex=e.pos+1,_globals.wordEndPattern.test(e.css),0===_globals.wordEndPattern.lastIndex?e.nextPos=e.css.length-1:e.nextPos=_globals.wordEndPattern.lastIndex-2,e.cssPart=e.css.slice(e.pos,e.nextPos+1),e.token="word"),e.tokens.push([e.token,e.cssPart,e.line,e.pos-e.offset,e.line,e.nextPos-e.offset])),e.pos=e.nextPos}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeAtRule;var _globals=require("./globals"),_unclosed=require("./unclosed"),_unclosed2=_interopRequireDefault(_unclosed);module.exports=exports.default;

View file

@ -0,0 +1,29 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeBackslash;
var _globals = require('./globals');
function tokenizeBackslash(state) {
state.nextPos = state.pos;
state.escape = true;
while (state.css.charCodeAt(state.nextPos + 1) === _globals.backslash) {
state.nextPos += 1;
state.escape = !state.escape;
}
state.symbolCode = state.css.charCodeAt(state.nextPos + 1);
if (state.escape && state.symbolCode !== _globals.slash && state.symbolCode !== _globals.space && state.symbolCode !== _globals.newline && state.symbolCode !== _globals.tab && state.symbolCode !== _globals.carriageReturn && state.symbolCode !== _globals.feed) {
state.nextPos += 1;
}
state.tokens.push(['word', state.css.slice(state.pos, state.nextPos + 1), state.line, state.pos - state.offset, state.line, state.nextPos - state.offset]);
state.pos = state.nextPos;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function tokenizeBackslash(e){for(e.nextPos=e.pos,e.escape=!0;e.css.charCodeAt(e.nextPos+1)===_globals.backslash;)e.nextPos+=1,e.escape=!e.escape;e.symbolCode=e.css.charCodeAt(e.nextPos+1),e.escape&&e.symbolCode!==_globals.slash&&e.symbolCode!==_globals.space&&e.symbolCode!==_globals.newline&&e.symbolCode!==_globals.tab&&e.symbolCode!==_globals.carriageReturn&&e.symbolCode!==_globals.feed&&(e.nextPos+=1),e.tokens.push(["word",e.css.slice(e.pos,e.nextPos+1),e.line,e.pos-e.offset,e.line,e.nextPos-e.offset]),e.pos=e.nextPos}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeBackslash;var _globals=require("./globals");module.exports=exports.default;

View file

@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeBasicSymbol;
function tokenizeBasicSymbol(state) {
state.tokens.push([state.symbol, state.symbol, state.line, state.pos - state.offset]);
}
module.exports = exports["default"];

View file

@ -0,0 +1 @@
"use strict";function tokenizeBasicSymbol(e){e.tokens.push([e.symbol,e.symbol,e.line,e.pos-e.offset])}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeBasicSymbol,module.exports=exports.default;

View file

@ -0,0 +1,10 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeComma;
function tokenizeComma(state) {
state.tokens.push(['word', state.symbol, state.line, state.pos - state.offset, state.line, state.pos - state.offset + 1]);
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function tokenizeComma(e){e.tokens.push(["word",e.symbol,e.line,e.pos-e.offset,e.line,e.pos-e.offset+1])}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeComma,module.exports=exports.default;

View file

@ -0,0 +1,66 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeDefault;
var _globals = require('./globals');
var _findEndOfEscaping = require('./find-end-of-escaping');
var _findEndOfEscaping2 = _interopRequireDefault(_findEndOfEscaping);
var _isEscaping = require('./is-escaping');
var _isEscaping2 = _interopRequireDefault(_isEscaping);
var _tokenizeInlineComment = require('./tokenize-inline-comment');
var _tokenizeInlineComment2 = _interopRequireDefault(_tokenizeInlineComment);
var _tokenizeMultilineComment = require('./tokenize-multiline-comment');
var _tokenizeMultilineComment2 = _interopRequireDefault(_tokenizeMultilineComment);
var _unclosed = require('./unclosed');
var _unclosed2 = _interopRequireDefault(_unclosed);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function tokenizeDefault(state) {
var nextSymbolCode = state.css.charCodeAt(state.pos + 1);
if (state.symbolCode === _globals.slash && nextSymbolCode === _globals.asterisk) {
(0, _tokenizeMultilineComment2.default)(state);
} else if (state.symbolCode === _globals.slash && nextSymbolCode === _globals.slash) {
(0, _tokenizeInlineComment2.default)(state);
} else {
if ((0, _isEscaping2.default)(state)) {
var pos = (0, _findEndOfEscaping2.default)(state);
if (pos < 0) {
(0, _unclosed2.default)(state, 'escaping');
} else {
state.nextPos = pos;
}
} else {
_globals.wordEndPattern.lastIndex = state.pos + 1;
_globals.wordEndPattern.test(state.css);
if (_globals.wordEndPattern.lastIndex === 0) {
state.nextPos = state.css.length - 1;
} else {
state.nextPos = _globals.wordEndPattern.lastIndex - 2;
}
}
state.cssPart = state.css.slice(state.pos, state.nextPos + 1);
state.tokens.push(['word', state.cssPart, state.line, state.pos - state.offset, state.line, state.nextPos - state.offset]);
state.pos = state.nextPos;
}
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function tokenizeDefault(e){var n=e.css.charCodeAt(e.pos+1);if(e.symbolCode===_globals.slash&&n===_globals.asterisk)(0,_tokenizeMultilineComment2.default)(e);else if(e.symbolCode===_globals.slash&&n===_globals.slash)(0,_tokenizeInlineComment2.default)(e);else{if((0,_isEscaping2.default)(e)){var t=(0,_findEndOfEscaping2.default)(e);t<0?(0,_unclosed2.default)(e,"escaping"):e.nextPos=t}else _globals.wordEndPattern.lastIndex=e.pos+1,_globals.wordEndPattern.test(e.css),0===_globals.wordEndPattern.lastIndex?e.nextPos=e.css.length-1:e.nextPos=_globals.wordEndPattern.lastIndex-2;e.cssPart=e.css.slice(e.pos,e.nextPos+1),e.tokens.push(["word",e.cssPart,e.line,e.pos-e.offset,e.line,e.nextPos-e.offset]),e.pos=e.nextPos}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeDefault;var _globals=require("./globals"),_findEndOfEscaping=require("./find-end-of-escaping"),_findEndOfEscaping2=_interopRequireDefault(_findEndOfEscaping),_isEscaping=require("./is-escaping"),_isEscaping2=_interopRequireDefault(_isEscaping),_tokenizeInlineComment=require("./tokenize-inline-comment"),_tokenizeInlineComment2=_interopRequireDefault(_tokenizeInlineComment),_tokenizeMultilineComment=require("./tokenize-multiline-comment"),_tokenizeMultilineComment2=_interopRequireDefault(_tokenizeMultilineComment),_unclosed=require("./unclosed"),_unclosed2=_interopRequireDefault(_unclosed);module.exports=exports.default;

View file

@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeInlineComment;
function tokenizeInlineComment(state) {
state.nextPos = state.css.indexOf('\n', state.pos + 2) - 1;
if (state.nextPos === -2) {
state.nextPos = state.css.length - 1;
}
state.tokens.push(['comment', state.css.slice(state.pos, state.nextPos + 1), state.line, state.pos - state.offset, state.line, state.nextPos - state.offset, 'inline']);
state.pos = state.nextPos;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function tokenizeInlineComment(e){e.nextPos=e.css.indexOf("\n",e.pos+2)-1,-2===e.nextPos&&(e.nextPos=e.css.length-1),e.tokens.push(["comment",e.css.slice(e.pos,e.nextPos+1),e.line,e.pos-e.offset,e.line,e.nextPos-e.offset,"inline"]),e.pos=e.nextPos}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeInlineComment,module.exports=exports.default;

View file

@ -0,0 +1,39 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeMultilineComment;
var _unclosed = require('./unclosed');
var _unclosed2 = _interopRequireDefault(_unclosed);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function tokenizeMultilineComment(state) {
state.nextPos = state.css.indexOf('*/', state.pos + 2) + 1;
if (state.nextPos === 0) {
(0, _unclosed2.default)(state, 'comment');
}
state.cssPart = state.css.slice(state.pos, state.nextPos + 1);
state.lines = state.cssPart.split('\n');
state.lastLine = state.lines.length - 1;
if (state.lastLine > 0) {
state.nextLine = state.line + state.lastLine;
state.nextOffset = state.nextPos - state.lines[state.lastLine].length;
} else {
state.nextLine = state.line;
state.nextOffset = state.offset;
}
state.tokens.push(['comment', state.cssPart, state.line, state.pos - state.offset, state.nextLine, state.nextPos - state.nextOffset]);
state.offset = state.nextOffset;
state.line = state.nextLine;
state.pos = state.nextPos;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function tokenizeMultilineComment(e){e.nextPos=e.css.indexOf("*/",e.pos+2)+1,0===e.nextPos&&(0,_unclosed2.default)(e,"comment"),e.cssPart=e.css.slice(e.pos,e.nextPos+1),e.lines=e.cssPart.split("\n"),e.lastLine=e.lines.length-1,e.lastLine>0?(e.nextLine=e.line+e.lastLine,e.nextOffset=e.nextPos-e.lines[e.lastLine].length):(e.nextLine=e.line,e.nextOffset=e.offset),e.tokens.push(["comment",e.cssPart,e.line,e.pos-e.offset,e.nextLine,e.nextPos-e.nextOffset]),e.offset=e.nextOffset,e.line=e.nextLine,e.pos=e.nextPos}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeMultilineComment;var _unclosed=require("./unclosed"),_unclosed2=_interopRequireDefault(_unclosed);module.exports=exports.default;

View file

@ -0,0 +1,90 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeOpenedParenthesis;
var _globals = require('./globals');
var _unclosed = require('./unclosed');
var _unclosed2 = _interopRequireDefault(_unclosed);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function findClosedParenthesisPosition(css, length, start) {
var openedParenthesisCount = 0;
for (var i = start; i < length; i++) {
var symbol = css[i];
if (symbol === '(') {
openedParenthesisCount++;
} else if (symbol === ')') {
openedParenthesisCount--;
if (!openedParenthesisCount) {
return i;
}
}
}
return -1;
}
// it is not very reasonable to reduce complexity beyond this level
// eslint-disable-next-line complexity
function tokenizeOpenedParenthesis(state) {
var nextSymbolCode = state.css.charCodeAt(state.pos + 1);
var tokensCount = state.tokens.length;
var prevTokenCssPart = tokensCount ? state.tokens[tokensCount - 1][1] : '';
if (prevTokenCssPart === 'url' && nextSymbolCode !== _globals.singleQuote && nextSymbolCode !== _globals.doubleQuote && nextSymbolCode !== _globals.space && nextSymbolCode !== _globals.newline && nextSymbolCode !== _globals.tab && nextSymbolCode !== _globals.feed && nextSymbolCode !== _globals.carriageReturn) {
state.nextPos = state.pos;
do {
state.escaped = false;
state.nextPos = state.css.indexOf(')', state.nextPos + 1);
if (state.nextPos === -1) {
(0, _unclosed2.default)(state, 'bracket');
}
state.escapePos = state.nextPos;
while (state.css.charCodeAt(state.escapePos - 1) === _globals.backslash) {
state.escapePos -= 1;
state.escaped = !state.escaped;
}
} while (state.escaped);
state.tokens.push(['brackets', state.css.slice(state.pos, state.nextPos + 1), state.line, state.pos - state.offset, state.line, state.nextPos - state.offset]);
state.pos = state.nextPos;
} else {
state.nextPos = findClosedParenthesisPosition(state.css, state.length, state.pos);
state.cssPart = state.css.slice(state.pos, state.nextPos + 1);
var foundParam = state.cssPart.indexOf('@') >= 0;
var foundString = /['"]/.test(state.cssPart);
if (state.cssPart.length === 0 || state.cssPart === '...' || foundParam && !foundString) {
// we're dealing with a mixin param block
if (state.nextPos === -1) {
(0, _unclosed2.default)(state, 'bracket');
}
state.tokens.push([state.symbol, state.symbol, state.line, state.pos - state.offset]);
} else {
var badBracket = _globals.badBracketPattern.test(state.cssPart);
if (state.nextPos === -1 || badBracket) {
state.tokens.push([state.symbol, state.symbol, state.line, state.pos - state.offset]);
} else {
state.tokens.push(['brackets', state.cssPart, state.line, state.pos - state.offset, state.line, state.nextPos - state.offset]);
state.pos = state.nextPos;
}
}
}
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function findClosedParenthesisPosition(e,s,o){for(var t=0,n=o;n<s;n++){var l=e[n];if("("===l)t++;else if(")"===l&&!--t)return n}return-1}function tokenizeOpenedParenthesis(e){var s=e.css.charCodeAt(e.pos+1),o=e.tokens.length;if("url"===(o?e.tokens[o-1][1]:"")&&s!==_globals.singleQuote&&s!==_globals.doubleQuote&&s!==_globals.space&&s!==_globals.newline&&s!==_globals.tab&&s!==_globals.feed&&s!==_globals.carriageReturn){e.nextPos=e.pos;do{for(e.escaped=!1,e.nextPos=e.css.indexOf(")",e.nextPos+1),-1===e.nextPos&&(0,_unclosed2.default)(e,"bracket"),e.escapePos=e.nextPos;e.css.charCodeAt(e.escapePos-1)===_globals.backslash;)e.escapePos-=1,e.escaped=!e.escaped}while(e.escaped);e.tokens.push(["brackets",e.css.slice(e.pos,e.nextPos+1),e.line,e.pos-e.offset,e.line,e.nextPos-e.offset]),e.pos=e.nextPos}else{e.nextPos=findClosedParenthesisPosition(e.css,e.length,e.pos),e.cssPart=e.css.slice(e.pos,e.nextPos+1);var t=e.cssPart.indexOf("@")>=0,n=/['"]/.test(e.cssPart);if(0===e.cssPart.length||"..."===e.cssPart||t&&!n)-1===e.nextPos&&(0,_unclosed2.default)(e,"bracket"),e.tokens.push([e.symbol,e.symbol,e.line,e.pos-e.offset]);else{var l=_globals.badBracketPattern.test(e.cssPart);-1===e.nextPos||l?e.tokens.push([e.symbol,e.symbol,e.line,e.pos-e.offset]):(e.tokens.push(["brackets",e.cssPart,e.line,e.pos-e.offset,e.line,e.nextPos-e.offset]),e.pos=e.nextPos)}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeOpenedParenthesis;var _globals=require("./globals"),_unclosed=require("./unclosed"),_unclosed2=_interopRequireDefault(_unclosed);module.exports=exports.default;

View file

@ -0,0 +1,39 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeQuotes;
var _globals = require('./globals');
var _unclosed = require('./unclosed');
var _unclosed2 = _interopRequireDefault(_unclosed);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function tokenizeQuotes(state) {
state.nextPos = state.pos;
do {
state.escaped = false;
state.nextPos = state.css.indexOf(state.symbol, state.nextPos + 1);
if (state.nextPos === -1) {
(0, _unclosed2.default)(state, 'quote');
}
state.escapePos = state.nextPos;
while (state.css.charCodeAt(state.escapePos - 1) === _globals.backslash) {
state.escapePos -= 1;
state.escaped = !state.escaped;
}
} while (state.escaped);
state.tokens.push(['string', state.css.slice(state.pos, state.nextPos + 1), state.line, state.pos - state.offset, state.line, state.nextPos - state.offset]);
state.pos = state.nextPos;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function tokenizeQuotes(e){e.nextPos=e.pos;do{for(e.escaped=!1,e.nextPos=e.css.indexOf(e.symbol,e.nextPos+1),-1===e.nextPos&&(0,_unclosed2.default)(e,"quote"),e.escapePos=e.nextPos;e.css.charCodeAt(e.escapePos-1)===_globals.backslash;)e.escapePos-=1,e.escaped=!e.escaped}while(e.escaped);e.tokens.push(["string",e.css.slice(e.pos,e.nextPos+1),e.line,e.pos-e.offset,e.line,e.nextPos-e.offset]),e.pos=e.nextPos}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeQuotes;var _globals=require("./globals"),_unclosed=require("./unclosed"),_unclosed2=_interopRequireDefault(_unclosed);module.exports=exports.default;

View file

@ -0,0 +1,92 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeSymbol;
var _globals = require('./globals');
var _tokenizeAtRule = require('./tokenize-at-rule');
var _tokenizeAtRule2 = _interopRequireDefault(_tokenizeAtRule);
var _tokenizeBackslash = require('./tokenize-backslash');
var _tokenizeBackslash2 = _interopRequireDefault(_tokenizeBackslash);
var _tokenizeBasicSymbol = require('./tokenize-basic-symbol');
var _tokenizeBasicSymbol2 = _interopRequireDefault(_tokenizeBasicSymbol);
var _tokenizeComma = require('./tokenize-comma');
var _tokenizeComma2 = _interopRequireDefault(_tokenizeComma);
var _tokenizeDefault = require('./tokenize-default');
var _tokenizeDefault2 = _interopRequireDefault(_tokenizeDefault);
var _tokenizeOpenedParenthesis = require('./tokenize-opened-parenthesis');
var _tokenizeOpenedParenthesis2 = _interopRequireDefault(_tokenizeOpenedParenthesis);
var _tokenizeQuotes = require('./tokenize-quotes');
var _tokenizeQuotes2 = _interopRequireDefault(_tokenizeQuotes);
var _tokenizeWhitespace = require('./tokenize-whitespace');
var _tokenizeWhitespace2 = _interopRequireDefault(_tokenizeWhitespace);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// we cannot reduce complexity beyond this level
// eslint-disable-next-line complexity
function tokenizeSymbol(state) {
switch (state.symbolCode) {
case _globals.newline:
case _globals.space:
case _globals.tab:
case _globals.carriageReturn:
case _globals.feed:
(0, _tokenizeWhitespace2.default)(state);
break;
case _globals.comma:
(0, _tokenizeComma2.default)(state);
break;
case _globals.colon:
case _globals.semicolon:
case _globals.openedCurlyBracket:
case _globals.closedCurlyBracket:
case _globals.closedParenthesis:
case _globals.openSquareBracket:
case _globals.closeSquareBracket:
(0, _tokenizeBasicSymbol2.default)(state);
break;
case _globals.openedParenthesis:
(0, _tokenizeOpenedParenthesis2.default)(state);
break;
case _globals.singleQuote:
case _globals.doubleQuote:
(0, _tokenizeQuotes2.default)(state);
break;
case _globals.atRule:
(0, _tokenizeAtRule2.default)(state);
break;
case _globals.backslash:
(0, _tokenizeBackslash2.default)(state);
break;
default:
(0, _tokenizeDefault2.default)(state);
break;
}
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function tokenizeSymbol(e){switch(e.symbolCode){case _globals.newline:case _globals.space:case _globals.tab:case _globals.carriageReturn:case _globals.feed:(0,_tokenizeWhitespace2.default)(e);break;case _globals.comma:(0,_tokenizeComma2.default)(e);break;case _globals.colon:case _globals.semicolon:case _globals.openedCurlyBracket:case _globals.closedCurlyBracket:case _globals.closedParenthesis:case _globals.openSquareBracket:case _globals.closeSquareBracket:(0,_tokenizeBasicSymbol2.default)(e);break;case _globals.openedParenthesis:(0,_tokenizeOpenedParenthesis2.default)(e);break;case _globals.singleQuote:case _globals.doubleQuote:(0,_tokenizeQuotes2.default)(e);break;case _globals.atRule:(0,_tokenizeAtRule2.default)(e);break;case _globals.backslash:(0,_tokenizeBackslash2.default)(e);break;default:(0,_tokenizeDefault2.default)(e)}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeSymbol;var _globals=require("./globals"),_tokenizeAtRule=require("./tokenize-at-rule"),_tokenizeAtRule2=_interopRequireDefault(_tokenizeAtRule),_tokenizeBackslash=require("./tokenize-backslash"),_tokenizeBackslash2=_interopRequireDefault(_tokenizeBackslash),_tokenizeBasicSymbol=require("./tokenize-basic-symbol"),_tokenizeBasicSymbol2=_interopRequireDefault(_tokenizeBasicSymbol),_tokenizeComma=require("./tokenize-comma"),_tokenizeComma2=_interopRequireDefault(_tokenizeComma),_tokenizeDefault=require("./tokenize-default"),_tokenizeDefault2=_interopRequireDefault(_tokenizeDefault),_tokenizeOpenedParenthesis=require("./tokenize-opened-parenthesis"),_tokenizeOpenedParenthesis2=_interopRequireDefault(_tokenizeOpenedParenthesis),_tokenizeQuotes=require("./tokenize-quotes"),_tokenizeQuotes2=_interopRequireDefault(_tokenizeQuotes),_tokenizeWhitespace=require("./tokenize-whitespace"),_tokenizeWhitespace2=_interopRequireDefault(_tokenizeWhitespace);module.exports=exports.default;

View file

@ -0,0 +1,26 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeWhitespace;
var _globals = require('./globals');
function tokenizeWhitespace(state) {
state.nextPos = state.pos;
// collect all neighbour space symbols
do {
state.nextPos += 1;
state.symbolCode = state.css.charCodeAt(state.nextPos);
if (state.symbolCode === _globals.newline) {
state.offset = state.nextPos;
state.line += 1;
}
} while (state.symbolCode === _globals.space || state.symbolCode === _globals.newline || state.symbolCode === _globals.tab || state.symbolCode === _globals.carriageReturn || state.symbolCode === _globals.feed);
state.tokens.push(['space', state.css.slice(state.pos, state.nextPos)]);
state.pos = state.nextPos - 1;
}
module.exports = exports['default'];

View file

@ -0,0 +1 @@
"use strict";function tokenizeWhitespace(e){e.nextPos=e.pos;do{e.nextPos+=1,e.symbolCode=e.css.charCodeAt(e.nextPos),e.symbolCode===_globals.newline&&(e.offset=e.nextPos,e.line+=1)}while(e.symbolCode===_globals.space||e.symbolCode===_globals.newline||e.symbolCode===_globals.tab||e.symbolCode===_globals.carriageReturn||e.symbolCode===_globals.feed);e.tokens.push(["space",e.css.slice(e.pos,e.nextPos)]),e.pos=e.nextPos-1}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=tokenizeWhitespace;var _globals=require("./globals");module.exports=exports.default;

View file

@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = unclosed;
function unclosed(state, what) {
throw state.input.error("Unclosed " + what, state.line, state.pos - state.offset);
}
module.exports = exports["default"];

View file

@ -0,0 +1 @@
"use strict";function unclosed(e,o){throw e.input.error("Unclosed "+o,e.line,e.pos-e.offset)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=unclosed,module.exports=exports.default;

View file

@ -0,0 +1,4 @@
'use strict';
module.exports = function () {
return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g;
};

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,64 @@
{
"name": "ansi-regex",
"version": "2.1.1",
"description": "Regular expression for matching ANSI escape codes",
"license": "MIT",
"repository": "chalk/ansi-regex",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)",
"JD Ballard <i.am.qix@gmail.com> (github.com/qix-)"
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "xo && ava --verbose",
"view-supported": "node fixtures/view-codes.js"
},
"files": [
"index.js"
],
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"text",
"regex",
"regexp",
"re",
"match",
"test",
"find",
"pattern"
],
"devDependencies": {
"ava": "0.17.0",
"xo": "0.16.0"
},
"xo": {
"rules": {
"guard-for-in": 0,
"no-loop-func": 0
}
}
}

View file

@ -0,0 +1,39 @@
# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex)
> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install --save ansi-regex
```
## Usage
```js
const ansiRegex = require('ansi-regex');
ansiRegex().test('\u001b[4mcake\u001b[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001b[4mcake\u001b[0m'.match(ansiRegex());
//=> ['\u001b[4m', '\u001b[0m']
```
## FAQ
### Why do you test for codes not in the ECMA 48 standard?
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. If I recall correctly, we test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View file

@ -0,0 +1,65 @@
'use strict';
function assembleStyles () {
var styles = {
modifiers: {
reset: [0, 0],
bold: [1, 22], // 21 isn't widely supported and 22 does the same thing
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
colors: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39]
},
bgColors: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49]
}
};
// fix humans
styles.colors.grey = styles.colors.gray;
Object.keys(styles).forEach(function (groupName) {
var group = styles[groupName];
Object.keys(group).forEach(function (styleName) {
var style = group[styleName];
styles[styleName] = group[styleName] = {
open: '\u001b[' + style[0] + 'm',
close: '\u001b[' + style[1] + 'm'
};
});
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
});
return styles;
}
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,50 @@
{
"name": "ansi-styles",
"version": "2.2.1",
"description": "ANSI escape codes for styling strings in the terminal",
"license": "MIT",
"repository": "chalk/ansi-styles",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)"
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"files": [
"index.js"
],
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"devDependencies": {
"mocha": "*"
}
}

View file

@ -0,0 +1,86 @@
# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles)
> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal
You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings.
![](screenshot.png)
## Install
```
$ npm install --save ansi-styles
```
## Usage
```js
var ansi = require('ansi-styles');
console.log(ansi.green.open + 'Hello world!' + ansi.green.close);
```
## API
Each style has an `open` and `close` property.
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(not widely supported)*
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `gray`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
## Advanced usage
By default you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module.
- `ansi.modifiers`
- `ansi.colors`
- `ansi.bgColors`
###### Example
```js
console.log(ansi.colors.green.open);
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View file

@ -0,0 +1,116 @@
'use strict';
var escapeStringRegexp = require('escape-string-regexp');
var ansiStyles = require('ansi-styles');
var stripAnsi = require('strip-ansi');
var hasAnsi = require('has-ansi');
var supportsColor = require('supports-color');
var defineProps = Object.defineProperties;
var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM);
function Chalk(options) {
// detect mode if not set manually
this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled;
}
// use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\u001b[94m';
}
var styles = (function () {
var ret = {};
Object.keys(ansiStyles).forEach(function (key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function () {
return build.call(this, this._styles.concat(key));
}
};
});
return ret;
})();
var proto = defineProps(function chalk() {}, styles);
function build(_styles) {
var builder = function () {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
builder.enabled = this.enabled;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
/* eslint-disable no-proto */
builder.__proto__ = proto;
return builder;
}
function applyStyle() {
// support varags, but simply cast to string in case there's only one arg
var args = arguments;
var argsLen = args.length;
var str = argsLen !== 0 && String(arguments[0]);
if (argsLen > 1) {
// don't slice `arguments`, it prevents v8 optimizations
for (var a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || !str) {
return str;
}
var nestedStyles = this._styles;
var i = nestedStyles.length;
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
var originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) {
ansiStyles.dim.open = '';
}
while (i--) {
var code = ansiStyles[nestedStyles[i]];
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
}
// Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue.
ansiStyles.dim.open = originalDim;
return str;
}
function init() {
var ret = {};
Object.keys(styles).forEach(function (name) {
ret[name] = {
get: function () {
return build.call(this, [name]);
}
};
});
return ret;
}
defineProps(Chalk.prototype, init());
module.exports = new Chalk();
module.exports.styles = ansiStyles;
module.exports.hasColor = hasAnsi;
module.exports.stripColor = stripAnsi;
module.exports.supportsColor = supportsColor;

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,50 @@
'use strict';
var argv = process.argv;
var terminator = argv.indexOf('--');
var hasFlag = function (flag) {
flag = '--' + flag;
var pos = argv.indexOf(flag);
return pos !== -1 && (terminator !== -1 ? pos < terminator : true);
};
module.exports = (function () {
if ('FORCE_COLOR' in process.env) {
return true;
}
if (hasFlag('no-color') ||
hasFlag('no-colors') ||
hasFlag('color=false')) {
return false;
}
if (hasFlag('color') ||
hasFlag('colors') ||
hasFlag('color=true') ||
hasFlag('color=always')) {
return true;
}
if (process.stdout && !process.stdout.isTTY) {
return false;
}
if (process.platform === 'win32') {
return true;
}
if ('COLORTERM' in process.env) {
return true;
}
if (process.env.TERM === 'dumb') {
return false;
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
return true;
}
return false;
})();

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,49 @@
{
"name": "supports-color",
"version": "2.0.0",
"description": "Detect whether a terminal supports color",
"license": "MIT",
"repository": "chalk/supports-color",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)"
],
"engines": {
"node": ">=0.8.0"
},
"scripts": {
"test": "mocha"
},
"files": [
"index.js"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"ansi",
"styles",
"tty",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"support",
"supports",
"capability",
"detect"
],
"devDependencies": {
"mocha": "*",
"require-uncached": "^1.0.2"
}
}

View file

@ -0,0 +1,36 @@
# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color)
> Detect whether a terminal supports color
## Install
```
$ npm install --save supports-color
```
## Usage
```js
var supportsColor = require('supports-color');
if (supportsColor) {
console.log('Terminal supports color');
}
```
It obeys the `--color` and `--no-color` CLI flags.
For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`.
## Related
- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View file

@ -0,0 +1,70 @@
{
"name": "chalk",
"version": "1.1.3",
"description": "Terminal string styling done right. Much color.",
"license": "MIT",
"repository": "chalk/chalk",
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)",
"JD Ballard <i.am.qix@gmail.com> (github.com/qix-)"
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "xo && mocha",
"bench": "matcha benchmark.js",
"coverage": "nyc npm test && nyc report",
"coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
},
"files": [
"index.js"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"str",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"ansi-styles": "^2.2.1",
"escape-string-regexp": "^1.0.2",
"has-ansi": "^2.0.0",
"strip-ansi": "^3.0.0",
"supports-color": "^2.0.0"
},
"devDependencies": {
"coveralls": "^2.11.2",
"matcha": "^0.6.0",
"mocha": "*",
"nyc": "^3.0.0",
"require-uncached": "^1.0.2",
"resolve-from": "^1.0.0",
"semver": "^4.3.3",
"xo": "*"
},
"xo": {
"envs": [
"node",
"mocha"
]
}
}

View file

@ -0,0 +1,213 @@
<h1 align="center">
<br>
<br>
<img width="360" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
<br>
<br>
<br>
</h1>
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk)
[![Coverage Status](https://coveralls.io/repos/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/r/chalk/chalk?branch=master)
[![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4)
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough.
**Chalk is a clean and focused alternative.**
![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png)
## Why
- Highly performant
- Doesn't extend `String.prototype`
- Expressive API
- Ability to nest styles
- Clean and focused
- Auto-detects color support
- Actively maintained
- [Used by ~4500 modules](https://www.npmjs.com/browse/depended/chalk) as of July 15, 2015
## Install
```
$ npm install --save chalk
```
## Usage
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
var chalk = require('chalk');
// style a string
chalk.blue('Hello world!');
// combine styled and normal strings
chalk.blue('Hello') + 'World' + chalk.red('!');
// compose multiple styles using the chainable API
chalk.blue.bgRed.bold('Hello world!');
// pass in multiple arguments
chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz');
// nest styles
chalk.red('Hello', chalk.underline.bgBlue('world') + '!');
// nest styles of the same type even (color, underline, background)
chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
);
```
Easily define your own themes.
```js
var chalk = require('chalk');
var error = chalk.bold.red;
console.log(error('Error!'));
```
Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data).
```js
var name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> Hello Sindre
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `Chalk.red.yellow.green` is equivalent to `Chalk.green`.
Multiple arguments will be separated by space.
### chalk.enabled
Color support is automatically detected, but you can override it by setting the `enabled` property. You should however only do this in your own code as it applies globally to all chalk consumers.
If you need to change this in a reusable module create a new instance:
```js
var ctx = new chalk.constructor({enabled: false});
```
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`.
### chalk.styles
Exposes the styles as [ANSI escape codes](https://github.com/chalk/ansi-styles).
Generally not useful, but you might need just the `.open` or `.close` escape code if you're mixing externally styled strings with your own.
```js
var chalk = require('chalk');
console.log(chalk.styles.red);
//=> {open: '\u001b[31m', close: '\u001b[39m'}
console.log(chalk.styles.red.open + 'Hello' + chalk.styles.red.close);
```
### chalk.hasColor(string)
Check whether a string [has color](https://github.com/chalk/has-ansi).
### chalk.stripColor(string)
[Strip color](https://github.com/chalk/strip-ansi) from a string.
Can be useful in combination with `.supportsColor` to strip color on externally styled text when it's not supported.
Example:
```js
var chalk = require('chalk');
var styledString = getText();
if (!chalk.supportsColor) {
styledString = chalk.stripColor(styledString);
}
```
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(not widely supported)*
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue` *(on Windows the bright version is used as normal blue is illegible)*
- `magenta`
- `cyan`
- `white`
- `gray`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
## 256-colors
Chalk does not support anything other than the base eight colors, which guarantees it will work on all terminals and systems. Some terminals, specifically `xterm` compliant ones, will support the full range of 8-bit colors. For this the lower level [ansi-256-colors](https://github.com/jbnicolai/ansi-256-colors) package can be used.
## Windows
If you're on Windows, do yourself a favor and use [`cmder`](http://bliker.github.io/cmder/) instead of `cmd.exe`.
## Related
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles/) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color/) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View file

@ -0,0 +1,11 @@
'use strict';
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
module.exports = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
};

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,41 @@
{
"name": "escape-string-regexp",
"version": "1.0.5",
"description": "Escape RegExp special characters",
"license": "MIT",
"repository": "sindresorhus/escape-string-regexp",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Boy Nicolai Appelman <joshua@jbna.nl> (jbna.nl)"
],
"engines": {
"node": ">=0.8.0"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"escape",
"regex",
"regexp",
"re",
"regular",
"expression",
"string",
"str",
"special",
"characters"
],
"devDependencies": {
"ava": "*",
"xo": "*"
}
}

View file

@ -0,0 +1,27 @@
# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp)
> Escape RegExp special characters
## Install
```
$ npm install --save escape-string-regexp
```
## Usage
```js
const escapeStringRegexp = require('escape-string-regexp');
const escapedString = escapeStringRegexp('how much $ for a unicorn?');
//=> 'how much \$ for a unicorn\?'
new RegExp(escapedString);
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View file

@ -0,0 +1,10 @@
'use strict';
module.exports = function (flag, argv) {
argv = argv || process.argv;
var terminatorPos = argv.indexOf('--');
var prefix = /^--/.test(flag) ? '' : '--';
var pos = argv.indexOf(prefix + flag);
return pos !== -1 && (terminatorPos !== -1 ? pos < terminatorPos : true);
};

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,48 @@
{
"name": "has-flag",
"version": "1.0.0",
"description": "Check if argv has a specific flag",
"license": "MIT",
"repository": "sindresorhus/has-flag",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)",
"JD Ballard <i.am.qix@gmail.com> (github.com/qix-)"
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "node test.js"
},
"files": [
"index.js"
],
"keywords": [
"has",
"check",
"detect",
"contains",
"find",
"flag",
"cli",
"command-line",
"argv",
"process",
"arg",
"args",
"argument",
"arguments",
"getopt",
"minimist",
"optimist"
],
"devDependencies": {
"ava": "0.0.4"
}
}

View file

@ -0,0 +1,64 @@
# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag)
> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag
Correctly stops looking after an `--` argument terminator.
## Install
```
$ npm install --save has-flag
```
## Usage
```js
// foo.js
var hasFlag = require('has-flag');
hasFlag('unicorn');
//=> true
hasFlag('--unicorn');
//=> true
hasFlag('foo=bar');
//=> true
hasFlag('foo');
//=> false
hasFlag('rainbow');
//=> false
```
```
$ node foo.js --unicorn --foo=bar -- --rainbow
```
## API
### hasFlag(flag, [argv])
Returns a boolean whether the flag exists.
#### flag
Type: `string`
CLI flag to look for. The `--` prefix is optional.
#### argv
Type: `array`
Default: `process.argv`
CLI arguments.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View file

@ -0,0 +1,460 @@
# Change Log
This project adheres to [Semantic Versioning](http://semver.org/).
## 5.1.18
* Fix TypeScript definitions for case of multiple PostCSS versions
in `node_modules` (by Chris Eppstein).
## 5.2.17
* Add `postcss-sass` suggestion to syntax error on `.sass` input.
## 5.2.16
* Better error on wrong argument in node constructor.
## 5.2.15
* Fix TypeScript definitions (by bumbleblym).
## 5.2.14
* Fix browser bundle building in webpack (by janschoenherr).
## 5.2.13
* Do not add comment to important raws.
* Fix JSDoc (by Dmitry Semigradsky).
## 5.2.12
* Fix typo in deprecation message (by Garet McKinley).
## 5.2.11
* Fix TypeScript definitions (by Jed Mao).
## 5.2.10
* Fix TypeScript definitions (by Jed Mao).
## 5.2.9
* Update TypeScript definitions (by Jed Mao).
## 5.2.8
* Fix error message (by Ben Briggs).
## 5.2.7
* Better error message on syntax object in plugins list.
## 5.2.6
* Fix `postcss.vendor` for values with spaces (by 刘祺).
## 5.2.5
* Better error message on unclosed string (by Ben Briggs).
## 5.2.4
* Improve terminal CSS syntax highlight (by Simon Lydell).
## 5.2.3
* Better color highlight in syntax error code frame.
* Fix color highlight support in old systems.
## 5.2.2
* Update `Processor#version`.
## 5.2.1
* Fix source map path for CSS without `from` option (by Michele Locati).
## 5.2 “Duke Vapula”
* Add syntax highlight to code frame in syntax error (by Andrey Popp).
* Use Babel code frame style and size in syntax error.
* Add `[` and `]` tokens to parse `[attr=;] {}` correctly.
* Add `ignoreErrors` options to tokenizer (by Andrey Popp).
* Fix error position on tab indent (by Simon Lydell).
## 5.1.2
* Suggests SCSS/Less parsers on parse errors depends on file extension.
## 5.1.1
* Fix TypeScript definitions (by Efremov Alexey).
## 5.1 “King and President Zagan”
* Add URI in source map support (by Mark Finger).
* Add `map.from` option (by Mark Finger).
* Add `<no source>` mappings for nodes without source (by Bogdan Chadkin).
* Add function value support to `map.prev` option (by Chris Montoro).
* Add declaration value type check in shortcut creating (by 刘祺).
* `Result#warn` now returns new created warning.
* Dont call plugin creator in `postcss.plugin` call.
* Add source maps to PostCSS ES5 build.
* Add JSDoc to PostCSS classes.
* Clean npm package from unnecessary docs.
## 5.0.21
* Fix support with input source mao with `utf8` encoding name.
## 5.0.20
* Fix between raw value parsing (by David Clark).
* Update TypeScript definitions (by Jed Mao).
* Clean fake node.source after `append(string)`.
## 5.0.19
* Fix indent-based syntaxes support.
## 5.0.18
* Parse new lines according W3C CSS syntax specification.
## 5.0.17
* Fix options argument in `Node#warn` (by Ben Briggs).
* Fix TypeScript definitions (by Jed Mao).
## 5.0.16
* Fix CSS syntax error position on unclosed quotes.
## 5.0.15
* Fix `Node#clone()` on `null` value somewhere in node.
## 5.0.14
* Allow to use PostCSS in webpack bundle without JSON loader.
## 5.0.13
* Fix `index` and `word` options in `Warning#toString` (by Bogdan Chadkin).
* Fix input source content loading in errors.
* Fix map options on using `LazyResult` as input CSS.
* 100% test coverage.
* Use Babel 6.
## 5.0.12
* Allow passing a previous map with no mappings (by Andreas Lind).
## 5.0.11
* Increase plugins performance by 1.5 times.
## 5.0.10
* Fix warning from nodes without source.
## 5.0.9
* Fix source map type detection (by @asan).
## 5.0.8
* Fixed a missed step in `5.0.7` that caused the module to be published as
ES6 code.
## 5.0.7
* PostCSS now requires that node 0.12 is installed via the engines property
in package.json (by Howard Zuo).
## 5.0.6
* Fix parsing nested at-rule without semicolon (by Matt Drake).
* Trim `Declaration#value` (by Bogdan Chadkin).
## 5.0.5
* Fix multi-tokens property parsing (by Matt Drake).
## 5.0.4
* Fix start position in `Root#source`.
* Fix source map annotation, when CSS uses `\r\n` (by Mohammad Younes).
## 5.0.3
* Fix `url()` parsing.
* Fix using `selectors` in `Rule` constructor.
* Add start source to `Root` node.
## 5.0.2
* Fix `remove(index)` to be compatible with 4.x plugin.
## 5.0.1
* Fix PostCSS 4.x plugins compatibility.
* Fix type definition loading (by Jed Mao).
## 5.0 “President Valac”
* Remove `safe` option. Move Safe Parser to separate project.
* `Node#toString` does not include `before` for root nodes.
* Remove plugin returning `Root` API.
* Remove Promise polyfill for node.js 0.10.
* Deprecate `eachInside`, `eachDecl`, `eachRule`, `eachAtRule` and `eachComment`
in favor of `walk`, `walkDecls`, `walkRules`, `walkAtRules` and `walkComments`
(by Jed Mao).
* Deprecate `Container#remove` and `Node#removeSelf`
in favor of `Container#removeChild` and `Node#remove` (by Ben Briggs).
* Deprecate `Node#replace` in favor of `replaceWith` (by Ben Briggs).
* Deprecate raw properties in favor of `Node#raws` object.
* Deprecate `Node#style` in favor of `raw`.
* Deprecate `CssSyntaxError#generated` in favor of `input`.
* Deprecate `Node#cleanStyles` in favor of `cleanRaws`.
* Deprecate `Root#prevMap` in favor of `Root.source.input.map`.
* Add `syntax`, `parser` and `stringifier` options for Custom Syntaxes.
* Add stringifier option to `Node#toString`.
* Add `Result#content` alias for non-CSS syntaxes.
* Add `plugin.process(css)` shortcut to every plugin function (by Ben Briggs).
* Add multiple nodes support to insert methods (by Jonathan Neal).
* Add `Node#warn` shortcut (by Ben Briggs).
* Add `word` and `index` options to errors and warnings (by David Clark).
* Add `line`, `column` properties to `Warning`.
* Use `supports-color` library to detect color support in error output.
* Add type definitions for TypeScript plugin developers (by Jed Mao).
* `Rule#selectors` setter detects separators.
* Add `postcss.stringify` method.
* Throw descriptive errors for incorrectly formatted plugins.
* Add docs to npm release.
* Fix `url()` parsing.
* Fix Windows support (by Jed Mao).
## 4.1.16
* Fix errors without stack trace.
## 4.1.15
* Allow asynchronous plugins to change processor plugins list (by Ben Briggs).
## 4.1.14
* Fix for plugins packs defined by `postcss.plugin`.
## 4.1.13
* Fix input inlined source maps with UTF-8 encoding.
## 4.1.12
* Update Promise polyfill.
## 4.1.11
* Fix error message on wrong plugin format.
## 4.1.10
* Fix Promise behavior on sync plugin errors.
* Automatically fill `plugin` field in `CssSyntaxError`.
* Fix warning message (by Ben Briggs).
## 4.1.9
* Speed up `node.clone()`.
## 4.1.8
* Accepts `Processor` instance in `postcss()` constructor too.
## 4.1.7
* Speed up `postcss.list` (by Bogdan Chadkin).
## 4.1.6
* Fix Promise behavior on parsing error.
## 4.1.5
* Parse at-words in declaration values.
## 4.1.4
* Fix Promise polyfill dependency (by Anton Yakushev and Matija Marohnić).
## 4.1.3
* Add Promise polyfill for node.js 0.10 and IE.
## 4.1.2
* List helpers can be accessed independently `var space = postcss.list.space`.
## 4.1.1
* Show deprecated message only once.
## 4.1 “Marquis Andras”
* Asynchronous plugin support.
* Add warnings from plugins and `Result#messages`.
* Add `postcss.plugin()` to create plugins with a standard API.
* Insert nodes by CSS string.
* Show version warning message on error from an outdated plugin.
* Send `Result` instance to plugins as the second argument.
* Add `CssSyntaxError#plugin`.
* Add `CssSyntaxError#showSourceCode()`.
* Add `postcss.list` and `postcss.vendor` aliases.
* Add `Processor#version`.
* Parse wrong closing bracket.
* Parse `!important` statement with spaces and comments inside (by Ben Briggs).
* Throw an error on declaration without `prop` or `value` (by Philip Peterson).
* Fix source map mappings position.
* Add indexed source map support.
* Always set `error.generated`.
* Clean all source map annotation comments.
## 4.0.6
* Remove `babel` from released package dependencies (by Andres Suarez).
## 4.0.5
* Fix error message on double colon in declaration.
## 4.0.4
* Fix indent detection in some rare cases.
## 4.0.3
* Faster API with 6to5 Loose mode.
* Fix indexed source maps support.
## 4.0.2
* Do not copy IE hacks to code style.
## 4.0.1
* Add `source.input` to `Root` too.
## 4.0 “Duke Flauros”
* Rename `Container#childs` to `nodes`.
* Rename `PostCSS#processors` to `plugins`.
* Add `Node#replaceValues()` method.
* Add `Node#moveTo()`, `moveBefore()` and `moveAfter()` methods.
* Add `Node#cloneBefore()` and `cloneAfter()` shortcuts.
* Add `Node#next()`, `prev()` and `root()` shortcuts.
* Add `Node#replaceWith()` method.
* Add `Node#error()` method.
* Add `Container#removeAll()` method.
* Add filter argument to `eachDecl()` and `eachAtRule()`.
* Add `Node#source.input` and move `source.file` or `source.id` to `input`.
* Change code indent, when node was moved.
* Better fix code style on `Rule`, `AtRule` and `Comment` nodes changes.
* Allow to create rules and at-rules by hash shortcut in append methods.
* Add class name to CSS syntax error output.
## 3.0.7
* Fix IE filter parsing with multiple commands.
* Safer way to consume PostCSS object as plugin (by Maxime Thirouin).
## 3.0.6
* Fix missing semicolon when comment comes after last declaration.
* Fix Safe Mode declaration parsing on unclosed blocks.
## 3.0.5
* Fix parser to support difficult cases with backslash escape and brackets.
* Add `CssSyntaxError#stack` (by Maxime Thirouin).
## 3.0.4
* Fix Safe Mode on unknown word before declaration.
## 3.0.3
* Increase tokenizer speed (by Roman Dvornov).
## 3.0.2
* Fix empty comment parsing.
* Fix `Root#normalize` in some inserts.
## 3.0.1
* Fix Rhino JS runtime support.
* Typo in deprecated warning (by Maxime Thirouin).
## 3.0 “Marquis Andrealphus”
* New parser, which become the fastest ever CSS parser written in JavaScript.
* Parser can now parse declarations and rules in one parent (like in `@page`)
and nested declarations for plugins like `postcss-nested`.
* Child nodes array is now in `childs` property, instead of `decls` and `rules`.
* `map.inline` and `map.sourcesContent` options are now `true` by default.
* Fix iterators (`each`, `insertAfter`) on children array changes.
* Use previous source map to show origin source of CSS syntax error.
* Use 6to5 ES6 compiler, instead of ES6 Transpiler.
* Use code style for manually added rules from existing rules.
* Use `from` option from previous source map `file` field.
* Set `to` value to `from` if `to` option is missing.
* Use better node source name when missing `from` option.
* Show a syntax error when `;` is missed between declarations.
* Allow to pass `PostCSS` instance or list of plugins to `use()` method.
* Allow to pass `Result` instance to `process()` method.
* Trim Unicode BOM on source maps parsing.
* Parse at-rules without spaces like `@import"file"`.
* Better previous `sourceMappingURL` annotation comment cleaning.
* Do not remove previous `sourceMappingURL` comment on `map.annotation: false`.
* Parse nameless at-rules in Safe Mode.
* Fix source map generation for nodes without source.
* Fix next child `before` if `Root` first child got removed.
## 2.2.6
* Fix map generation for nodes without source (by Josiah Savary).
## 2.2.5
* Fix source map with BOM marker support (by Mohammad Younes).
* Fix source map paths (by Mohammad Younes).
## 2.2.4
* Fix `prepend()` on empty `Root`.
## 2.2.3
* Allow to use object shortcut in `use()` with functions like `autoprefixer`.
## 2.2.2
* Add shortcut to set processors in `use()` via object with `.postcss` property.
## 2.2.1
* Send `opts` from `Processor#process(css, opts)` to processors.
## 2.2 “Marquis Cimeies”
* Use GNU style syntax error messages.
* Add `Node#replace` method.
* Add `CssSyntaxError#reason` property.
## 2.1.2
* Fix UTF-8 support in inline source map.
* Fix source map `sourcesContent` if there is no `from` and `to` options.
## 2.1.1
* Allow to miss `to` and `from` options for inline source maps.
* Add `Node#source.id` if file name is unknown.
* Better detect splitter between rules in CSS concatenation tools.
* Automatically clone node in insert methods.
## 2.1 “King Amdusias”
* Change Traceur ES6 compiler to ES6 Transpiler.
* Show broken CSS line in syntax error.
## 2.0 “King Belial”
* Project was rewritten from CoffeeScript to ES6.
* Add Safe Mode to works with live input or with hacks from legacy code.
* More safer parser to pass all hacks from Browserhacks.com.
* Use real properties instead of magic getter/setter for raw properties.
## 1.0 “Marquis Decarabia”
* Save previous source map for each node to support CSS concatenation
with multiple previous maps.
* Add `map.sourcesContent` option to add origin content to `sourcesContent`
inside map.
* Allow to set different place of output map in annotation comment.
* Allow to use arrays and `Root` in `Container#append` and same methods.
* Add `Root#prevMap` with information about previous map.
* Allow to use latest PostCSS from GitHub by npm.
* `Result` now is lazy and it will generate output CSS only if you use `css`
or `map` property.
* Use separated `map.prev` option to set previous map.
* Rename `inlineMap` option to `map.inline`.
* Rename `mapAnnotation` option to `map.annotation`.
* `Result#map` now return `SourceMapGenerator` object, instead of string.
* Run previous map autodetect only if input CSS contains annotation comment.
* Add `map: 'inline'` shortcut for `map: { inline: true }` option.
* `Node#source.file` now will contains absolute path.
* Clean `Declaration#between` style on node clone.
## 0.3.5
* Allow to use `Root` or `Result` as first argument in `process()`.
* Save parsed AST to `Result#root`.
## 0.3.4
* Better space symbol detect to read UTF-8 BOM correctly.
## 0.3.3
* Remove source map hacks by using new Mozillas `source-map` (by Simon Lydell).
## 0.3.2
* Add URI encoding support for inline source maps.
## 0.3.1
* Fix relative paths from previous source map.
* Safer space split in `Rule#selectors` (by Simon Lydell).
## 0.3 “Prince Seere”
* Add `Comment` node for comments between declarations or rules.
* Add source map annotation comment to output CSS.
* Allow to inline source map to annotation comment by data:uri.
* Fix source maps on Windows.
* Fix source maps for subdirectory (by Dmitry Nikitenko and Simon Lydell).
* Autodetect previous source map.
* Add `first` and `last` shortcuts to container nodes.
* Parse `!important` to separated property in `Declaration`.
* Allow to break iteration by returning `false`.
* Copy code style to new nodes.
* Add `eachInside` method to recursively iterate all nodes.
* Add `selectors` shortcut to get selectors array.
* Add `toResult` method to `Rule` to simplify work with several input files.
* Clean declarations `value`, rules `selector` and at-rules `params`
by storing spaces in `between` property.
## 0.2 “Duke Dantalion”
* Add source map support.
* Add shortcuts to create nodes.
* Method `process()` now returns object with `css` and `map` keys.
* Origin CSS file option was renamed from `file` to `from`.
* Rename `Node#remove()` method to `removeSelf()` to fix name conflict.
* Node source was moved to `source` property with origin file
and node end position.
* You can set own CSS generate function.
## 0.1 “Count Andromalius”
* Initial release.

View file

@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2013 Andrey Sitnik <andrey@sitnik.ru>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,379 @@
# PostCSS [![Travis Build Status][travis-img]][travis] [![AppVeyor Build Status][appveyor-img]][appveyor] [![Gitter][chat-img]][chat]
<img align="right" width="95" height="95"
title="Philosophers stone, logo of PostCSS"
src="http://postcss.github.io/postcss/logo.svg">
[appveyor-img]: https://img.shields.io/appveyor/ci/ai/postcss.svg?label=windows
[travis-img]: https://img.shields.io/travis/postcss/postcss.svg?label=unix
[chat-img]: https://img.shields.io/badge/Gitter-Join_the_PostCSS_chat-brightgreen.svg
[appveyor]: https://ci.appveyor.com/project/ai/postcss
[travis]: https://travis-ci.org/postcss/postcss
[chat]: https://gitter.im/postcss/postcss
PostCSS is a tool for transforming styles with JS plugins.
These plugins can lint your CSS, support variables and mixins,
transpile future CSS syntax, inline images, and more.
PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba,
and JetBrains. The [Autoprefixer] PostCSS plugin is one of the most popular
CSS processors.
Twitter account: [@postcss](https://twitter.com/postcss).
VK.com page: [postcss](https://vk.com/postcss).
Support / Discussion: [Gitter](https://gitter.im/postcss/postcss).
For PostCSS commercial support (consulting, improving the front-end culture
of your company, PostCSS plugins), contact [Evil Martians](https://evilmartians.com/?utm_source=postcss)
at <surrender@evilmartians.com>.
[Autoprefixer]: https://github.com/postcss/autoprefixer
<a href="https://evilmartians.com/?utm_source=postcss">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
alt="Sponsored by Evil Martians" width="236" height="54">
</a>
## Plugins
Currently, PostCSS has more than 200 plugins. You can find all of the plugins
in the [plugins list] or in the [searchable catalog]. Below is a list
of our favorite plugins — the best demonstrations of what can be built
on top of PostCSS.
If you have any new ideas, [PostCSS plugin development] is really easy.
[searchable catalog]: http://postcss.parts
[plugins list]: https://github.com/postcss/postcss/blob/master/docs/plugins.md
### Solve Global CSS Problem
* [`postcss-use`] allows you to explicitly set PostCSS plugins within CSS
and execute them only for the current file.
* [`postcss-modules`] and [`react-css-modules`] automatically isolate
selectors within components.
* [`postcss-autoreset`] is an alternative to using a global reset
that is better for isolatable components.
* [`postcss-initial`] adds `all: initial` support, which resets
all inherited styles.
* [`cq-prolyfill`] adds container query support, allowing styles that respond
to the width of the parent.
### Use Future CSS, Today
* [`autoprefixer`] adds vendor prefixes, using data from Can I Use.
* [`postcss-cssnext`] allows you to use future CSS features today
(includes `autoprefixer`).
* [`postcss-image-set-polyfill`] emulates [`image-set`] function logic for all browsers
### Better CSS Readability
* [`precss`] contains plugins for Sass-like features, like variables, nesting,
and mixins.
* [`postcss-sorting`] sorts the content of rules and at-rules.
* [`postcss-utilities`] includes the most commonly used shortcuts and helpers.
* [`short`] adds and extends numerous shorthand properties.
### Images and Fonts
* [`postcss-assets`] inserts image dimensions and inlines files.
* [`postcss-sprites`] generates image sprites.
* [`font-magician`] generates all the `@font-face` rules needed in CSS.
* [`postcss-inline-svg`] allows you to inline SVG and customize its styles.
* [`postcss-write-svg`] allows you to write simple SVG directly in your CSS.
### Linters
* [`stylelint`] is a modular stylesheet linter.
* [`stylefmt`] is a tool that automatically formats CSS
according `stylelint` rules.
* [`doiuse`] lints CSS for browser support, using data from Can I Use.
* [`colorguard`] helps you maintain a consistent color palette.
### Other
* [`postcss-rtl`] combines both-directional (left-to-right and right-to-left) styles in one CSS file.
* [`cssnano`] is a modular CSS minifier.
* [`lost`] is a feature-rich `calc()` grid system.
* [`rtlcss`] mirrors styles for right-to-left locales.
[PostCSS plugin development]: https://github.com/postcss/postcss/blob/master/docs/writing-a-plugin.md
[`postcss-inline-svg`]: https://github.com/TrySound/postcss-inline-svg
[`react-css-modules`]: https://github.com/gajus/react-css-modules
[`postcss-autoreset`]: https://github.com/maximkoretskiy/postcss-autoreset
[`postcss-write-svg`]: https://github.com/jonathantneal/postcss-write-svg
[`postcss-utilities`]: https://github.com/ismamz/postcss-utilities
[`postcss-initial`]: https://github.com/maximkoretskiy/postcss-initial
[`postcss-sprites`]: https://github.com/2createStudio/postcss-sprites
[`postcss-modules`]: https://github.com/outpunk/postcss-modules
[`postcss-sorting`]: https://github.com/hudochenkov/postcss-sorting
[`postcss-cssnext`]: http://cssnext.io
[`postcss-image-set-polyfill`]: https://github.com/SuperOl3g/postcss-image-set-polyfill
[`postcss-assets`]: https://github.com/assetsjs/postcss-assets
[`font-magician`]: https://github.com/jonathantneal/postcss-font-magician
[`autoprefixer`]: https://github.com/postcss/autoprefixer
[`cq-prolyfill`]: https://github.com/ausi/cq-prolyfill
[`postcss-rtl`]: https://github.com/vkalinichev/postcss-rtl
[`postcss-use`]: https://github.com/postcss/postcss-use
[`css-modules`]: https://github.com/css-modules/css-modules
[`colorguard`]: https://github.com/SlexAxton/css-colorguard
[`stylelint`]: https://github.com/stylelint/stylelint
[`stylefmt`]: https://github.com/morishitter/stylefmt
[`cssnano`]: http://cssnano.co
[`precss`]: https://github.com/jonathantneal/precss
[`doiuse`]: https://github.com/anandthakker/doiuse
[`rtlcss`]: https://github.com/MohammadYounes/rtlcss
[`short`]: https://github.com/jonathantneal/postcss-short
[`lost`]: https://github.com/peterramsing/lost
[`image-set`]: https://drafts.csswg.org/css-images-3/#image-set-notation
## Syntaxes
PostCSS can transform styles in any syntax, not just CSS.
If there is not yet support for your favorite syntax,
you can write a parser and/or stringifier to extend PostCSS.
* [`sugarss`] is a indent-based syntax like Sass or Stylus.
* [`postcss-scss`] allows you to work with SCSS
*(but does not compile SCSS to CSS)*.
* [`postcss-sass`] allows you to work with Sass
*(but does not compile Sass to CSS)*.
* [`postcss-less`] allows you to work with Less
*(but does not compile LESS to CSS)*.
* [`postcss-less-engine`] allows you to work with Less
*(and DOES compile LESS to CSS using true Less.js evaluation)*.
* [`postcss-js`] allows you to write styles in JS or transform
React Inline Styles, Radium or JSS.
* [`postcss-safe-parser`] finds and fixes CSS syntax errors.
* [`midas`] converts a CSS string to highlighted HTML.
[`sugarss`]: https://github.com/postcss/sugarss
[`postcss-scss`]: https://github.com/postcss/postcss-scss
[`postcss-sass`]: https://github.com/AleshaOleg/postcss-sass
[`postcss-less`]: https://github.com/webschik/postcss-less
[`postcss-less-engine`]: https://github.com/Crunch/postcss-less
[`postcss-js`]: https://github.com/postcss/postcss-js
[`postcss-safe-parser`]: https://github.com/postcss/postcss-safe-parser
[`midas`]: https://github.com/ben-eb/midas
## Articles
* [Some things you may think about PostCSS… and you might be wrong](http://julian.io/some-things-you-may-think-about-postcss-and-you-might-be-wrong)
* [What PostCSS Really Is; What It Really Does](http://davidtheclark.com/its-time-for-everyone-to-learn-about-postcss)
* [PostCSS Guides](http://webdesign.tutsplus.com/series/postcss-deep-dive--cms-889)
More articles and videos you can find on [awesome-postcss](https://github.com/jjaderg/awesome-postcss) list.
## Books
* [Mastering PostCSS for Web Design](https://www.packtpub.com/web-development/mastering-postcss-web-design) by Alex Libby, Packt. (June 2016)
## Usage
You can start using PostCSS in just two steps:
1. Find and add PostCSS extensions for your build tool.
2. [Select plugins] and add them to your PostCSS process.
[Select plugins]: http://postcss.parts
### Webpack
Use [`postcss-loader`] in `webpack.config.js`:
```js
module.exports = {
module: {
loaders: [
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 1,
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: 'inline',
}
}
]
}
]
}
}
```
Then create `postcss.config.js`:
```js
module.exports = {
plugins: [
require('precss'),
require('autoprefixer')
]
}
```
[`postcss-loader`]: https://github.com/postcss/postcss-loader
### Gulp
Use [`gulp-postcss`] and [`gulp-sourcemaps`].
```js
gulp.task('css', function () {
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
return gulp.src('src/**/*.css')
.pipe( sourcemaps.init() )
.pipe( postcss([ require('precss'), require('autoprefixer') ]) )
.pipe( sourcemaps.write('.') )
.pipe( gulp.dest('build/') );
});
```
[`gulp-sourcemaps`]: https://github.com/floridoo/gulp-sourcemaps
[`gulp-postcss`]: https://github.com/postcss/gulp-postcss
### npm run / CLI
To use PostCSS from your command-line interface or with npm scripts
there is [`postcss-cli`].
```sh
postcss --use autoprefixer -c options.json -o main.css css/*.css
```
[`postcss-cli`]: https://github.com/postcss/postcss-cli
### Browser
If you want to compile CSS string in browser (for instance, in live edit
tools like CodePen), just use [Browserify] or [webpack]. They will pack
PostCSS and plugins files into a single file.
To apply PostCSS plugins to React Inline Styles, JSS, Radium
and other [CSS-in-JS], you can use [`postcss-js`] and transforms style objects.
```js
var postcss = require('postcss-js');
var prefixer = postcss.sync([ require('autoprefixer') ]);
prefixer({ display: 'flex' }); //=> { display: ['-webkit-box', '-webkit-flex', '-ms-flexbox', 'flex'] }
```
[`postcss-js`]: https://github.com/postcss/postcss-js
[Browserify]: http://browserify.org/
[webpack]: https://webpack.github.io/
[CSS-in-JS]: https://github.com/MicheleBertoli/css-in-js
### Runners
* **Grunt**: [`grunt-postcss`](https://github.com/nDmitry/grunt-postcss)
* **HTML**: [`posthtml-postcss`](https://github.com/posthtml/posthtml-postcss)
* **Stylus**: [`poststylus`](https://github.com/seaneking/poststylus)
* **Rollup**: [`rollup-plugin-postcss`](https://github.com/egoist/rollup-plugin-postcss)
* **Brunch**: [`postcss-brunch`](https://github.com/brunch/postcss-brunch)
* **Broccoli**: [`broccoli-postcss`](https://github.com/jeffjewiss/broccoli-postcss)
* **Meteor**: [`postcss`](https://atmospherejs.com/juliancwirko/postcss)
* **ENB**: [`enb-postcss`](https://github.com/awinogradov/enb-postcss)
* **Fly**: [`fly-postcss`](https://github.com/postcss/fly-postcss)
* **Start**: [`start-postcss`](https://github.com/start-runner/postcss)
* **Connect/Express**: [`postcss-middleware`](https://github.com/jedmao/postcss-middleware)
### JS API
For other environments, you can use the JS API:
```js
const fs = require('fs');
const postcss = require('postcss');
const precss = require('precss');
const autoprefixer = require('autoprefixer');
fs.readFile('src/app.css', (err, css) => {
postcss([precss, autoprefixer])
.process(css, { from: 'src/app.css', to: 'dest/app.css' })
.then(result => {
fs.writeFile('dest/app.css', result.css);
if ( result.map ) fs.writeFile('dest/app.css.map', result.map);
});
});
```
Read the [PostCSS API documentation] for more details about the JS API.
All PostCSS runners should pass [PostCSS Runner Guidelines].
[PostCSS Runner Guidelines]: https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md
[PostCSS API documentation]: http://api.postcss.org/postcss.html
### Options
Most PostCSS runners accept two parameters:
* An array of plugins.
* An object of options.
Common options:
* `syntax`: an object providing a syntax parser and a stringifier.
* `parser`: a special syntax parser (for example, [SCSS]).
* `stringifier`: a special syntax output generator (for example, [Midas]).
* `map`: [source map options].
* `from`: the input file name (most runners set it automatically).
* `to`: the output file name (most runners set it automatically).
[source map options]: https://github.com/postcss/postcss/blob/master/docs/source-maps.md
[Midas]: https://github.com/ben-eb/midas
[SCSS]: https://github.com/postcss/postcss-scss
### Node.js 0.10 and the Promise API
If you want to run PostCSS in Node.js 0.10, add the [Promise polyfill]:
```js
require('es6-promise').polyfill();
var postcss = require('postcss');
```
[Promise polyfill]: https://github.com/jakearchibald/es6-promise
## Editors & IDE Integration
### Atom
* [`language-postcss`] adds PostCSS and [SugarSS] highlight.
* [`source-preview-postcss`] previews your output CSS in a separate, live pane.
[SugarSS]: https://github.com/postcss/sugarss
### Sublime Text
* [`Syntax-highlighting-for-PostCSS`] adds PostCSS highlight.
[`Syntax-highlighting-for-PostCSS`]: https://github.com/hudochenkov/Syntax-highlighting-for-PostCSS
[`source-preview-postcss`]: https://atom.io/packages/source-preview-postcss
[`language-postcss`]: https://atom.io/packages/language-postcss
### Vim
* [`postcss.vim`] adds PostCSS highlight.
[`postcss.vim`]: https://github.com/stephenway/postcss.vim
### WebStorm
WebStorm 2016.3 [has] built-in PostCSS support.
[has]: https://blog.jetbrains.com/webstorm/2016/08/webstorm-2016-3-early-access-preview/

View file

@ -0,0 +1,195 @@
# PostCSS Plugin Guidelines
A PostCSS plugin is a function that receives and, usually,
transforms a CSS AST from the PostCSS parser.
The rules below are *mandatory* for all PostCSS plugins.
See also [ClojureWerkzs recommendations] for open source projects.
[ClojureWerkzs recommendations]: http://blog.clojurewerkz.org/blog/2013/04/20/how-to-make-your-open-source-project-really-awesome/
## 1. API
### 1.1 Clear name with `postcss-` prefix
The plugins purpose should be clear just by reading its name.
If you wrote a transpiler for CSS 4 Custom Media, `postcss-custom-media`
would be a good name. If you wrote a plugin to support mixins,
`postcss-mixins` would be a good name.
The prefix `postcss-` shows that the plugin is part of the PostCSS ecosystem.
This rule is not mandatory for plugins that can run as independent tools,
without the user necessarily knowing that it is powered by
PostCSS — for example, [cssnext] and [Autoprefixer].
[Autoprefixer]: https://github.com/postcss/autoprefixer
[cssnext]: http://cssnext.io/
### 1.2. Do one thing, and do it well
Do not create multitool plugins. Several small, one-purpose plugins bundled into
a plugin pack is usually a better solution.
For example, [cssnext] contains many small plugins,
one for each W3C specification. And [cssnano] contains a separate plugin
for each of its optimization.
[cssnext]: http://cssnext.io/
[cssnano]: https://github.com/ben-eb/cssnano
### 1.3. Do not use mixins
Preprocessors libraries like Compass provide an API with mixins.
PostCSS plugins are different.
A plugin cannot be just a set of mixins for [postcss-mixins].
To achieve your goal, consider transforming valid CSS
or using custom at-rules and custom properties.
[postcss-mixins]: https://github.com/postcss/postcss-mixins
### 1.4. Create plugin by `postcss.plugin`
By wrapping your function in this method,
you are hooking into a common plugin API:
```js
module.exports = postcss.plugin('plugin-name', function (opts) {
return function (root, result) {
// Plugin code
};
});
```
## 2. Processing
### 2.1. Plugin must be tested
A CI service like [Travis] is also recommended for testing code in
different environments. You should test in (at least) Node.js [active LTS](https://github.com/nodejs/LTS) and current stable version.
[Travis]: https://travis-ci.org/
### 2.2. Use asynchronous methods whenever possible
For example, use `fs.writeFile` instead of `fs.writeFileSync`:
```js
postcss.plugin('plugin-sprite', function (opts) {
return function (root, result) {
return new Promise(function (resolve, reject) {
var sprite = makeSprite();
fs.writeFile(opts.file, function (err) {
if ( err ) return reject(err);
resolve();
})
});
};
});
```
### 2.3. Set `node.source` for new nodes
Every node must have a relevant `source` so PostCSS can generate
an accurate source map.
So if you add new declaration based on some existing declaration, you should
clone the existing declaration in order to save that original `source`.
```js
if ( needPrefix(decl.prop) ) {
decl.cloneBefore({ prop: '-webkit-' + decl.prop });
}
```
You can also set `source` directly, copying from some existing node:
```js
if ( decl.prop === 'animation' ) {
var keyframe = createAnimationByName(decl.value);
keyframes.source = decl.source;
decl.root().append(keyframes);
}
```
### 2.4. Use only the public PostCSS API
PostCSS plugins must not rely on undocumented properties or methods,
which may be subject to change in any minor release. The public API
is described in [API docs].
[API docs]: http://api.postcss.org/
## 3. Errors
### 3.1. Use `node.error` on CSS relevant errors
If you have an error because of input CSS (like an unknown name
in a mixin plugin) you should use `node.error` to create an error
that includes source position:
```js
if ( typeof mixins[name] === 'undefined' ) {
throw decl.error('Unknown mixin ' + name, { plugin: 'postcss-mixins' });
}
```
### 3.2. Use `result.warn` for warnings
Do not print warnings with `console.log` or `console.warn`,
because some PostCSS runner may not allow console output.
```js
if ( outdated(decl.prop) ) {
result.warn(decl.prop + ' is outdated', { node: decl });
}
```
If CSS input is a source of the warning, the plugin must set the `node` option.
## 4. Documentation
### 4.1. Document your plugin in English
PostCSS plugins must have their `README.md` written in English. Do not be afraid
of your English skills, as the open source community will fix your errors.
Of course, you are welcome to write documentation in other languages;
just name them appropriately (e.g. `README.ja.md`).
### 4.2. Include input and output examples
The plugin's `README.md` must contain example input and output CSS.
A clear example is the best way to describe how your plugin works.
The first section of the `README.md` is a good place to put examples.
See [postcss-opacity](https://github.com/iamvdo/postcss-opacity) for an example.
Of course, this guideline does not apply if your plugin does not
transform the CSS.
### 4.3. Maintain a changelog
PostCSS plugins must describe the changes of all their releases
in a separate file, such as `CHANGELOG.md`, `History.md`, or [GitHub Releases].
Visit [Keep A Changelog] for more information about how to write one of these.
Of course, you should be using [SemVer].
[Keep A Changelog]: http://keepachangelog.com/
[GitHub Releases]: https://help.github.com/articles/creating-releases/
[SemVer]: http://semver.org/
### 4.4. Include `postcss-plugin` keyword in `package.json`
PostCSS plugins written for npm must have the `postcss-plugin` keyword
in their `package.json`. This special keyword will be useful for feedback about
the PostCSS ecosystem.
For packages not published to npm, this is not mandatory, but is recommended
if the package format can contain keywords.

View file

@ -0,0 +1,143 @@
# PostCSS Runner Guidelines
A PostCSS runner is a tool that processes CSS through a user-defined list
of plugins; for example, [`postcss-cli`] or [`gulppostcss`].
These rules are mandatory for any such runners.
For single-plugin tools, like [`gulp-autoprefixer`],
these rules are not mandatory but are highly recommended.
See also [ClojureWerkzs recommendations] for open source projects.
[ClojureWerkzs recommendations]: http://blog.clojurewerkz.org/blog/2013/04/20/how-to-make-your-open-source-project-really-awesome/
[`gulp-autoprefixer`]: https://github.com/sindresorhus/gulp-autoprefixer
[`gulppostcss`]: https://github.com/w0rm/gulp-postcss
[`postcss-cli`]: https://github.com/postcss/postcss-cli
## 1. API
### 1.1. Accept functions in plugin parameters
If your runner uses a config file, it must be written in JavaScript, so that
it can support plugins which accept a function, such as [`postcss-assets`]:
```js
module.exports = [
require('postcss-assets')({
cachebuster: function (file) {
return fs.statSync(file).mtime.getTime().toString(16);
}
})
];
```
[`postcss-assets`]: https://github.com/borodean/postcss-assets
## 2. Processing
### 2.1. Set `from` and `to` processing options
To ensure that PostCSS generates source maps and displays better syntax errors,
runners must specify the `from` and `to` options. If your runner does not handle
writing to disk (for example, a gulp transform), you should set both options
to point to the same file:
```js
processor.process({ from: file.path, to: file.path });
```
### 2.2. Use only the asynchronous API
PostCSS runners must use only the asynchronous API.
The synchronous API is provided only for debugging, is slower,
and cant work with asynchronous plugins.
```js
processor.process(opts).then(function (result) {
// processing is finished
});
```
### 2.3. Use only the public PostCSS API
PostCSS runners must not rely on undocumented properties or methods,
which may be subject to change in any minor release. The public API
is described in [API docs].
[API docs]: http://api.postcss.org/
## 3. Output
### 3.1. Dont show JS stack for `CssSyntaxError`
PostCSS runners must not show a stack trace for CSS syntax errors,
as the runner can be used by developers who are not familiar with JavaScript.
Instead, handle such errors gracefully:
```js
processor.process(opts).catch(function (error) {
if ( error.name === 'CssSyntaxError' ) {
process.stderr.write(error.message + error.showSourceCode());
} else {
throw error;
}
});
```
### 3.2. Display `result.warnings()`
PostCSS runners must output warnings from `result.warnings()`:
```js
result.warnings().forEach(function (warn) {
process.stderr.write(warn.toString());
});
```
See also [postcss-log-warnings] and [postcss-messages] plugins.
[postcss-log-warnings]: https://github.com/davidtheclark/postcss-log-warnings
[postcss-messages]: https://github.com/postcss/postcss-messages
### 3.3. Allow the user to write source maps to different files
PostCSS by default will inline source maps in the generated file; however,
PostCSS runners must provide an option to save the source map in a different
file:
```js
if ( result.map ) {
fs.writeFile(opts.to + '.map', result.map.toString());
}
```
## 4. Documentation
### 4.1. Document your runner in English
PostCSS runners must have their `README.md` written in English. Do not be afraid
of your English skills, as the open source community will fix your errors.
Of course, you are welcome to write documentation in other languages;
just name them appropriately (e.g. `README.ja.md`).
### 4.2. Maintain a changelog
PostCSS runners must describe changes of all releases in a separate file,
such as `ChangeLog.md`, `History.md`, or with [GitHub Releases].
Visit [Keep A Changelog] for more information on how to write one of these.
Of course you should use [SemVer].
[Keep A Changelog]: http://keepachangelog.com/
[GitHub Releases]: https://help.github.com/articles/creating-releases/
[SemVer]: http://semver.org/
### 4.3. `postcss-runner` keyword in `package.json`
PostCSS runners written for npm must have the `postcss-runner` keyword
in their `package.json`. This special keyword will be useful for feedback about
the PostCSS ecosystem.
For packages not published to npm, this is not mandatory, but recommended
if the package format is allowed to contain keywords.

View file

@ -0,0 +1,72 @@
# PostCSS and Source Maps
PostCSS has great [source maps] support. It can read and interpret maps
from previous transformation steps, autodetect the format that you expect,
and output both external and inline maps.
To ensure that you generate an accurate source map, you must indicate the input
and output CSS file paths — using the options `from` and `to`, respectively.
To generate a new source map with the default options, simply set `map: true`.
This will generate an inline source map that contains the source content.
If you dont want the map inlined, you can set `map.inline: false`.
```js
processor
.process(css, {
from: 'app.sass.css',
to: 'app.css',
map: { inline: false },
})
.then(function (result) {
result.map //=> '{ "version":3,
// "file":"app.css",
// "sources":["app.sass"],
// "mappings":"AAAA,KAAI" }'
});
```
If PostCSS finds source maps from a previous transformation,
it will automatically update that source map with the same options.
## Options
If you want more control over source map generation, you can define the `map`
option as an object with the following parameters:
* `inline` boolean: indicates that the source map should be embedded
in the output CSS as a Base64-encoded comment. By default, it is `true`.
But if all previous maps are external, not inline, PostCSS will not embed
the map even if you do not set this option.
If you have an inline source map, the `result.map` property will be empty,
as the source map will be contained within the text of `result.css`.
* `prev` string, object, boolean or function: source map content from
a previous processing step (for example, Sass compilation).
PostCSS will try to read the previous source map automatically
(based on comments within the source CSS), but you can use this option
to identify it manually. If desired, you can omit the previous map
with `prev: false`.
* `sourcesContent` boolean: indicates that PostCSS should set the origin
content (for example, Sass source) of the source map. By default,
it is `true`. But if all previous maps do not contain sources content,
PostCSS will also leave it out even if you do not set this option.
* `annotation` boolean or string: indicates that PostCSS should add annotation
comments to the CSS. By default, PostCSS will always add a comment with a path
to the source map. PostCSS will not add annotations to CSS files that
do not contain any comments.
By default, PostCSS presumes that you want to save the source map as
`opts.to + '.map'` and will use this path in the annotation comment.
A different path can be set by providing a string value for `annotation`.
If you have set `inline: true`, annotation cannot be disabled.
* `from` string: by default, PostCSS will set the `sources` property of the map
to the value of the `from` option. If you want to override this behaviour, you
can use `map.from` to explicitly set the source map's `sources` property.
[source maps]: http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/

View file

@ -0,0 +1,231 @@
# How to Write Custom Syntax
PostCSS can transform styles in any syntax, and is not limited to just CSS.
By writing a custom syntax, you can transform styles in any desired format.
Writing a custom syntax is much harder than writing a PostCSS plugin, but
it is an awesome adventure.
There are 3 types of PostCSS syntax packages:
* **Parser** to parse input string to nodes tree.
* **Stringifier** to generate output string by nodes tree.
* **Syntax** contains both parser and stringifier.
## Syntax
A good example of a custom syntax is [SCSS]. Some users may want to transform
SCSS sources with PostCSS plugins, for example if they need to add vendor
prefixes or change the property order. So this syntax should output SCSS from
an SCSS input.
The syntax API is a very simple plain object, with `parse` & `stringify`
functions:
```js
module.exports = {
parse: require('./parse'),
stringify: require('./stringify')
};
```
[SCSS]: https://github.com/postcss/postcss-scss
## Parser
A good example of a parser is [Safe Parser], which parses malformed/broken CSS.
Because there is no point to generate broken output, this package only provides
a parser.
The parser API is a function which receives a string & returns a [`Root`] node.
The second argument is a function which receives an object with PostCSS options.
```js
var postcss = require('postcss');
module.exports = function (css, opts) {
var root = postcss.root();
// Add other nodes to root
return root;
};
```
[Safe Parser]: https://github.com/postcss/postcss-safe-parser
[`Root`]: http://api.postcss.org/Root.html
### Main Theory
There are many books about parsers; but do not worry because CSS syntax is
very easy, and so the parser will be much simpler than a programming language
parser.
The default PostCSS parser contains two steps:
1. [Tokenizer] which reads input string character by character and builds a
tokens array. For example, it joins space symbols to a `['space', '\n ']`
token, and detects strings to a `['string', '"\"{"']` token.
2. [Parser] which reads the tokens array, creates node instances and
builds a tree.
[Tokenizer]: https://github.com/postcss/postcss/blob/master/lib/tokenize.es6
[Parser]: https://github.com/postcss/postcss/blob/master/lib/parser.es6
### Performance
Parsing input is often the most time consuming task in CSS processors. So it
is very important to have a fast parser.
The main rule of optimization is that there is no performance without a
benchmark. You can look at [PostCSS benchmarks] to build your own.
Of parsing tasks, the tokenize step will often take the most time, so its
performance should be prioritized. Unfortunately, classes, functions and
high level structures can slow down your tokenizer. Be ready to write dirty
code with repeated statements. This is why it is difficult to extend the
default [PostCSS tokenizer]; copy & paste will be a necessary evil.
Second optimization is using character codes instead of strings.
```js
// Slow
string[i] === '{';
// Fast
const OPEN_CURLY = 123; // `{'
string.charCodeAt(i) === OPEN_CURLY;
```
Third optimization is “fast jumps”. If you find open quotes, you can find
next closing quote much faster by `indexOf`:
```js
// Simple jump
next = string.indexOf('"', currentPosition + 1);
// Jump by RegExp
regexp.lastIndex = currentPosion + 1;
regexp.text(string);
next = regexp.lastIndex;
```
The parser can be a well written class. There is no need in copy-paste and
hardcore optimization there. You can extend the default [PostCSS parser].
[PostCSS benchmarks]: https://github.com/postcss/benchmark
[PostCSS tokenizer]: https://github.com/postcss/postcss/blob/master/lib/tokenize.es6
[PostCSS parser]: https://github.com/postcss/postcss/blob/master/lib/parser.es6
### Node Source
Every node should have `source` property to generate correct source map.
This property contains `start` and `end` properties with `{ line, column }`,
and `input` property with an [`Input`] instance.
Your tokenizer should save the original position so that you can propagate
the values to the parser, to ensure that the source map is correctly updated.
[`Input`]: https://github.com/postcss/postcss/blob/master/lib/input.es6
### Raw Values
A good PostCSS parser should provide all information (including spaces symbols)
to generate byte-to-byte equal output. It is not so difficult, but respectful
for user input and allow integration smoke tests.
A parser should save all additional symbols to `node.raws` object.
It is an open structure for you, you can add additional keys.
For example, [SCSS parser] saves comment types (`/* */` or `//`)
in `node.raws.inline`.
The default parser cleans CSS values from comments and spaces.
It saves the original value with comments to `node.raws.value.raw` and uses it,
if the node value was not changed.
[SCSS parser]: https://github.com/postcss/postcss-scss
### Tests
Of course, all parsers in the PostCSS ecosystem must have tests.
If your parser just extends CSS syntax (like [SCSS] or [Safe Parser]),
you can use the [PostCSS Parser Tests]. It contains unit & integration tests.
[PostCSS Parser Tests]: https://github.com/postcss/postcss-parser-tests
## Stringifier
A style guide generator is a good example of a stringifier. It generates output
HTML which contains CSS components. For this use case, a parser isn't necessary,
so the package should just contain a stringifier.
The Stringifier API is little bit more complicated, than the parser API.
PostCSS generates a source map, so a stringifier cant just return a string.
It must link every substring with its source node.
A Stringifier is a function which receives [`Root`] node and builder callback.
Then it calls builder with every nodes string and node instance.
```js
module.exports = function (root, builder) {
// Some magic
var string = decl.prop + ':' + decl.value + ';';
builder(string, decl);
// Some science
};
```
### Main Theory
PostCSS [default stringifier] is just a class with a method for each node type
and many methods to detect raw properties.
In most cases it will be enough just to extend this class,
like in [SCSS stringifier].
[default stringifier]: https://github.com/postcss/postcss/blob/master/lib/stringifier.es6
[SCSS stringifier]: https://github.com/postcss/postcss-scss/blob/master/lib/scss-stringifier.es6
### Builder Function
A builder function will be passed to `stringify` function as second argument.
For example, the default PostCSS stringifier class saves it
to `this.builder` property.
Builder receives output substring and source node to append this substring
to the final output.
Some nodes contain other nodes in the middle. For example, a rule has a `{`
at the beginning, many declarations inside and a closing `}`.
For these cases, you should pass a third argument to builder function:
`'start'` or `'end'` string:
```js
this.builder(rule.selector + '{', rule, 'start');
// Stringify declarations inside
this.builder('}', rule, 'end');
```
### Raw Values
A good PostCSS custom syntax saves all symbols and provide byte-to-byte equal
output if there were no changes.
This is why every node has `node.raws` object to store space symbol, etc.
Be careful, because sometimes these raw properties will not be present; some
nodes may be built manually, or may lose their indentation when they are moved
to another parent node.
This is why the default stringifier has a `raw()` method to autodetect raw
properties by other nodes. For example, it will look at other nodes to detect
indent size and them multiply it with the current node depth.
### Tests
A stringifier must have tests too.
You can use unit and integration test cases from [PostCSS Parser Tests].
Just compare input CSS with CSS after your parser and stringifier.
[PostCSS Parser Tests]: https://github.com/postcss/postcss-parser-tests

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,89 @@
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _warnOnce = require('./warn-once');
var _warnOnce2 = _interopRequireDefault(_warnOnce);
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Represents a comment between declarations or statements (rule and at-rules).
*
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*
* @extends Node
*/
var Comment = function (_Node) {
_inherits(Comment, _Node);
function Comment(defaults) {
_classCallCheck(this, Comment);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'comment';
return _this;
}
_createClass(Comment, [{
key: 'left',
get: function get() {
(0, _warnOnce2.default)('Comment#left was deprecated. Use Comment#raws.left');
return this.raws.left;
},
set: function set(val) {
(0, _warnOnce2.default)('Comment#left was deprecated. Use Comment#raws.left');
this.raws.left = val;
}
}, {
key: 'right',
get: function get() {
(0, _warnOnce2.default)('Comment#right was deprecated. Use Comment#raws.right');
return this.raws.right;
},
set: function set(val) {
(0, _warnOnce2.default)('Comment#right was deprecated. Use Comment#raws.right');
this.raws.right = val;
}
/**
* @memberof Comment#
* @member {string} text - the comments text
*/
/**
* @memberof Comment#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node.
* * `left`: the space symbols between `/*` and the comments text.
* * `right`: the space symbols between the comments text.
*/
}]);
return Comment;
}(_node2.default);
exports.default = Comment;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNvbW1lbnQuZXM2Il0sIm5hbWVzIjpbIkNvbW1lbnQiLCJkZWZhdWx0cyIsInR5cGUiLCJyYXdzIiwibGVmdCIsInZhbCIsInJpZ2h0Il0sIm1hcHBpbmdzIjoiOzs7Ozs7QUFBQTs7OztBQUNBOzs7Ozs7Ozs7Ozs7QUFFQTs7Ozs7Ozs7SUFRTUEsTzs7O0FBRUYscUJBQVlDLFFBQVosRUFBc0I7QUFBQTs7QUFBQSxxREFDbEIsaUJBQU1BLFFBQU4sQ0FEa0I7O0FBRWxCLGNBQUtDLElBQUwsR0FBWSxTQUFaO0FBRmtCO0FBR3JCOzs7OzRCQUVVO0FBQ1Asb0NBQVMsb0RBQVQ7QUFDQSxtQkFBTyxLQUFLQyxJQUFMLENBQVVDLElBQWpCO0FBQ0gsUzswQkFFUUMsRyxFQUFLO0FBQ1Ysb0NBQVMsb0RBQVQ7QUFDQSxpQkFBS0YsSUFBTCxDQUFVQyxJQUFWLEdBQWlCQyxHQUFqQjtBQUNIOzs7NEJBRVc7QUFDUixvQ0FBUyxzREFBVDtBQUNBLG1CQUFPLEtBQUtGLElBQUwsQ0FBVUcsS0FBakI7QUFDSCxTOzBCQUVTRCxHLEVBQUs7QUFDWCxvQ0FBUyxzREFBVDtBQUNBLGlCQUFLRixJQUFMLENBQVVHLEtBQVYsR0FBa0JELEdBQWxCO0FBQ0g7O0FBRUQ7Ozs7O0FBS0E7Ozs7Ozs7Ozs7Ozs7Ozs7OztrQkFjV0wsTyIsImZpbGUiOiJjb21tZW50LmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHdhcm5PbmNlIGZyb20gJy4vd2Fybi1vbmNlJztcbmltcG9ydCBOb2RlICAgICBmcm9tICcuL25vZGUnO1xuXG4vKipcbiAqIFJlcHJlc2VudHMgYSBjb21tZW50IGJldHdlZW4gZGVjbGFyYXRpb25zIG9yIHN0YXRlbWVudHMgKHJ1bGUgYW5kIGF0LXJ1bGVzKS5cbiAqXG4gKiBDb21tZW50cyBpbnNpZGUgc2VsZWN0b3JzLCBhdC1ydWxlIHBhcmFtZXRlcnMsIG9yIGRlY2xhcmF0aW9uIHZhbHVlc1xuICogd2lsbCBiZSBzdG9yZWQgaW4gdGhlIGByYXdzYCBwcm9wZXJ0aWVzIGV4cGxhaW5lZCBhYm92ZS5cbiAqXG4gKiBAZXh0ZW5kcyBOb2RlXG4gKi9cbmNsYXNzIENvbW1lbnQgZXh0ZW5kcyBOb2RlIHtcblxuICAgIGNvbnN0cnVjdG9yKGRlZmF1bHRzKSB7XG4gICAgICAgIHN1cGVyKGRlZmF1bHRzKTtcbiAgICAgICAgdGhpcy50eXBlID0gJ2NvbW1lbnQnO1xuICAgIH1cblxuICAgIGdldCBsZWZ0KCkge1xuICAgICAgICB3YXJuT25jZSgnQ29tbWVudCNsZWZ0IHdhcyBkZXByZWNhdGVkLiBVc2UgQ29tbWVudCNyYXdzLmxlZnQnKTtcbiAgICAgICAgcmV0dXJuIHRoaXMucmF3cy5sZWZ0O1xuICAgIH1cblxuICAgIHNldCBsZWZ0KHZhbCkge1xuICAgICAgICB3YXJuT25jZSgnQ29tbWVudCNsZWZ0IHdhcyBkZXByZWNhdGVkLiBVc2UgQ29tbWVudCNyYXdzLmxlZnQnKTtcbiAgICAgICAgdGhpcy5yYXdzLmxlZnQgPSB2YWw7XG4gICAgfVxuXG4gICAgZ2V0IHJpZ2h0KCkge1xuICAgICAgICB3YXJuT25jZSgnQ29tbWVudCNyaWdodCB3YXMgZGVwcmVjYXRlZC4gVXNlIENvbW1lbnQjcmF3cy5yaWdodCcpO1xuICAgICAgICByZXR1cm4gdGhpcy5yYXdzLnJpZ2h0O1xuICAgIH1cblxuICAgIHNldCByaWdodCh2YWwpIHtcbiAgICAgICAgd2Fybk9uY2UoJ0NvbW1lbnQjcmlnaHQgd2FzIGRlcHJlY2F0ZWQuIFVzZSBDb21tZW50I3Jhd3MucmlnaHQnKTtcbiAgICAgICAgdGhpcy5yYXdzLnJpZ2h0ID0gdmFsO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEBtZW1iZXJvZiBDb21tZW50I1xuICAgICAqIEBtZW1iZXIge3N0cmluZ30gdGV4dCAtIHRoZSBjb21tZW504oCZcyB0ZXh0XG4gICAgICovXG5cbiAgICAvKipcbiAgICAgKiBAbWVtYmVyb2YgQ29tbWVudCNcbiAgICAgKiBAbWVtYmVyIHtvYmplY3R9IHJhd3MgLSBJbmZvcm1hdGlvbiB0byBnZW5lcmF0ZSBieXRlLXRvLWJ5dGUgZXF1YWxcbiAgICAgKiAgICAgICAgICAgICAgICAgICAgICAgICBub2RlIHN0cmluZyBhcyBpdCB3YXMgaW4gdGhlIG9yaWdpbiBpbnB1dC5cbiAgICAgKlxuICAgICAqIEV2ZXJ5IHBhcnNlciBzYXZlcyBpdHMgb3duIHByb3BlcnRpZXMsXG4gICAgICogYnV0IHRoZSBkZWZhdWx0IENTUyBwYXJzZXIgdXNlczpcbiAgICAgKlxuICAgICAqICogYGJlZm9yZWA6IHRoZSBzcGFjZSBzeW1ib2xzIGJlZm9yZSB0aGUgbm9kZS5cbiAgICAgKiAqIGBsZWZ0YDogdGhlIHNwYWNlIHN5bWJvbHMgYmV0d2VlbiBgLypgIGFuZCB0aGUgY29tbWVudOKAmXMgdGV4dC5cbiAgICAgKiAqIGByaWdodGA6IHRoZSBzcGFjZSBzeW1ib2xzIGJldHdlZW4gdGhlIGNvbW1lbnTigJlzIHRleHQuXG4gICAgICovXG59XG5cbmV4cG9ydCBkZWZhdWx0IENvbW1lbnQ7XG4iXX0=

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,43 @@
'use strict';
exports.__esModule = true;
exports.default = parse;
var _parser = require('./parser');
var _parser2 = _interopRequireDefault(_parser);
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function parse(css, opts) {
if (opts && opts.safe) {
throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
}
var input = new _input2.default(css, opts);
var parser = new _parser2.default(input);
try {
parser.tokenize();
parser.loop();
} catch (e) {
if (e.name === 'CssSyntaxError' && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
} else if (/\.sass/i.test(opts.from)) {
e.message += '\nYou tried to parse Sass with ' + 'the standard CSS parser; ' + 'try again with the postcss-sass parser';
} else if (/\.less$/i.test(opts.from)) {
e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
}
}
throw e;
}
return parser.root;
}
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInBhcnNlLmVzNiJdLCJuYW1lcyI6WyJwYXJzZSIsImNzcyIsIm9wdHMiLCJzYWZlIiwiRXJyb3IiLCJpbnB1dCIsInBhcnNlciIsInRva2VuaXplIiwibG9vcCIsImUiLCJuYW1lIiwiZnJvbSIsInRlc3QiLCJtZXNzYWdlIiwicm9vdCJdLCJtYXBwaW5ncyI6Ijs7O2tCQUd3QkEsSzs7QUFIeEI7Ozs7QUFDQTs7Ozs7O0FBRWUsU0FBU0EsS0FBVCxDQUFlQyxHQUFmLEVBQW9CQyxJQUFwQixFQUEwQjtBQUNyQyxRQUFLQSxRQUFRQSxLQUFLQyxJQUFsQixFQUF5QjtBQUNyQixjQUFNLElBQUlDLEtBQUosQ0FBVSw4QkFDQSw0Q0FEVixDQUFOO0FBRUg7O0FBRUQsUUFBSUMsUUFBUSxvQkFBVUosR0FBVixFQUFlQyxJQUFmLENBQVo7O0FBRUEsUUFBSUksU0FBUyxxQkFBV0QsS0FBWCxDQUFiO0FBQ0EsUUFBSTtBQUNBQyxlQUFPQyxRQUFQO0FBQ0FELGVBQU9FLElBQVA7QUFDSCxLQUhELENBR0UsT0FBT0MsQ0FBUCxFQUFVO0FBQ1IsWUFBS0EsRUFBRUMsSUFBRixLQUFXLGdCQUFYLElBQStCUixJQUEvQixJQUF1Q0EsS0FBS1MsSUFBakQsRUFBd0Q7QUFDcEQsZ0JBQUssV0FBV0MsSUFBWCxDQUFnQlYsS0FBS1MsSUFBckIsQ0FBTCxFQUFrQztBQUM5QkYsa0JBQUVJLE9BQUYsSUFBYSxvQ0FDQSwyQkFEQSxHQUVBLHdDQUZiO0FBR0gsYUFKRCxNQUlPLElBQUssVUFBVUQsSUFBVixDQUFlVixLQUFLUyxJQUFwQixDQUFMLEVBQWlDO0FBQ3BDRixrQkFBRUksT0FBRixJQUFhLG9DQUNBLDJCQURBLEdBRUEsd0NBRmI7QUFHSCxhQUpNLE1BSUEsSUFBSyxXQUFXRCxJQUFYLENBQWdCVixLQUFLUyxJQUFyQixDQUFMLEVBQWtDO0FBQ3JDRixrQkFBRUksT0FBRixJQUFhLG9DQUNBLDJCQURBLEdBRUEsd0NBRmI7QUFHSDtBQUNKO0FBQ0QsY0FBTUosQ0FBTjtBQUNIOztBQUVELFdBQU9ILE9BQU9RLElBQWQ7QUFDSCIsImZpbGUiOiJwYXJzZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBQYXJzZXIgZnJvbSAnLi9wYXJzZXInO1xuaW1wb3J0IElucHV0ICBmcm9tICcuL2lucHV0JztcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gcGFyc2UoY3NzLCBvcHRzKSB7XG4gICAgaWYgKCBvcHRzICYmIG9wdHMuc2FmZSApIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdPcHRpb24gc2FmZSB3YXMgcmVtb3ZlZC4gJyArXG4gICAgICAgICAgICAgICAgICAgICAgICAnVXNlIHBhcnNlcjogcmVxdWlyZShcInBvc3Rjc3Mtc2FmZS1wYXJzZXJcIiknKTtcbiAgICB9XG5cbiAgICBsZXQgaW5wdXQgPSBuZXcgSW5wdXQoY3NzLCBvcHRzKTtcblxuICAgIGxldCBwYXJzZXIgPSBuZXcgUGFyc2VyKGlucHV0KTtcbiAgICB0cnkge1xuICAgICAgICBwYXJzZXIudG9rZW5pemUoKTtcbiAgICAgICAgcGFyc2VyLmxvb3AoKTtcbiAgICB9IGNhdGNoIChlKSB7XG4gICAgICAgIGlmICggZS5uYW1lID09PSAnQ3NzU3ludGF4RXJyb3InICYmIG9wdHMgJiYgb3B0cy5mcm9tICkge1xuICAgICAgICAgICAgaWYgKCAvXFwuc2NzcyQvaS50ZXN0KG9wdHMuZnJvbSkgKSB7XG4gICAgICAgICAgICAgICAgZS5tZXNzYWdlICs9ICdcXG5Zb3UgdHJpZWQgdG8gcGFyc2UgU0NTUyB3aXRoICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndGhlIHN0YW5kYXJkIENTUyBwYXJzZXI7ICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHJ5IGFnYWluIHdpdGggdGhlIHBvc3Rjc3Mtc2NzcyBwYXJzZXInO1xuICAgICAgICAgICAgfSBlbHNlIGlmICggL1xcLnNhc3MvaS50ZXN0KG9wdHMuZnJvbSkgKSB7XG4gICAgICAgICAgICAgICAgZS5tZXNzYWdlICs9ICdcXG5Zb3UgdHJpZWQgdG8gcGFyc2UgU2FzcyB3aXRoICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndGhlIHN0YW5kYXJkIENTUyBwYXJzZXI7ICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHJ5IGFnYWluIHdpdGggdGhlIHBvc3Rjc3Mtc2FzcyBwYXJzZXInO1xuICAgICAgICAgICAgfSBlbHNlIGlmICggL1xcLmxlc3MkL2kudGVzdChvcHRzLmZyb20pICkge1xuICAgICAgICAgICAgICAgIGUubWVzc2FnZSArPSAnXFxuWW91IHRyaWVkIHRvIHBhcnNlIExlc3Mgd2l0aCAnICtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJ3RoZSBzdGFuZGFyZCBDU1MgcGFyc2VyOyAnICtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJ3RyeSBhZ2FpbiB3aXRoIHRoZSBwb3N0Y3NzLWxlc3MgcGFyc2VyJztcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICB0aHJvdyBlO1xuICAgIH1cblxuICAgIHJldHVybiBwYXJzZXIucm9vdDtcbn1cbiJdfQ==

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show more