first commit

This commit is contained in:
s.golasch
2023-08-01 13:49:46 +02:00
commit 1fc239fd54
20238 changed files with 3112246 additions and 0 deletions

21
build/node_modules/imagemin-svgo/index.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
'use strict';
const bufferFrom = require('buffer-from');
const isSvg = require('is-svg');
const SVGO = require('svgo');
module.exports = opts => buf => {
opts = Object.assign({multipass: true}, opts);
if (!isSvg(buf)) {
return Promise.resolve(buf);
}
if (Buffer.isBuffer(buf)) {
buf = buf.toString();
}
const svgo = new SVGO(opts);
// TODO: Use `Buffer.from` when targeting Node.js >=6
return svgo.optimize(buf).then(res => bufferFrom(res.data));
};

9
build/node_modules/imagemin-svgo/license generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) imagemin (github.com/imagemin)
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 @@
../esprima/bin/esparse.js

View File

@@ -0,0 +1 @@
../esprima/bin/esvalidate.js

View File

@@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
build/node_modules/imagemin-svgo/node_modules/.bin/svgo generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../svgo/bin/svgo

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015-present Sergey Berezhnoy <veged@ya.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,340 @@
# Command-Option-Argument
Yet another parser for command line options.
[![NPM Status][npm-img]][npm]
[![Travis Status][test-img]][travis]
[![AppVeyor Status][appveyor-img]][appveyor]
[![Coverage Status][coverage-img]][coveralls]
[![Dependency Status][dependency-img]][david]
[npm]: https://www.npmjs.org/package/coa
[npm-img]: https://img.shields.io/npm/v/coa.svg
[travis]: https://travis-ci.org/veged/coa
[test-img]: https://img.shields.io/travis/veged/coa.svg
[appveyor]: https://ci.appveyor.com/project/zxqfox/coa
[appveyor-img]: https://ci.appveyor.com/api/projects/status/github/veged/coa?svg=true
[coveralls]: https://coveralls.io/r/veged/coa
[coverage-img]: https://img.shields.io/coveralls/veged/coa.svg
[david]: https://david-dm.org/veged/coa
[dependency-img]: http://img.shields.io/david/veged/coa.svg
## What is it?
COA is a parser for command line options that aim to get maximum profit from formalization your program API.
Once you write definition in terms of commands, options and arguments you automaticaly get:
* Command line help text
* Program API for use COA-based programs as modules
* Shell completion
### Other features
* Rich types for options and arguments, such as arrays, boolean flags and required
* Commands can be async throught using promising (powered by [Q](https://github.com/kriskowal/q))
* Easy submoduling some existing commands to new top-level one
* Combined validation and complex parsing of values
### TODO
* Localization
* Shell-mode
* Configs
* Aliases
* Defaults
## Examples
````javascript
require('coa').Cmd() // main (top level) command declaration
.name(process.argv[1]) // set top level command name from program name
.title('My awesome command line util') // title for use in text messages
.helpful() // make command "helpful", i.e. options -h --help with usage message
.opt() // add some option
.name('version') // name for use in API
.title('Version') // title for use in text messages
.short('v') // short key: -v
.long('version') // long key: --version
.flag() // for options without value
.act(function(opts) { // add action for option
// return message as result of action
return JSON.parse(require('fs').readFileSync(__dirname + '/package.json'))
.version;
})
.end() // end option chain and return to main command
.cmd().name('subcommand').apply(require('./subcommand').COA).end() // load subcommand from module
.cmd() // inplace subcommand declaration
.name('othercommand').title('Awesome other subcommand').helpful()
.opt()
.name('input').title('input file, required')
.short('i').long('input')
.val(function(v) { // validator function, also for translate simple values
return require('fs').createReadStream(v) })
.req() // make option required
.end() // end option chain and return to command
.end() // end subcommand chain and return to parent command
.run(process.argv.slice(2)); // parse and run on process.argv
````
````javascript
// subcommand.js
exports.COA = function() {
this
.title('Awesome subcommand').helpful()
.opt()
.name('output').title('output file')
.short('o').long('output')
.output() // use default preset for "output" option declaration
.end()
};
````
## API reference
### Cmd
Command is a top level entity. Commands may have options and arguments.
#### Cmd.api
Returns object containing all its subcommands as methods to use from other programs.<br>
**@returns** *{Object}*
#### Cmd.name
Set a canonical command identifier to be used anywhere in the API.<br>
**@param** *String* `_name` command name<br>
**@returns** *COA.Cmd* `this` instance (for chainability)
#### Cmd.title
Set a long description for command to be used anywhere in text messages.<br>
**@param** *String* `_title` command title<br>
**@returns** *COA.Cmd* `this` instance (for chainability)
#### Cmd.cmd
Create new or add existing subcommand for current command.<br>
**@param** *COA.Cmd* `[cmd]` existing command instance<br>
**@returns** *COA.Cmd* new or added subcommand instance
#### Cmd.opt
Create option for current command.<br>
**@returns** *COA.Opt* `new` option instance
#### Cmd.arg
Create argument for current command.<br>
**@returns** *COA.Opt* `new` argument instance
#### Cmd.act
Add (or set) action for current command.<br>
**@param** *Function* `act` action function,
invoked in the context of command instance
and has the parameters:<br>
- *Object* `opts` parsed options<br>
- *Array* `args` parsed arguments<br>
- *Object* `res` actions result accumulator<br>
It can return rejected promise by Cmd.reject (in case of error)
or any other value treated as result.<br>
**@param** *{Boolean}* [force=false] flag for set action instead add to existings<br>
**@returns** *COA.Cmd* `this` instance (for chainability)
#### Cmd.apply
Apply function with arguments in context of command instance.<br>
**@param** *Function* `fn`<br>
**@param** *Array* `args`<br>
**@returns** *COA.Cmd* `this` instance (for chainability)
#### Cmd.comp
Set custom additional completion for current command.<br>
**@param** *Function* `fn` completion generation function,
invoked in the context of command instance.
Accepts parameters:<br>
- *Object* `opts` completion options<br>
It can return promise or any other value treated as result.<br>
**@returns** *COA.Cmd* `this` instance (for chainability)
#### Cmd.helpful
Make command "helpful", i.e. add -h --help flags for print usage.<br>
**@returns** *COA.Cmd* `this` instance (for chainability)
#### Cmd.completable
Adds shell completion to command, adds "completion" subcommand, that makes all the magic.<br>
Must be called only on root command.<br>
**@returns** *COA.Cmd* `this` instance (for chainability)
#### Cmd.usage
Build full usage text for current command instance.<br>
**@returns** *String* `usage` text
#### Cmd.run
Parse arguments from simple format like NodeJS process.argv
and run ahead current program, i.e. call process.exit when all actions done.<br>
**@param** *Array* `argv`<br>
**@returns** *COA.Cmd* `this` instance (for chainability)
#### Cmd.invoke
Invoke specified (or current) command using provided options and arguments.<br>
**@param** *String|Array* `cmds` subcommand to invoke (optional)<br>
**@param** *Object* `opts` command options (optional)<br>
**@param** *Object* `args` command arguments (optional)<br>
**@returns** *Q.Promise*
#### Cmd.reject
Return reject of actions results promise.<br>
Use in .act() for return with error.<br>
**@param** *Object* `reason` reject reason<br>
You can customize toString() method and exitCode property
of reason object.<br>
**@returns** *Q.promise* rejected promise
#### Cmd.end
Finish chain for current subcommand and return parent command instance.<br>
**@returns** *COA.Cmd* `parent` command
### Opt
Option is a named entity. Options may have short and long keys for use from command line.<br>
**@namespace**<br>
**@class** Presents option
#### Opt.name
Set a canonical option identifier to be used anywhere in the API.<br>
**@param** *String* `_name` option name<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.title
Set a long description for option to be used anywhere in text messages.<br>
**@param** *String* `_title` option title<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.short
Set a short key for option to be used with one hyphen from command line.<br>
**@param** *String* `_short`<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.long
Set a short key for option to be used with double hyphens from command line.<br>
**@param** *String* `_long`<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.flag
Make an option boolean, i.e. option without value.<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.arr
Makes an option accepts multiple values.<br>
Otherwise, the value will be used by the latter passed.<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.req
Makes an option req.<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.only
Makes an option to act as a command,
i.e. program will exit just after option action.<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.val
Set a validation (or value) function for argument.<br>
Value from command line passes through before becoming available from API.<br>
Using for validation and convertion simple types to any values.<br>
**@param** *Function* `_val` validating function,
invoked in the context of option instance
and has one parameter with value from command line<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.def
Set a default value for option.
Default value passed through validation function as ordinary value.<br>
**@param** *Object* `_def`<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.input
Make option value inputting stream.
It's add useful validation and shortcut for STDIN.
**@returns** *{COA.Opt}* `this` instance (for chainability)
#### Opt.output
Make option value outputing stream.<br>
It's add useful validation and shortcut for STDOUT.<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.act
Add action for current option command.
This action is performed if the current option
is present in parsed options (with any value).<br>
**@param** *Function* `act` action function,
invoked in the context of command instance
and has the parameters:<br>
- *Object* `opts` parsed options<br>
- *Array* `args` parsed arguments<br>
- *Object* `res` actions result accumulator<br>
It can return rejected promise by Cmd.reject (in case of error)
or any other value treated as result.<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.comp
Set custom additional completion for current option.<br>
**@param** *Function* `fn` completion generation function,
invoked in the context of command instance.
Accepts parameters:<br>
- *Object* `opts` completion options<br>
It can return promise or any other value treated as result.<br>
**@returns** *COA.Opt* `this` instance (for chainability)
#### Opt.end
Finish chain for current option and return parent command instance.<br>
**@returns** *COA.Cmd* `parent` command
### Arg
Argument is a unnamed entity.<br>
From command line arguments passed as list of unnamed values.
#### Arg.name
Set a canonical argument identifier to be used anywhere in text messages.<br>
**@param** *String* `_name` argument name<br>
**@returns** *COA.Arg* `this` instance (for chainability)
#### Arg.title
Set a long description for argument to be used anywhere in text messages.<br>
**@param** *String* `_title` argument title<br>
**@returns** *COA.Arg* `this` instance (for chainability)
#### Arg.arr
Makes an argument accepts multiple values.<br>
Otherwise, the value will be used by the latter passed.<br>
**@returns** *COA.Arg* `this` instance (for chainability)
#### Arg.req
Makes an argument req.<br>
**@returns** *COA.Arg* `this` instance (for chainability)
#### Arg.val
Set a validation (or value) function for argument.<br>
Value from command line passes through before becoming available from API.<br>
Using for validation and convertion simple types to any values.<br>
**@param** *Function* `_val` validating function,
invoked in the context of argument instance
and has one parameter with value from command line<br>
**@returns** *COA.Arg* `this` instance (for chainability)
#### Arg.def
Set a default value for argument.
Default value passed through validation function as ordinary value.<br>
**@param** *Object* `_def`<br>
**@returns** *COA.Arg* `this` instance (for chainability)
#### Arg.output
Make argument value outputing stream.<br>
It's add useful validation and shortcut for STDOUT.<br>
**@returns** *COA.Arg* `this` instance (for chainability)
#### Arg.comp
Set custom additional completion for current argument.<br>
**@param** *Function* `fn` completion generation function,
invoked in the context of command instance.
Accepts parameters:<br>
- *Object* `opts` completion options<br>
It can return promise or any other value treated as result.<br>
**@returns** *COA.Arg* `this` instance (for chainability)
#### Arg.end
Finish chain for current option and return parent command instance.<br>
**@returns** *COA.Cmd* `parent` command

View File

@@ -0,0 +1,316 @@
# Command-Option-Argument
[![build status](https://secure.travis-ci.org/veged/coa.png)](http://travis-ci.org/veged/coa)
## Что это?
COA — парсер параметров командной строки, позволяющий извлечь максимум пользы от формального API вашей программы.
Как только вы опишете определение в терминах команд, параметров и аргументов, вы автоматически получите:
* Справку для командной строки
* API для использования программы как модуля в COA-совместимых программах
* Автодополнение для командной строки
### Прочие возможности
* Широкий выбор настроек для параметров и аргументов, включая множественные значения, логические значения и обязательность параметров
* Возможность асинхронного исполнения команд, используя промисы (используется библиотека [Q](https://github.com/kriskowal/q))
* Простота использования существующих команд как подмодулей для новых команд
* Комбинированная валидация и анализ сложных значений
## Примеры
````javascript
require('coa').Cmd() // декларация команды верхнего уровня
.name(process.argv[1]) // имя команды верхнего уровня, берем из имени программы
.title('Жутко полезная утилита для командной строки') // название для использования в справке и сообщениях
.helpful() // добавляем поддержку справки командной строки (-h, --help)
.opt() // добавляем параметр
.name('version') // имя параметра для использования в API
.title('Version') // текст для вывода в сообщениях
.short('v') // короткое имя параметра: -v
.long('version') // длинное имя параметра: --version
.flag() // параметр не требует ввода значения
.act(function(opts) { // действия при вызове аргумента
// результатом является вывод текстового сообщения
return JSON.parse(require('fs').readFileSync(__dirname + '/package.json'))
.version;
})
.end() // завершаем определение параметра и возвращаемся к определению верхнего уровня
.cmd().name('subcommand').apply(require('./subcommand').COA).end() // загрузка подкоманды из модуля
.cmd() // добавляем еще одну подкоманду
.name('othercommand').title('Еще одна полезная подпрограмма').helpful()
.opt()
.name('input').title('input file, required')
.short('i').long('input')
.val(function(v) { // функция-валидатор, также может использоваться для трансформации значений параметров
return require('fs').createReadStream(v) })
.req() // параметр является обязательным
.end() // завершаем определение параметра и возвращаемся к определению команды
.end() // завершаем определение подкоманды и возвращаемся к определению команды верхнего уровня
.run(process.argv.slice(2)); // разбираем process.argv и запускаем
````
````javascript
// subcommand.js
exports.COA = function() {
this
.title('Полезная подпрограмма').helpful()
.opt()
.name('output').title('output file')
.short('o').long('output')
.output() // использовать стандартную настройку для параметра вывода
.end()
};
````
## API
### Cmd
Команда — сущность верхнего уровня. У команды могут быть определены параметры и аргументы.
#### Cmd.api
Возвращает объект, который можно использовать в других программах. Подкоманды являются методами этого объекта.<br>
**@returns** *{Object}*
#### Cmd.name
Определяет канонический идентификатор команды, используемый в вызовах API.<br>
**@param** *String* `_name` имя команды<br>
**@returns** *COA.Cmd* `this` экземпляр команды (для поддержки цепочки методов)
#### Cmd.title
Определяет название команды, используемый в текстовых сообщениях.<br>
**@param** *String* `_title` название команды<br>
**@returns** *COA.Cmd* `this` экземпляр команды (для поддержки цепочки методов)
#### Cmd.cmd
Создает новую подкоманду или добавляет ранее определенную подкоманду к текущей команде.<br>
**@param** *COA.Cmd* `[cmd]` экземпляр ранее определенной подкоманды<br>
**@returns** *COA.Cmd* экземпляр новой или ранее определенной подкоманды
#### Cmd.opt
Создает параметр для текущей команды.<br>
**@returns** *COA.Opt* `new` экземпляр параметра
#### Cmd.arg
Создает аргумент для текущей команды.<br>
**@returns** *COA.Opt* `new` экземпляр аргумента
#### Cmd.act
Добавляет (или создает) действие для текущей команды.<br>
**@param** *Function* `act` функция,
выполняемая в контексте экземпляра текущей команды
и принимающая следующие параметры:<br>
- *Object* `opts` параметры команды<br>
- *Array* `args` аргументы команды<br>
- *Object* `res` объект-аккумулятор результатов<br>
Функция может вернуть проваленный промис из Cmd.reject (в случае ошибки)
или любое другое значение, рассматриваемое как результат.<br>
**@param** *{Boolean}* [force=false] флаг, назначающий немедленное исполнение вместо добавления к списку существующих действий<br>
**@returns** *COA.Cmd* `this` экземпляр команды (для поддержки цепочки методов)
#### Cmd.apply
Исполняет функцию с переданными аргументами в контексте экземпляра текущей команды.<br>
**@param** *Function* `fn`<br>
**@param** *Array* `args`<br>
**@returns** *COA.Cmd* `this` экземпляр команды (для поддержки цепочки методов)
#### Cmd.comp
Назначает кастомную функцию автодополнения для текущей команды.<br>
**@param** *Function* `fn` функция-генератор автодополнения,
исполняемая в контексте текущей команды.
Принимает параметры:<br>
- *Object* `opts` параметры<br>
Может возвращать промис или любое другое значение, рассматриваемое как результат исполнения команды.<br>
**@returns** *COA.Cmd* `this` экземпляр команды (для поддержки цепочки методов)
#### Cmd.helpful
Ставит флаг поддержки справки командной строки, т.е. вызов команды с параметрами -h --help выводит справку по работе с командой.<br>
**@returns** *COA.Cmd* `this` экземпляр команды (для поддержки цепочки методов)
#### Cmd.completable
Добавляет поддержку автодополнения командной строки. Добавляется подкоманда "completion", которая выполняет все необходимые действия.<br>
Может быть добавлен только для главной команды.<br>
**@returns** *COA.Cmd* `this` экземпляр команды (для поддержки цепочки методов)
#### Cmd.usage
Возвращает текст справки по использованию команды для текущего экземпляра.<br>
**@returns** *String* `usage` Текст справки по использованию
#### Cmd.run
Разбирает аргументы из значения, возвращаемого NodeJS process.argv,
и запускает текущую программу, т.е. вызывает process.exit после завершения
всех действий.<br>
**@param** *Array* `argv`<br>
**@returns** *COA.Cmd* `this` экземпляр команды (для поддержки цепочки методов)
#### Cmd.invoke
Исполняет переданную (или текущую) команду с указанными параметрами и аргументами.<br>
**@param** *String|Array* `cmds` подкоманда для исполнения (необязательно)<br>
**@param** *Object* `opts` параметры, передаваемые команде (необязательно)<br>
**@param** *Object* `args` аргументы, передаваемые команде (необязательно)<br>
**@returns** *Q.Promise*
#### Cmd.reject
Проваливает промисы, возращенные в действиях.<br>
Используется в .act() для возврата с ошибкой.<br>
**@param** *Object* `reason` причина провала<br>
Вы можете определить метод toString() и свойство toString()
объекта причины провала.<br>
**@returns** *Q.promise* проваленный промис
#### Cmd.end
Завершает цепочку методов текущей подкоманды и возвращает экземпляр родительской команды.<br>
**@returns** *COA.Cmd* `parent` родительская команда
### Opt
Параметр — именованная сущность. У параметра может быть определено короткое или длинное имя для использования из командной строки.<br>
**@namespace**<br>
**@class** Переданный параметр
#### Opt.name
Определяет канонический идентификатор параметра, используемый в вызовах API.<br>
**@param** *String* `_name` имя параметра<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.title
Определяет описание для параметра, используемое в текстовых сообщениях.<br>
**@param** *String* `_title` название параметра<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.short
Назначает ключ для короткого имени параметра, передаваемого из командной строки с одинарным дефисом (например, `-v`).<br>
**@param** *String* `_short`<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.long
Назначает ключ для длинного имени параметра, передаваемого из командной строки с двойным дефисом (например, `--version`).<br>
**@param** *String* `_long`<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.flag
Помечает параметр как логический, т.е. параметр не имеющий значения.<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.arr
Помечает параметр как принимающий множественные значения.<br>
Иначе будет использовано последнее переданное значение параметра.<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.req
Помечает параметр как обязательный.<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.only
Интерпретирует параметр как команду,
т.е. программа будет завершена сразу после выполнения параметра.<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.val
Назначает функцию валидации (или трансформации значения) для значения параметра.<br>
Значение, полученное из командной строки, передается в функцию-валидатор прежде чем оно станет доступно из API.<br>
Используется для валидации и трансформации введенных данных.<br>
**@param** *Function* `_val` функция валидации,
исполняемая в контексте экземпляра параметра
и принимающая в качестве единственного параметра значение, полученное
из командной строки<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.def
Назначает значение параметра по умолчанию. Это значение также передается
в функцию валидации как обычное значение.<br>
**@param** *Object* `_def`<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.input
Помечает параметр как принимающий ввод пользователя. <br>
Позволяет использовать валидацию для STDIN.<br>
**@returns** *{COA.Opt}* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.output
Помечает параметр как вывод.<br>
Позволяет использовать валидацию для STDOUT.<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.act
Добавляет (или создает) действие для текущего параметра команды.
Это действие будет выполнено, если текущий параметр есть
в списке полученных параметров (с любым значением).<br>
**@param** *Function* `act` функция, выполняемая в контексте
экземпляра текущей команды и принимающая следующие параметры:<br>
- *Object* `opts` параметры команды<br>
- *Array* `args` аргументы команды<br>
- *Object* `res` объект-аккумулятор результатов<br>
Функция может вернуть проваленный промис из Cmd.reject (в случае ошибки)
или любое другое значение, рассматриваемое как результат.<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.comp
Назначает кастомную функцию автодополнения для текущей команды.<br>
**@param** *Function* `fn` функция-генератор автодоплнения, исполняемая в
контексте экземпляра команды.
Принимает параметры:<br>
- *Object* `opts` параметры автодополнения<br>
Может возвращать промис или любое другое значение, рассматриваемое как результат исполнения команды.<br>
**@returns** *COA.Opt* `this` экземпляр параметра (для поддержки цепочки методов)
#### Opt.end
Завершает цепочку методов текущего параметра и возвращает экземпляр родительской команды.<br>
**@returns** *COA.Cmd* `parent` родительская команда
### Arg
Аргумент — неименованная сущность.<br>
Аргументы передаются из командной строки как список неименованных значений.
#### Arg.name
Определяет канонический идентификатор аргумента, используемый в вызовах API.<br>
**@param** *String* `_name` имя аргумента<br>
**@returns** *COA.Arg* `this` экземпляр аргумента (для поддержки цепочки методов)
#### Arg.title
Определяет описание для аргумента, используемое в текстовых сообщениях.<br>
**@param** *String* `_title` описание аргумента<br>
**@returns** *COA.Arg* `this` экземпляр аргумента (для поддержки цепочки методов)
#### Arg.arr
Помечает аргумент как принимающий множественные значения.<br>
Иначе будет использовано последнее переданное значение аргумента.<br>
**@returns** *COA.Arg* `this` экземпляр аргумента (для поддержки цепочки методов)
#### Arg.req
Помечает аргумент как обязательный.<br>
**@returns** *COA.Arg* `this` экземпляр аргумента (для поддержки цепочки методов)
#### Arg.val
Назначает функцию валидации (или трансформации значения) для аргумента.<br>
Значение, полученное из командной строки, передается в функцию-валидатор прежде чем оно станет доступно из API.<br>
Используется для валидации и трансформации введенных данных.<br>
**@param** *Function* `_val` функция валидации,
исполняемая в контексте экземпляра аргумента
и принимающая в качестве единственного параметра значение, полученное
из командной строки<br>
**@returns** *COA.Opt* `this` экземпляр аргумента (для поддержки цепочки методов)
#### Arg.def
Назначает дефолтное значение для аргумента. Дефолтное значение передается
в функцию валидации как обычное значение.<br>
**@param** *Object* `_def`<br>
**@returns** *COA.Arg* `this` экземпляр аргумента (для поддержки цепочки методов)
#### Arg.output
Помечает параметр как вывод.<br>
Позволяет назначить валидацию для STDOUT.<br>
**@returns** *COA.Arg* `this` экземпляр аргумента (для поддержки цепочки методов)
#### Arg.comp
Назначает кастомную функцию автодополнения для текущего аргумента.<br>
**@param** *Function* `fn` функция-генератор автодоплнения,
исполняемая в контексте текущей команды.
Принимает параметры:<br>
- *Object* `opts` параметры
Может возвращать промис или любое другое значение, рассматриваемое как результат исполнения команды.<br>
**@returns** *COA.Arg* `this` экземпляр аргумента (для поддержки цепочки методов)
#### Arg.end
Завершает цепочку методов текущего аргумента и возвращает экземпляр родительской команды.<br>
**@returns** *COA.Cmd* `parent` родительская команда

View File

@@ -0,0 +1 @@
module.exports = require('./lib');

View File

@@ -0,0 +1,58 @@
'use strict';
const
CoaParam = require('./coaparam'),
Color = require('./color');
/**
* Argument
*
* Unnamed entity. From command line arguments passed as list of unnamed values.
*
* @class Arg
* @extends CoaParam
*/
module.exports = class Arg extends CoaParam {
/**
* @constructs
* @param {COA.Cmd} cmd - parent command
*/
constructor(cmd) {
super(cmd);
this._cmd._args.push(this);
}
_saveVal(args, val) {
this._val && (val = this._val(val));
const name = this._name;
this._arr
? (args[name] || (args[name] = [])).push(val)
: (args[name] = val);
return val;
}
_parse(arg, args) {
return this._saveVal(args, arg);
}
_checkParsed(opts, args) {
return !args.hasOwnProperty(this._name);
}
_usage() {
const res = [];
res.push(Color('lpurple', this._name.toUpperCase()), ' : ', this._title);
this._req && res.push(' ', Color('lred', '(required)'));
return res.join('');
}
_requiredText() {
return `Missing required argument:\n ${this._usage()}`;
}
};

View File

@@ -0,0 +1,492 @@
'use strict';
const
UTIL = require('util'),
PATH = require('path'),
EOL = require('os').EOL,
Q = require('q'),
CoaObject = require('./coaobject'),
Color = require('./color'),
Opt = require('./opt'),
Arg = require('./arg'),
completion = require('./completion');
/**
* Command
*
* Top level entity. Commands may have options and arguments.
*
* @namespace
* @class Cmd
* @extends CoaObject
*/
class Cmd extends CoaObject {
/**
* @constructs
* @param {COA.Cmd} [cmd] parent command
*/
constructor(cmd) {
super(cmd);
this._parent(cmd);
this._cmds = [];
this._cmdsByName = {};
this._opts = [];
this._optsByKey = {};
this._args = [];
this._api = null;
this._ext = false;
}
static create(cmd) {
return new Cmd(cmd);
}
/**
* Returns object containing all its subcommands as methods
* to use from other programs.
*
* @returns {Object}
*/
get api() {
// Need _this here because of passed arguments into _api
const _this = this;
this._api || (this._api = function () {
return _this.invoke.apply(_this, arguments);
});
const cmds = this._cmdsByName;
Object.keys(cmds).forEach(cmd => { this._api[cmd] = cmds[cmd].api; });
return this._api;
}
_parent(cmd) {
this._cmd = cmd || this;
this.isRootCmd ||
cmd._cmds.push(this) &&
this._name &&
(this._cmd._cmdsByName[this._name] = this);
return this;
}
get isRootCmd() {
return this._cmd === this;
}
/**
* Set a canonical command identifier to be used anywhere in the API.
*
* @param {String} name - command name
* @returns {COA.Cmd} - this instance (for chainability)
*/
name(name) {
super.name(name);
this.isRootCmd ||
(this._cmd._cmdsByName[name] = this);
return this;
}
/**
* Create new or add existing subcommand for current command.
*
* @param {COA.Cmd} [cmd] existing command instance
* @returns {COA.Cmd} new subcommand instance
*/
cmd(cmd) {
return cmd?
cmd._parent(this)
: new Cmd(this);
}
/**
* Create option for current command.
*
* @returns {COA.Opt} new option instance
*/
opt() {
return new Opt(this);
}
/**
* Create argument for current command.
*
* @returns {COA.Opt} new argument instance
*/
arg() {
return new Arg(this);
}
/**
* Add (or set) action for current command.
*
* @param {Function} act - action function,
* invoked in the context of command instance
* and has the parameters:
* - {Object} opts - parsed options
* - {String[]} args - parsed arguments
* - {Object} res - actions result accumulator
* It can return rejected promise by Cmd.reject (in case of error)
* or any other value treated as result.
* @param {Boolean} [force=false] flag for set action instead add to existings
* @returns {COA.Cmd} - this instance (for chainability)
*/
act(act, force) {
if(!act) return this;
(!this._act || force) && (this._act = []);
this._act.push(act);
return this;
}
/**
* Make command "helpful", i.e. add -h --help flags for print usage.
*
* @returns {COA.Cmd} - this instance (for chainability)
*/
helpful() {
return this.opt()
.name('help')
.title('Help')
.short('h')
.long('help')
.flag()
.only()
.act(function() {
return this.usage();
})
.end();
}
/**
* Adds shell completion to command, adds "completion" subcommand,
* that makes all the magic.
* Must be called only on root command.
*
* @returns {COA.Cmd} - this instance (for chainability)
*/
completable() {
return this.cmd()
.name('completion')
.apply(completion)
.end();
}
/**
* Allow command to be extendable by external node.js modules.
*
* @param {String} [pattern] Pattern of node.js module to find subcommands at.
* @returns {COA.Cmd} - this instance (for chainability)
*/
extendable(pattern) {
this._ext = pattern || true;
return this;
}
_exit(msg, code) {
return process.once('exit', function() {
msg && console[code === 0 ? 'log' : 'error'](msg);
process.exit(code || 0);
});
}
/**
* Build full usage text for current command instance.
*
* @returns {String} usage text
*/
usage() {
const res = [];
this._title && res.push(this._fullTitle());
res.push('', 'Usage:');
this._cmds.length
&& res.push([
'', '', Color('lred', this._fullName()), Color('lblue', 'COMMAND'),
Color('lgreen', '[OPTIONS]'), Color('lpurple', '[ARGS]')
].join(' '));
(this._opts.length + this._args.length)
&& res.push([
'', '', Color('lred', this._fullName()),
Color('lgreen', '[OPTIONS]'), Color('lpurple', '[ARGS]')
].join(' '));
res.push(
this._usages(this._cmds, 'Commands'),
this._usages(this._opts, 'Options'),
this._usages(this._args, 'Arguments')
);
return res.join(EOL);
}
_usage() {
return Color('lblue', this._name) + ' : ' + this._title;
}
_usages(os, title) {
if(!os.length) return;
return ['', title + ':']
.concat(os.map(o => ` ${o._usage()}`))
.join(EOL);
}
_fullTitle() {
return `${this.isRootCmd? '' : this._cmd._fullTitle() + EOL}${this._title}`;
}
_fullName() {
return `${this.isRootCmd? '' : this._cmd._fullName() + ' '}${PATH.basename(this._name)}`;
}
_ejectOpt(opts, opt) {
const pos = opts.indexOf(opt);
if(pos === -1) return;
return opts[pos]._arr?
opts[pos] :
opts.splice(pos, 1)[0];
}
_checkRequired(opts, args) {
if(this._opts.some(opt => opt._only && opts.hasOwnProperty(opt._name))) return;
const all = this._opts.concat(this._args);
let i;
while(i = all.shift())
if(i._req && i._checkParsed(opts, args))
return this.reject(i._requiredText());
}
_parseCmd(argv, unparsed) {
unparsed || (unparsed = []);
let i,
optSeen = false;
while(i = argv.shift()) {
i.indexOf('-') || (optSeen = true);
if(optSeen || !/^\w[\w-_]*$/.test(i)) {
unparsed.push(i);
continue;
}
let pkg, cmd = this._cmdsByName[i];
if(!cmd && this._ext) {
if(this._ext === true) {
pkg = i;
let c = this;
while(true) { // eslint-disable-line
pkg = c._name + '-' + pkg;
if(c.isRootCmd) break;
c = c._cmd;
}
} else if(typeof this._ext === 'string')
pkg = ~this._ext.indexOf('%s')?
UTIL.format(this._ext, i) :
this._ext + i;
let cmdDesc;
try {
cmdDesc = require(pkg);
} catch(e) {
// Dummy
}
if(cmdDesc) {
if(typeof cmdDesc === 'function') {
this.cmd().name(i).apply(cmdDesc).end();
} else if(typeof cmdDesc === 'object') {
this.cmd(cmdDesc);
cmdDesc.name(i);
} else throw new Error('Error: Unsupported command declaration type, '
+ 'should be a function or COA.Cmd() object');
cmd = this._cmdsByName[i];
}
}
if(cmd) return cmd._parseCmd(argv, unparsed);
unparsed.push(i);
}
return { cmd : this, argv : unparsed };
}
_parseOptsAndArgs(argv) {
const opts = {},
args = {},
nonParsedOpts = this._opts.concat(),
nonParsedArgs = this._args.concat();
let res, i;
while(i = argv.shift()) {
if(i !== '--' && i[0] === '-') {
const m = i.match(/^(--\w[\w-_]*)=(.*)$/);
if(m) {
i = m[1];
this._optsByKey[i]._flag || argv.unshift(m[2]);
}
const opt = this._ejectOpt(nonParsedOpts, this._optsByKey[i]);
if(!opt) return this.reject(`Unknown option: ${i}`);
if(Q.isRejected(res = opt._parse(argv, opts))) return res;
continue;
}
i === '--' && (i = argv.splice(0));
Array.isArray(i) || (i = [i]);
let a;
while(a = i.shift()) {
let arg = nonParsedArgs.shift();
if(!arg) return this.reject(`Unknown argument: ${a}`);
arg._arr && nonParsedArgs.unshift(arg);
if(Q.isRejected(res = arg._parse(a, args))) return res;
}
}
return {
opts : this._setDefaults(opts, nonParsedOpts),
args : this._setDefaults(args, nonParsedArgs)
};
}
_setDefaults(params, desc) {
for(const item of desc)
item._def &&
!params.hasOwnProperty(item._name) &&
item._saveVal(params, item._def);
return params;
}
_processParams(params, desc) {
const notExists = [];
for(const item of desc) {
const n = item._name;
if(!params.hasOwnProperty(n)) {
notExists.push(item);
continue;
}
const vals = Array.isArray(params[n])? params[n] : [params[n]];
delete params[n];
let res;
for(const v of vals)
if(Q.isRejected(res = item._saveVal(params, v)))
return res;
}
return this._setDefaults(params, notExists);
}
_parseArr(argv) {
return Q.when(this._parseCmd(argv), p =>
Q.when(p.cmd._parseOptsAndArgs(p.argv), r => ({
cmd : p.cmd,
opts : r.opts,
args : r.args
})));
}
_do(inputPromise) {
return Q.when(inputPromise, input => {
return [this._checkRequired]
.concat(input.cmd._act || [])
.reduce((res, act) =>
Q.when(res, prev => act.call(input.cmd, input.opts, input.args, prev)),
undefined);
});
}
/**
* Parse arguments from simple format like NodeJS process.argv
* and run ahead current program, i.e. call process.exit when all actions done.
*
* @param {String[]} argv - arguments
* @returns {COA.Cmd} - this instance (for chainability)
*/
run(argv) {
argv || (argv = process.argv.slice(2));
const cb = code =>
res => res?
this._exit(res.stack || res.toString(), (res.hasOwnProperty('exitCode')? res.exitCode : code) || 0) :
this._exit();
Q.when(this.do(argv), cb(0), cb(1)).done();
return this;
}
/**
* Invoke specified (or current) command using provided
* options and arguments.
*
* @param {String|String[]} [cmds] - subcommand to invoke (optional)
* @param {Object} [opts] - command options (optional)
* @param {Object} [args] - command arguments (optional)
* @returns {Q.Promise}
*/
invoke(cmds, opts, args) {
cmds || (cmds = []);
opts || (opts = {});
args || (args = {});
typeof cmds === 'string' && (cmds = cmds.split(' '));
if(arguments.length < 3 && !Array.isArray(cmds)) {
args = opts;
opts = cmds;
cmds = [];
}
return Q.when(this._parseCmd(cmds), p => {
if(p.argv.length)
return this.reject(`Unknown command: ${cmds.join(' ')}`);
return Q.all([
this._processParams(opts, this._opts),
this._processParams(args, this._args)
]).spread((_opts, _args) =>
this._do({
cmd : p.cmd,
opts : _opts,
args : _args
})
.fail(res => (res && res.exitCode === 0)?
res.toString() :
this.reject(res)));
});
}
}
/**
* Convenient function to run command from tests.
*
* @param {String[]} argv - arguments
* @returns {Q.Promise}
*/
Cmd.prototype.do = function(argv) {
return this._do(this._parseArr(argv || []));
};
module.exports = Cmd;

View File

@@ -0,0 +1,100 @@
'use strict';
const Q = require('q');
/**
* COA Object
*
* Base class for all COA-related objects
*
* --------|-----|-----|-----
* | Cmd | Opt | Arg
* --------|-----|-----|-----
* name | ✓ | ✓ | ✓
* title | ✓ | ✓ | ✓
* comp | ✓ | ✓ | ✓
* reject | ✓ | ✓ | ✓
* end | ✓ | ✓ | ✓
* apply | ✓ | ✓ | ✓
*
* @class CoaObject
*/
module.exports = class CoaObject {
constructor(cmd) {
this._cmd = cmd;
this._name = null;
this._title = null;
this._comp = null;
}
/**
* Set a canonical identifier to be used anywhere in the API.
*
* @param {String} name - command, option or argument name
* @returns {COA.CoaObject} - this instance (for chainability)
*/
name(name) {
this._name = name;
return this;
}
/**
* Set a long description to be used anywhere in text messages.
* @param {String} title - human readable entity title
* @returns {COA.CoaObject} - this instance (for chainability)
*/
title(title) {
this._title = title;
return this;
}
/**
* Set custom additional completion for current object.
*
* @param {Function} comp - completion generation function,
* invoked in the context of object instance.
* Accepts parameters:
* - {Object} opts - completion options
* It can return promise or any other value threated as a result.
* @returns {COA.CoaObject} - this instance (for chainability)
*/
comp(comp) {
this._comp = comp;
return this;
}
/**
* Apply function with arguments in a context of object instance.
*
* @param {Function} fn - body
* @param {Array.<*>} args... - arguments
* @returns {COA.CoaObject} - this instance (for chainability)
*/
apply(fn) {
arguments.length > 1?
fn.apply(this, [].slice.call(arguments, 1))
: fn.call(this);
return this;
}
/**
* Return reject of actions results promise with error code.
* Use in .act() for return with error.
* @param {Object} reason - reject reason
* You can customize toString() method and exitCode property
* of reason object.
* @returns {Q.promise} rejected promise
*/
reject(reason) {
return Q.reject(reason);
}
/**
* Finish chain for current subcommand and return parent command instance.
* @returns {COA.Cmd} parent command
*/
end() {
return this._cmd;
}
};

View File

@@ -0,0 +1,125 @@
'use strict';
const fs = require('fs');
const CoaObject = require('./coaobject');
/**
* COA Parameter
*
* Base class for options and arguments
*
* --------|-----|-----|-----
* | Cmd | Opt | Arg
* --------|-----|-----|-----
* arr | | ✓ | ✓
* req | | ✓ | ✓
* val | | ✓ | ✓
* def | | ✓ | ✓
* input | | ✓ | ✓
* output | | ✓ | ✓
*
* @class CoaParam
* @extends CoaObject
*/
module.exports = class CoaParam extends CoaObject {
constructor(cmd) {
super(cmd);
this._arr = false;
this._req = false;
this._val = undefined;
this._def = undefined;
}
/**
* Makes a param accepts multiple values.
* Otherwise, the value will be used by the latter passed.
*
* @returns {COA.CoaParam} - this instance (for chainability)
*/
arr() {
this._arr = true;
return this;
}
/**
* Makes a param required.
*
* @returns {COA.CoaParam} - this instance (for chainability)
*/
req() {
this._req = true;
return this;
}
/**
* Set a validation (or value) function for param.
* Value from command line passes through before becoming available from API.
* Using for validation and convertion simple types to any values.
*
* @param {Function} val - validating function,
* invoked in the context of option instance
* and has one parameter with value from command line.
* @returns {COA.CoaParam} - this instance (for chainability)
*/
val(val) {
this._val = val;
return this;
}
/**
* Set a default value for param.
* Default value passed through validation function as ordinary value.
*
* @param {*} def - default value of function generator
* @returns {COA.CoaParam} - this instance (for chainability)
*/
def(def) {
this._def = def;
return this;
}
/**
* Make option value inputting stream.
* It's add useful validation and shortcut for STDIN.
*
* @returns {COA.CoaParam} - this instance (for chainability)
*/
input() {
process.stdin.pause();
return this
.def(process.stdin)
.val(function(v) {
if(typeof v !== 'string')
return v;
if(v === '-')
return process.stdin;
const s = fs.createReadStream(v, { encoding : 'utf8' });
s.pause();
return s;
});
}
/**
* Make option value outputing stream.
* It's add useful validation and shortcut for STDOUT.
*
* @returns {COA.CoaParam} - this instance (for chainability)
*/
output() {
return this
.def(process.stdout)
.val(function(v) {
if(typeof v !== 'string')
return v;
if(v === '-')
return process.stdout;
return fs.createWriteStream(v, { encoding : 'utf8' });
});
}
};

View File

@@ -0,0 +1,22 @@
'use strict';
const colors = {
black : '30',
dgray : '1;30',
red : '31',
lred : '1;31',
green : '32',
lgreen : '1;32',
brown : '33',
yellow : '1;33',
blue : '34',
lblue : '1;34',
purple : '35',
lpurple : '1;35',
cyan : '36',
lcyan : '1;36',
lgray : '37',
white : '1;37'
};
module.exports = (c, str) => `\x1B[${colors[c]}m${str}\x1B[m`;

View File

@@ -0,0 +1,176 @@
'use strict';
const constants = require('constants');
const fs = require('fs');
const path = require('path');
const Q = require('q');
const shell = require('./shell');
const escape = shell.escape;
const unescape = shell.unescape;
/**
* Most of the code adopted from the npm package shell completion code.
* See https://github.com/isaacs/npm/blob/master/lib/completion.js
*
* @returns {COA.CoaObject}
*/
module.exports = function completion() {
return this
.title('Shell completion')
.helpful()
.arg()
.name('raw')
.title('Completion words')
.arr()
.end()
.act((opts, args) => {
if(process.platform === 'win32') {
const e = new Error('shell completion not supported on windows');
e.code = 'ENOTSUP';
e.errno = constants.ENOTSUP;
return this.reject(e);
}
// if the COMP_* isn't in the env, then just dump the script
if((process.env.COMP_CWORD == null)
|| (process.env.COMP_LINE == null)
|| (process.env.COMP_POINT == null)) {
return dumpScript(this._cmd._name);
}
console.error('COMP_LINE: %s', process.env.COMP_LINE);
console.error('COMP_CWORD: %s', process.env.COMP_CWORD);
console.error('COMP_POINT: %s', process.env.COMP_POINT);
console.error('args: %j', args.raw);
// completion opts
opts = getOpts(args.raw);
// cmd
const parsed = this._cmd._parseCmd(opts.partialWords);
return Q.when(complete(parsed.cmd, parsed.opts), compls => {
console.error('filtered: %j', compls);
return console.log(compls.map(escape).join('\n'));
});
});
};
function dumpScript(name) {
const defer = Q.defer();
fs.readFile(path.resolve(__dirname, 'completion.sh'), 'utf8', function(err, d) {
if(err) return defer.reject(err);
d = d.replace(/{{cmd}}/g, path.basename(name)).replace(/^\#\!.*?\n/, '');
process.stdout.on('error', onError);
process.stdout.write(d, () => defer.resolve());
});
return defer.promise;
function onError(err) {
// Darwin is a real dick sometimes.
//
// This is necessary because the "source" or "." program in
// bash on OS X closes its file argument before reading
// from it, meaning that you get exactly 1 write, which will
// work most of the time, and will always raise an EPIPE.
//
// Really, one should not be tossing away EPIPE errors, or any
// errors, so casually. But, without this, `. <(cmd completion)`
// can never ever work on OS X.
if(err.errno !== constants.EPIPE) return defer.reject(err);
process.stdout.removeListener('error', onError);
return defer.resolve();
}
}
function getOpts(argv) {
// get the partial line and partial word, if the point isn't at the end
// ie, tabbing at: cmd foo b|ar
const line = process.env.COMP_LINE;
const w = +process.env.COMP_CWORD;
const point = +process.env.COMP_POINT;
const words = argv.map(unescape);
const word = words[w];
const partialLine = line.substr(0, point);
const partialWords = words.slice(0, w);
// figure out where in that last word the point is
let partialWord = argv[w] || '';
let i = partialWord.length;
while(partialWord.substr(0, i) !== partialLine.substr(-1 * i) && i > 0) i--;
partialWord = unescape(partialWord.substr(0, i));
partialWord && partialWords.push(partialWord);
return {
line,
w,
point,
words,
word,
partialLine,
partialWords,
partialWord
};
}
function complete(cmd, opts) {
let optWord, optPrefix,
compls = [];
// Complete on cmds
if(opts.partialWord.indexOf('-'))
compls = Object.keys(cmd._cmdsByName);
// Complete on required opts without '-' in last partial word
// (if required not already specified)
//
// Commented out because of uselessness:
// -b, --block suggest results in '-' on cmd line;
// next completion suggest all options, because of '-'
//.concat Object.keys(cmd._optsByKey).filter (v) -> cmd._optsByKey[v]._req
else {
// complete on opt values: --opt=| case
const m = opts.partialWord.match(/^(--\w[\w-_]*)=(.*)$/);
if(m) {
optWord = m[1];
optPrefix = optWord + '=';
} else
// complete on opts
// don't complete on opts in case of --opt=val completion
// TODO: don't complete on opts in case of unknown arg after commands
// TODO: complete only on opts with arr() or not already used
// TODO: complete only on full opts?
compls = Object.keys(cmd._optsByKey);
}
// complete on opt values: next arg case
opts.partialWords[opts.w - 1].indexOf('-') || (optWord = opts.partialWords[opts.w - 1]);
// complete on opt values: completion
let opt;
optWord
&& (opt = cmd._optsByKey[optWord])
&& !opt._flag
&& opt._comp
&& (compls = Q.join(compls,
Q.when(opt._comp(opts),
(c, o) => c.concat(o.map(v => (optPrefix || '') + v)))));
// TODO: complete on args values (context aware, custom completion?)
// custom completion on cmds
cmd._comp && (compls = Q.join(compls, Q.when(cmd._comp(opts)), (c, o) => c.concat(o)));
// TODO: context aware custom completion on cmds, opts and args
// (can depend on already entered values, especially options)
return Q.when(compls, complitions => {
console.error('partialWord: %s', opts.partialWord);
console.error('compls: %j', complitions);
return compls.filter(c => c.indexOf(opts.partialWord) === 0);
});
}

View File

@@ -0,0 +1,43 @@
#!/usr/bin/env bash
###-begin-{{cmd}}-completion-###
#
# {{cmd}} command completion script
#
# Installation: {{cmd}} completion >> ~/.bashrc (or ~/.zshrc)
# Or, maybe: {{cmd}} completion > /usr/local/etc/bash_completion.d/{{cmd}}
#
COMP_WORDBREAKS=${COMP_WORDBREAKS/=/}
COMP_WORDBREAKS=${COMP_WORDBREAKS/@/}
export COMP_WORDBREAKS
if complete &>/dev/null; then
_{{cmd}}_completion () {
local si="$IFS"
IFS=$'\n' COMPREPLY=($(COMP_CWORD="$COMP_CWORD" \
COMP_LINE="$COMP_LINE" \
COMP_POINT="$COMP_POINT" \
{{cmd}} completion -- "${COMP_WORDS[@]}" \
2>/dev/null)) || return $?
IFS="$si"
}
complete -F _{{cmd}}_completion {{cmd}}
elif compctl &>/dev/null; then
_{{cmd}}_completion () {
local cword line point words si
read -Ac words
read -cn cword
let cword-=1
read -l line
read -ln point
si="$IFS"
IFS=$'\n' reply=($(COMP_CWORD="$cword" \
COMP_LINE="$line" \
COMP_POINT="$point" \
{{cmd}} completion -- "${words[@]}" \
2>/dev/null)) || return $?
IFS="$si"
}
compctl -K _{{cmd}}_completion {{cmd}}
fi
###-end-{{cmd}}-completion-###

View File

@@ -0,0 +1,14 @@
const
Cmd = require('./cmd'),
Opt = require('./opt'),
Arg = require('./arg'),
shell = require('./shell');
module.exports = {
Cmd : Cmd.create,
Opt : Opt.create,
Arg : Arg.create,
classes : { Cmd, Opt, Arg },
shell,
require
};

View File

@@ -0,0 +1,155 @@
'use strict';
const
Q = require('q'),
CoaParam = require('./coaparam'),
Color = require('./color');
/**
* Option
*
* Named entity. Options may have short and long keys for use from command line.
*
* @namespace
* @class Opt
* @extends CoaParam
*/
module.exports = class Opt extends CoaParam {
/**
* @constructs
* @param {COA.Cmd} cmd - parent command
*/
constructor(cmd) {
super(cmd);
this._short = null;
this._long = null;
this._flag = false;
this._only = false;
this._cmd._opts.push(this);
}
/**
* Set a short key for option to be used with one hyphen from command line.
*
* @param {String} short - short name
* @returns {COA.Opt} - this instance (for chainability)
*/
short(short) {
this._short = short;
this._cmd._optsByKey[`-${short}`] = this;
return this;
}
/**
* Set a short key for option to be used with double hyphens from command line.
*
* @param {String} long - long name
* @returns {COA.Opt} - this instance (for chainability)
*/
long(long) {
this._long = long;
this._cmd._optsByKey[`--${long}`] = this;
return this;
}
/**
* Make an option boolean, i.e. option without value.
*
* @returns {COA.Opt} - this instance (for chainability)
*/
flag() {
this._flag = true;
return this;
}
/**
* Makes an option to act as a command,
* i.e. program will exit just after option action.
*
* @returns {COA.Opt} - this instance (for chainability)
*/
only() {
this._only = true;
return this;
}
/**
* Add action for current option command.
* This action is performed if the current option
* is present in parsed options (with any value).
*
* @param {Function} act - action function,
* invoked in the context of command instance
* and has the parameters:
* - {Object} opts - parsed options
* - {Array} args - parsed arguments
* - {Object} res - actions result accumulator
* It can return rejected promise by Cmd.reject (in case of error)
* or any other value treated as result.
* @returns {COA.Opt} - this instance (for chainability)
*/
act(act) {
// Need function here for arguments
const opt = this;
this._cmd.act(function(opts) {
if(!opts.hasOwnProperty(opt._name)) return;
const res = act.apply(this, arguments);
if(!opt._only) return res;
return Q.when(res, out => this.reject({
toString : () => out.toString(),
exitCode : 0
}));
});
return this;
}
_saveVal(opts, val) {
this._val && (val = this._val(val));
const name = this._name;
this._arr
? (opts[name] || (opts[name] = [])).push(val)
: (opts[name] = val);
return val;
}
_parse(argv, opts) {
return this._saveVal(opts, this._flag ? true : argv.shift());
}
_checkParsed(opts) {
return !opts.hasOwnProperty(this._name);
}
_usage() {
const res = [],
nameStr = this._name.toUpperCase();
if(this._short) {
res.push('-', Color('lgreen', this._short));
this._flag || res.push(' ' + nameStr);
res.push(', ');
}
if(this._long) {
res.push('--', Color('green', this._long));
this._flag || res.push('=' + nameStr);
}
res.push(' : ', this._title);
this._req && res.push(' ', Color('lred', '(required)'));
return res.join('');
}
_requiredText() {
return `Missing required option:\n ${this._usage()}`;
}
};

View File

@@ -0,0 +1,14 @@
module.exports = { escape, unescape };
function unescape(w) {
w = w.charAt(0) === '"'
? w.replace(/^"|([^\\])"$/g, '$1')
: w.replace(/\\ /g, ' ');
return w.replace(/\\("|'|\$|`|\\)/g, '$1');
}
function escape(w) {
w = w.replace(/(["'$`\\])/g,'\\$1');
return w.match(/\s+/) ? `"${w}"` : w;
}

View File

@@ -0,0 +1,93 @@
{
"_from": "coa@~2.0.0",
"_id": "coa@2.0.0",
"_inBundle": false,
"_integrity": "sha1-r4geviFPwpvuTp52tJVrYTIpVUY=",
"_location": "/imagemin-svgo/coa",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "coa@~2.0.0",
"name": "coa",
"escapedName": "coa",
"rawSpec": "~2.0.0",
"saveSpec": null,
"fetchSpec": "~2.0.0"
},
"_requiredBy": [
"/imagemin-svgo/svgo"
],
"_resolved": "https://registry.npmjs.org/coa/-/coa-2.0.0.tgz",
"_shasum": "af881ebe214fc29bee4e9e76b4956b6132295546",
"_spec": "coa@~2.0.0",
"_where": "/Users/asciidisco/Desktop/asciidisco.com/build/node_modules/imagemin-svgo/node_modules/svgo",
"author": {
"name": "Sergey Berezhnoy",
"email": "veged@ya.ru",
"url": "http://github.com/veged"
},
"bugs": {
"url": "https://github.com/veged/coa/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Sergey Belov",
"email": "peimei@ya.ru",
"url": "http://github.com/arikon"
}
],
"dependencies": {
"q": "^1.1.2"
},
"deprecated": false,
"description": "Command-Option-Argument: Yet another parser for command line options.",
"devDependencies": {
"chai": "~1.7.2",
"coveralls": "^2.11.16",
"eslint": "^3.15.0",
"eslint-config-pedant": "^0.8.0",
"mocha": "~1.21.4",
"nyc": "^10.1.2"
},
"directories": {
"lib": "./lib"
},
"engines": {
"node": ">= 4.0"
},
"files": [
"lib/",
"index.js",
"README.ru.md"
],
"homepage": "http://github.com/veged/coa",
"license": "MIT",
"maintainers": [
{
"name": "Sergey Berezhnoy",
"email": "veged@ya.ru",
"url": "http://github.com/veged"
},
{
"name": "Sergey Belov",
"email": "peimei@ya.ru",
"url": "http://github.com/arikon"
}
],
"name": "coa",
"repository": {
"type": "git",
"url": "git://github.com/veged/coa.git"
},
"scripts": {
"clean": "rm -r .nyc_output coverage",
"coverage": "nyc --reporter=text --reporter=html mocha; echo; echo 'Open coverage/index.html file in your browser'",
"coveralls": "nyc report --reporter=text-lcov | coveralls",
"lint": "eslint .",
"pretest": "npm run lint",
"test": "nyc mocha"
},
"version": "2.0.0"
}

View File

@@ -0,0 +1,369 @@
## 3.4.0 (November 3, 2017)
- Added percent sign removal for zero percentages for some properties that is safe (@RubaXa, #286)
- Removed unit removal for zero values in `-ms-flex` due it breaks flex in IE10/11 (#362)
- Improved performance of selectors comparison (@smelukov, #343)
## 3.3.1 (October 17, 2017)
- Fixed merge of `position` declarations when `sticky` fallback is using (@gruzzilkin, #356)
## 3.3.0 (October 12, 2017)
- Migrated to [CSSTree](https://github.com/csstree/csstree) `1.0.0-alpha25`
- Changed AST format (see [CSSTree change log](https://github.com/csstree/csstree/blob/master/HISTORY.md) for details)
- Fixed performance issue when generate CSS with source map (quadratic increase in time depending on the size of the CSS)
## 3.2.0 (September 10, 2017)
- Fixed named color compression to apply only when an identifier is guaranteed to be a color
- Added lifting of `@keyframes` to the beginning of style sheet (chunk), but after `@charset` and `@import` rules
- Added removal of `@keyframes`, `@media` and `@supports` with no prelude
- Added removal of duplicate `@keyframes` (#202)
- Added new option `forceMediaMerge` to force media rules merging. It's unsafe in general, but works fine in many cases. Use it on your own risk (#350)
- Bumped `CSSTree` to `1.0.0-alpha23`
## 3.1.1 (April 25, 2017)
- Fixed crash on a number processing when it used not in a list (#335)
## 3.1.0 (April 24, 2017)
- Implemented optimisation for `none` keyword in `border` and `outline` properties (@zoobestik, #41)
- Implemented replacing `rgba(x, x, x, 0)` to `transparent`
- Fixed plus sign omitting for numbers following identifier, hex color, number or unicode range, since it can change the meaning of CSS (e.g. `calc(1px+2px)` has been optimized to `calc(1px2px)` before, now it stays the same)
- Improved usage filtering for nested selectors (i.e. for `:nth-*()`, `:has()`, `:matches` and other pseudos)
- Implemented `blacklist` filtering in usage (#334, see [Black list filtering](https://github.com/css/csso#black-list-filtering))
- Improved white space removing, now white spaces are removing in the beginning and at the ending of sequences, and between stylesheet and block nodes
- Bumped `CSSTree` to `1.0.0-alpha19`
## 3.0.1 (March 14, 2017)
- Fixed declaration merging when declaration contains an `!important`
## 3.0.0 (March 13, 2017)
- Migrated to [CSSTree](https://github.com/csstree/csstree) as AST backend and exposed its API behind `syntax` property
- Extracted CLI into standalone package [css/csso-cli](https://github.com/css/csso-cli)
## 2.3.1 (January 6, 2017)
- Added `\0` IE hack support (#320)
## 2.3.0 (October 25, 2016)
- Added `beforeCompress` and `afterCompress` options support (#316)
- Fixed crash on empty argument in function (#317)
## 2.2.1 (July 25, 2016)
- Fixed shorthand optimisation issue when value has a color value or something unknown (#311)
- Fixed `cursor` broken fallback (#306)
## 2.2.0 (June 23, 2016)
- Implement AST cloning by adding `clone()` [function](https://github.com/css/csso#cloneast) and `clone` [option](https://github.com/css/csso#compressast-options) for `compress()` function (#296)
- Fix parse and translate attribute selector with flags but w/o operator (i.e. `[attrName i]`)
- Don't merge rules with flagged attribute selectors with others (#291)
- Take in account functions when merge TRBL-properties (#297, thanks to @ArturAralin)
- Improve partial merge (#304)
- Tweak scanner, reduce code deoptimizations and other small improvements
## 2.1.1 (May 11, 2016)
- Fix wrong declaration with `\9` hack merge (#295)
## 2.1.0 (May 8, 2016)
- New option `comments` to specify what comments to left: `exclamation`, `first-exclamation` and `none`
- Add `offset` to CSS parse error details
- Fix token `offset` computation
## 2.0.0 (April 5, 2016)
- No more `gonzales` AST format and related code
- `minify()` and `minifyBlock()` is always return an object as result now (i.e. `{ css: String, map: SourceMapGenerator or null }`)
- `parse()`
- Returns AST in new format (so called `internal`)
- Dynamic scanner implemented
- New AST format + dynamic scanner = performance boost and less memory consumption
- No more `context` argument, context should be specified via `options`
- Supported contexts now: `stylesheet`, `atrule`, `atruleExpression`, `ruleset`, `selector`, `simpleSelector`, `block`, `declaration` and `value`
- Drop `needPositions` option, `positions` option should be used instead
- Drop `needInfo` option, `info` object is attaching to nodes when some information is requested by `options`
- `options` should be an object, otherwise it treats as empty object
- `compress()`
- No more AST converting (performance boost and less memory consumption)
- Drop `outputAst` option
- Returns an object as result instead of AST (i.e. `{ ast: Object }`)
- Drop methods: `justDoIt()`, `stringify()`, `cleanInfo()`
## 1.8.1 (March 30, 2016)
- Don't remove spaces after function/braces/urls since unsafe (#289)
## 1.8.0 (March 24, 2016)
- Usage data support:
- Filter rulesets by tag names, class names and ids white lists.
- More aggressive ruleset moving using class name scopes information.
- New CLI option `--usage` to pass usage data file.
- Improve initial ruleset merge
- Change order of ruleset processing, now it's left to right. Previously unmerged rulesets may prevent lookup and other rulesets merge.
- Difference in pseudo signature just prevents ruleset merging, but don't stop lookup.
- Simplify block comparison (performance).
- New method `csso.minifyBlock()` for css block compression (e.g. `style` attribute content).
- Ruleset merge improvement: at-rules with block (like `@media` or `@supports`) now can be skipped during ruleset merge lookup if doesn't contain something prevents it.
- FIX: Add negation (`:not()`) to pseudo signature to avoid unsafe merge (old browsers doesn't support it).
- FIX: Check nested parts of value when compute compatibility. It fixes unsafe property merging.
## 1.7.1 (March 16, 2016)
- pass block mode to tokenizer for correct parsing of declarations properties with `//` hack
- fix wrongly `@import` and `@charset` removal on double exclamation comment
## 1.7.0 (March 10, 2016)
- support for [CSS Custom Properties](https://www.w3.org/TR/css-variables/) (#279)
- rework RTBL properties merge better merge for values with special units and don't merge values with CSS-wide keywords (#255)
- remove redundant universal selectors (#178)
- take in account `!important` when check for property overriding (#280)
- don't merge `text-align` declarations with some values (#281)
- add spaces around `/deep/` combinator on translate, since it together with universal selector can produce a comment
- better keyword and property name resolving (tolerant to hacks and so on)
- integration improvements
- compression log function could be customized by `logger` option for `compress()` and `minify()`
- make possible to set initial line and column for parser
## 1.6.4 (March 1, 2016)
- `npm` publish issue (#276)
## 1.6.3 (February 29, 2016)
- add `file` to generated source map since other tools can relay on it in source map transform chain
## 1.6.2 (February 29, 2016)
- tweak some parse error messages and their positions
- fix `:not()` parsing and selector groups in `:not()` is supported now (#215)
- `needPosition` parser option is deprecated, `positions` option should be used instead (`needPosition` is used still if `positions` option omitted)
- expose internal AST API as `csso.internal.*`
- `minify()` adds `sourcesContent` by default when source map is generated
- bring back support for node.js `0.10` until major release (#275)
## 1.6.1 (February 28, 2016)
- fix exception on zero length dimension compress outside declaration (#273)
## 1.6.0 (February 27, 2016)
- **source maps support**
- parser remake:
- various parsing issues fixed
- fix unicode sequence processing in ident (#191)
- support for flags in attribute selector (#270)
- position (line and column) of parse error (#109)
- 4x performance boost, less memory consumption
- compressor refactoring
- internal AST is using doubly linked lists (with safe transformation support during iteration) instead of arrays
- rename `restructuring` to `restructure` option for `minify()`/`compress()` (`restructuring` is alias for `restructure` now, with lower priority)
- unquote urls when possible (#141, #60)
- setup code coverage and a number of related fixes
- add eslint to check unused things
## 1.5.4 (January 27, 2016)
- one more fix (in `restructRuleset` this time) with merge of rulesets when a ruleset with same specificity places between them (#264)
- disable partial merge of rulesets in `@keyframes` rulesets (until sure it's correct)
## 1.5.3 (January 25, 2016)
- don't override display values with different browser support (#259)
- fix publish issue (one of modules leak in development state)
## 1.5.2 (January 24, 2016)
- don't merge rulesets if between them a ruleset with same specificity (#264)
## 1.5.1 (January 14, 2016)
- ensure `-` is not used as an identifier in attribute selectors (thanks to @mathiasbynens)
- fix broken `justDoIt()` function
- various small fixes
## 1.5.0 (January 14, 2016)
### Parser
- attach minus to number
### Compressor
- split code base into small modules and related refactoring
- introduce internal AST format for compressor (`gonzales``internal` and `internal``gonzales` convertors, walkers, translator)
- various optimizations: no snapshots, using caches and indexes
- sort selectors, merge selectors in alphabet order
- compute selector's specificity
- better ruleset restructuring, improve compression of partially equal blocks
- better ruleset merge not only closest but also disjoined by other rulesets when safe
- join `@media` with same query
- `outputAst` new option to specify output AST format (`gonzales` by default for backward compatibility)
- remove quotes surrounding attribute values in attribute selectors when possible (#73)
- replace `from``0%` and `100%``to` at `@keyframes` (#205)
- prevent partial merge of rulesets at `@keyframes` (#80, #197)
### API
- walker for `gonzales` AST was implemented
### CLI
- new option `--stat` (output stat in `stderr`)
- new optional parameter `level` for `--debug` option
## 1.4.4 (December 10, 2015)
- prevent removal of spaces after braces that before identifier that breaking at-rules expressions (#258)
## 1.4.3 (December 4, 2015)
- fix unicode-range parsing that cause to wrong function detection (#250)
## 1.4.2 (November 9, 2015)
- allow spaces between `progid:` and rest part of value for IE's `filter` property as `autoprefixer` generates this kind of code (#249)
- fixes for Windows:
- correct processing new lines
- normalize file content in test suite
- fixes to work in strict mode (#252)
- init compressor dictionaries for every css block (#248, #251)
- bump uglify-js version
## 1.4.1 (October 20, 2015)
- allow merge for `display` property (#167, #244)
- more accurate `rect` (`clip` property value) merge
- fix typo when specifying options in cli (thanks to @Taritsyn)
- fix safe unit values merge with keyword values (#244)
- fix wrong descendant combinator removal (#246)
- build browser version on `prepublish` (thanks to @silentroach)
- parser: store whitespaces as single token (performance and reduce memory consumption)
- rearrange compress tests layout
## 1.4 (October 16, 2015)
Bringing project back to life. Changed files structure, cleaned up and refactored most of sources.
### Common
- single code base (no more `src` folder)
- build browser version with `browserify` (no more `make`, and `web` folder), browser version is available at `dist/csso-browser.js`
- main file is `lib/index.js` now
- minimal `node.js` version is `0.12` now
- restrict file list to publish on npm (no more useless folders and files in package)
- add `jscs` to control code style
- automate `gh-pages` update
- util functions reworked
- translator reworked
- test suite reworked
- compressor refactored
- initial parser refactoring
### API
- new method `minify(src, options)`, options:
- `restructuring` if set to `false`, disable structure optimisations (`true` by default)
- `debug` - outputs intermediate state of CSS during compression (`false` by default)
- deprecate `justDoIt()` method (use `minify` instead)
- rename `treeToString()` method to `stringify()`
- drop `printTree()` method
- AST node info
- `column` and `offset` added
- `ln` renamed to `line`
- fix line counting across multiple files and input with CR LF (#147)
### CLI
- completely reworked, use [clap](https://github.com/lahmatiy/clap) to parse argv
- add support for input from stdin (#128)
- drop undocumented and obsoleted options `--rule` and `--parser` (suppose nobody use it)
- drop `-off` alias for `--restructure-off` as incorrect (only one letter options should starts with single `-`)
- new option `--debug` that reflecting to `options.debug` for `minify`
### Parsing and optimizations
- keep all exclamation comments (#194)
- add `/deep/` combinator support (#209)
- attribute selector
- allow colon in attribute name (#237)
- support for namespaces (#233)
- color
- support all css/html colors
- convert `hsla` to `rgba` and `hls` to `rgb`
- convert `rgba` with 1 as alpha value to `rgb` (#122)
- interpolate `rgb` and `rgba` percentage values to absolute values
- replace percentage values in `rgba` for normalized/interpolated values
- lowercase hex colors and color names (#169)
- fix color minification when hex value replaced for color name (#176)
- fit rgb values to 0..255 range (#181)
- calc
- remove spaces for multiple operator in calc
- don't remove units inside calc (#222)
- fix wrong white space removal around `+` and `-` (#228)
- don't remove units in `flex` property as it could change value meaning (#200)
- don't merge `\9` hack values (#231)
- merge property values only if they have the same functions (#150, #227)
- don't merge property values with some sort of units (#140, #161)
- fix `!important` issue for `top-right-bottom-left` properties (#189)
- fix `top-right-bottom-left` properties merge (#139, #175)
- support for unicode-range (#148)
- don't crash on ruleset with no selector (#135)
- tolerant to class names that starts with digit (#99, #105)
- fix background compressing (#170)
## 1.3.12 (October 8, 2015)
- Case insensitive check for `!important` (#187)
- Fix problems with using `csso` as cli command on Windows (#83, #136, #142 and others)
- Remove byte order marker (the UTF-8 BOM) from input
- Don't strip space between funktion-funktion and funktion-vhash (#134)
- Don't merge TRBL values having \9 (hack for IE8 in bootstrap) (#159, #214, #230, #231 and others)
- Don't strip units off dimensions of non-length (#226, #229 and others)
## 1.3.7 (February 11, 2013)
- Gonzales 1.0.7.
## 1.3.6 (November 26, 2012)
- Gonzales 1.0.6.
## 1.3.5 (October 28, 2012)
- Gonzales 1.0.5.
- Protecting copyright notices in CSS: https://github.com/css/csso/issues/92
- Zero CSS throws an error: https://github.com/css/csso/issues/96
- Don't minify the second `0s` in Firefox for animations: https://github.com/css/csso/issues/100
- Japan manual
- BEM ready documentation
## 1.3.4 (October 10, 2012)
- @page inside @media Causes Error: https://github.com/css/csso/issues/90
## 1.3.3 (October 9, 2012)
- CSSO 1.3.2 compresses ".t-1" and ".t-01" as identical classes: https://github.com/css/csso/issues/88
## 1.3.2 (October 8, 2012)
- filter + important breaks CSSO v1.3.1: https://github.com/css/csso/issues/87
## 1.3.1 (October 8, 2012)
- "filter" IE property breaks CSSO v1.3.0: https://github.com/css/csso/issues/86
## 1.3.0 (October 4, 2012)
- PeCode CSS parser replaced by Gonzales CSS parser

View File

@@ -0,0 +1,19 @@
Copyright (C) 2011-2017 by Sergey Kryzhanovsky
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,376 @@
[![NPM version](https://img.shields.io/npm/v/csso.svg)](https://www.npmjs.com/package/csso)
[![Build Status](https://travis-ci.org/css/csso.svg?branch=master)](https://travis-ci.org/css/csso)
[![Coverage Status](https://coveralls.io/repos/github/css/csso/badge.svg?branch=master)](https://coveralls.io/github/css/csso?branch=master)
[![NPM Downloads](https://img.shields.io/npm/dm/csso.svg)](https://www.npmjs.com/package/csso)
[![Twitter](https://img.shields.io/badge/Twitter-@cssoptimizer-blue.svg)](https://twitter.com/cssoptimizer)
CSSO (CSS Optimizer) is a CSS minifier. It performs three sort of transformations: cleaning (removing redundant), compression (replacement for shorter form) and restructuring (merge of declarations, rulesets and so on). As a result your CSS becomes much smaller.
[![Originated by Yandex](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/yandex.svg)](https://www.yandex.com/)
[![Sponsored by Avito](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/avito.svg)](https://www.avito.ru/)
## Ready to use
- [Web interface](http://css.github.io/csso/csso.html)
- [csso-cli](https://github.com/css/csso-cli) command line interface
- [gulp-csso](https://github.com/ben-eb/gulp-csso) `Gulp` plugin
- [grunt-csso](https://github.com/t32k/grunt-csso) `Grunt` plugin
- [broccoli-csso](https://github.com/sindresorhus/broccoli-csso) `Broccoli` plugin
- [postcss-csso](https://github.com/lahmatiy/postcss-csso) `PostCSS` plugin
- [csso-loader](https://github.com/sandark7/csso-loader) `webpack` loader
- [csso-webpack-plugin](https://github.com/zoobestik/csso-webpack-plugin) `webpack` plugin
## Install
```
npm install csso
```
## API
<!-- MarkdownTOC -->
- [minify\(source\[, options\]\)](#minifysource-options)
- [minifyBlock\(source\[, options\]\)](#minifyblocksource-options)
- [compress\(ast\[, options\]\)](#compressast-options)
- [Source maps](#source-maps)
- [Usage data](#usage-data)
- [White list filtering](#white-list-filtering)
- [Black list filtering](#black-list-filtering)
- [Scopes](#scopes)
- [Debugging](#debugging)
<!-- /MarkdownTOC -->
Basic usage:
```js
var csso = require('csso');
var minifiedCss = csso.minify('.test { color: #ff0000; }').css;
console.log(minifiedCss);
// .test{color:red}
```
CSSO is based on [CSSTree](https://github.com/csstree/csstree) to parse CSS into AST, AST traversal and to generate AST back to CSS. All `CSSTree` API is available behind `syntax` field. You may minify CSS step by step:
```js
var csso = require('csso');
var ast = csso.syntax.parse('.test { color: #ff0000; }');
var compressedAst = csso.compress(ast).ast;
var minifiedCss = csso.syntax.translate(compressedAst);
console.log(minifiedCss);
// .test{color:red}
```
> Warning: CSSO uses early versions of CSSTree that still in active development. CSSO doesn't guarantee API behind `syntax` field or AST format will not change in future releases of CSSO, since it's subject to change in CSSTree. Be carefull with CSSO updates if you use `syntax` API until this warning removal.
### minify(source[, options])
Minify `source` CSS passed as `String`.
```js
var result = csso.minify('.test { color: #ff0000; }', {
restructure: false, // don't change CSS structure, i.e. don't merge declarations, rulesets etc
debug: true // show additional debug information:
// true or number from 1 to 3 (greater number - more details)
});
console.log(result.css);
// > .test{color:red}
```
Returns an object with properties:
- css `String` resulting CSS
- map `Object` instance of [`SourceMapGenerator`](https://github.com/mozilla/source-map#sourcemapgenerator) or `null`
Options:
- sourceMap
Type: `Boolean`
Default: `false`
Generate a source map when `true`.
- filename
Type: `String`
Default: `'<unknown>'`
Filename of input CSS, uses for source map generation.
- debug
Type: `Boolean`
Default: `false`
Output debug information to `stderr`.
- beforeCompress
Type: `function(ast, options)` or `Array<function(ast, options)>` or `null`
Default: `null`
Called right after parse is run.
- afterCompress
Type: `function(compressResult, options)` or `Array<function(compressResult, options)>` or `null`
Default: `null`
Called right after [`compress()`](#compressast-options) is run.
- Other options are the same as for [`compress()`](#compressast-options) function.
### minifyBlock(source[, options])
The same as `minify()` but for list of declarations. Usually it's a `style` attribute value.
```js
var result = csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000');
console.log(result.css);
// > color:red
```
### compress(ast[, options])
Does the main task compress an AST.
> NOTE: `compress()` performs AST compression by transforming input AST by default (since AST cloning is expensive and needed in rare cases). Use `clone` option with truthy value in case you want to keep input AST untouched.
Returns an object with properties:
- ast `Object` resulting AST
Options:
- restructure
Type: `Boolean`
Default: `true`
Disable or enable a structure optimisations.
- forceMediaMerge
Type: `Boolean`
Default: `false`
Enables merging of `@media` rules with the same media query by splitted by other rules. The optimisation is unsafe in general, but should work fine in most cases. Use it on your own risk.
- clone
Type: `Boolean`
Default: `false`
Transform a copy of input AST if `true`. Useful in case of AST reuse.
- comments
Type: `String` or `Boolean`
Default: `true`
Specify what comments to left:
- `'exclamation'` or `true` left all exclamation comments (i.e. `/*! .. */`)
- `'first-exclamation'` remove every comments except first one
- `false` remove every comments
- usage
Type: `Object` or `null`
Default: `null`
Usage data for advanced optimisations (see [Usage data](#usage-data) for details)
- logger
Type: `Function` or `null`
Default: `null`
Function to track every step of transformation.
### Source maps
To get a source map set `true` for `sourceMap` option. Additianaly `filename` option can be passed to specify source file. When `sourceMap` option is `true`, `map` field of result object will contain a [`SourceMapGenerator`](https://github.com/mozilla/source-map#sourcemapgenerator) instance. This object can be mixed with another source map or translated to string.
```js
var csso = require('csso');
var css = fs.readFileSync('path/to/my.css', 'utf8');
var result = csso.minify(css, {
filename: 'path/to/my.css', // will be added to source map as reference to source file
sourceMap: true // generate source map
});
console.log(result);
// { css: '...minified...', map: SourceMapGenerator {} }
console.log(result.map.toString());
// '{ .. source map content .. }'
```
Example of generating source map with respect of source map from input CSS:
```js
var require('source-map');
var csso = require('csso');
var inputFile = 'path/to/my.css';
var input = fs.readFileSync(inputFile, 'utf8');
var inputMap = input.match(/\/\*# sourceMappingURL=(\S+)\s*\*\/\s*$/);
var output = csso.minify(input, {
filename: inputFile,
sourceMap: true
});
// apply input source map to output
if (inputMap) {
output.map.applySourceMap(
new SourceMapConsumer(inputMap[1]),
inputFile
)
}
// result CSS with source map
console.log(
output.css +
'/*# sourceMappingURL=data:application/json;base64,' +
new Buffer(output.map.toString()).toString('base64') +
' */'
);
```
### Usage data
`CSSO` can use data about how `CSS` is used in a markup for better compression. File with this data (`JSON`) can be set using `usage` option. Usage data may contain following sections:
- `blacklist` a set of black lists (see [Black list filtering](#black-list-filtering))
- `tags` white list of tags
- `ids` white list of ids
- `classes` white list of classes
- `scopes` groups of classes which never used with classes from other groups on the same element
All sections are optional. Value of `tags`, `ids` and `classes` should be an array of a string, value of `scopes` should be an array of arrays of strings. Other values are ignoring.
#### White list filtering
`tags`, `ids` and `classes` are using on clean stage to filter selectors that contain something not in the lists. Selectors are filtering only by those kind of simple selector which white list is specified. For example, if only `tags` list is specified then type selectors are checking, and if all type selectors in selector present in list or selector has no any type selector it isn't filter.
> `ids` and `classes` are case sensitive, `tags` is not.
Input CSS:
```css
* { color: green; }
ul, ol, li { color: blue; }
UL.foo, span.bar { color: red; }
```
Usage data:
```json
{
"tags": ["ul", "LI"]
}
```
Resulting CSS:
```css
*{color:green}ul,li{color:blue}ul.foo{color:red}
```
Filtering performs for nested selectors too. `:not()` pseudos content is ignoring since the result of matching is unpredictable. Example for the same usage data as above:
```css
:nth-child(2n of ul, ol) { color: red }
:nth-child(3n + 1 of img) { color: yellow }
:not(div, ol, ul) { color: green }
:has(:matches(ul, ol), ul, ol) { color: blue }
```
Turns into:
```css
:nth-child(2n of ul){color:red}:not(div,ol,ul){color:green}:has(:matches(ul),ul){color:blue}
```
#### Black list filtering
Black list filtering performs the same as white list filtering, but filters things that mentioned in the lists. `blacklist` can contain the lists `tags`, `ids` and `classes`.
Black list has a higher priority, so when something mentioned in the white list and in the black list then white list occurrence is ignoring. The `:not()` pseudos content ignoring as well.
```css
* { color: green; }
ul, ol, li { color: blue; }
UL.foo, li.bar { color: red; }
```
Usage data:
```json
{
"blacklist": {
"tags": ["ul"]
},
"tags": ["ul", "LI"]
}
```
Resulting CSS:
```css
*{color:green}li{color:blue}li.bar{color:red}
```
#### Scopes
Scopes is designed for CSS scope isolation solutions such as [css-modules](https://github.com/css-modules/css-modules). Scopes are similar to namespaces and define lists of class names that exclusively used on some markup. This information allows the optimizer to move rules more agressive. Since it assumes selectors from different scopes don't match for the same element. This can improve rule merging.
Suppose we have a file:
```css
.module1-foo { color: red; }
.module1-bar { font-size: 1.5em; background: yellow; }
.module2-baz { color: red; }
.module2-qux { font-size: 1.5em; background: yellow; width: 50px; }
```
It can be assumed that first two rules are never used with the second two on the same markup. But we can't say that for sure without a markup review. The optimizer doesn't know it either and will perform safe transformations only. The result will be the same as input but with no spaces and some semicolons:
```css
.module1-foo{color:red}.module1-bar{font-size:1.5em;background:#ff0}.module2-baz{color:red}.module2-qux{font-size:1.5em;background:#ff0;width:50px}
```
With usage data `CSSO` can produce better output. If follow usage data is provided:
```json
{
"scopes": [
["module1-foo", "module1-bar"],
["module2-baz", "module2-qux"]
]
}
```
The result will be (29 bytes extra saving):
```css
.module1-foo,.module2-baz{color:red}.module1-bar,.module2-qux{font-size:1.5em;background:#ff0}.module2-qux{width:50px}
```
If class name isn't mentioned in the `scopes` it belongs to default scope. `scopes` data doesn't affect `classes` whitelist. If class name mentioned in `scopes` but missed in `classes` (both sections are specified) it will be filtered.
Note that class name can't be set for several scopes. Also selector can't has a class names from different scopes. In both cases an exception will thrown.
Currently the optimizer doesn't care about changing order safety for out-of-bounds selectors (i.e. selectors that match to elements without class name, e.g. `.scope div` or `.scope ~ :last-child`). It assumes that scoped CSS modules doesn't relay on it's order. It may be fix in future if to be an issue.
### Debugging
> TODO

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,65 @@
var resolveKeyword = require('css-tree').keyword;
module.exports = function cleanAtrule(node, item, list) {
if (node.block) {
// otherwise removed at-rule don't prevent @import for removal
if (this.stylesheet !== null) {
this.stylesheet.firstAtrulesAllowed = false;
}
if (node.block.children.isEmpty()) {
list.remove(item);
return;
}
}
switch (node.name) {
case 'charset':
if (!node.prelude || node.prelude.children.isEmpty()) {
list.remove(item);
return;
}
// if there is any rule before @charset -> remove it
if (item.prev) {
list.remove(item);
return;
}
break;
case 'import':
if (this.stylesheet === null || !this.stylesheet.firstAtrulesAllowed) {
list.remove(item);
return;
}
// if there are some rules that not an @import or @charset before @import
// remove it
list.prevUntil(item.prev, function(rule) {
if (rule.type === 'Atrule') {
if (rule.name === 'import' || rule.name === 'charset') {
return;
}
}
this.root.firstAtrulesAllowed = false;
list.remove(item);
return true;
}, this);
break;
default:
var keyword = resolveKeyword(node.name);
if (keyword.name === 'keyframes' ||
keyword.name === 'media' ||
keyword.name === 'supports') {
// drop at-rule with no prelude
if (!node.prelude || node.prelude.children.isEmpty()) {
list.remove(item);
}
}
}
};

View File

@@ -0,0 +1,3 @@
module.exports = function cleanComment(data, item, list) {
list.remove(item);
};

View File

@@ -0,0 +1,5 @@
module.exports = function cleanDeclartion(node, item, list) {
if (node.value.children && node.value.children.isEmpty()) {
list.remove(item);
}
};

View File

@@ -0,0 +1,14 @@
// remove white spaces around operators when safe
module.exports = function cleanWhitespace(node, item, list) {
if (node.value === '+' || node.value === '-') {
return;
}
if (item.prev !== null && item.prev.data.type === 'WhiteSpace') {
list.remove(item.prev);
}
if (item.next !== null && item.next.data.type === 'WhiteSpace') {
list.remove(item.next);
}
};

View File

@@ -0,0 +1,87 @@
var hasOwnProperty = Object.prototype.hasOwnProperty;
var walk = require('css-tree').walk;
function cleanUnused(selectorList, usageData) {
selectorList.children.each(function(selector, item, list) {
var shouldRemove = false;
walk(selector, function(node) {
// ignore nodes in nested selectors
if (this.selector === null || this.selector === selectorList) {
switch (node.type) {
case 'SelectorList':
// TODO: remove toLowerCase when pseudo selectors will be normalized
// ignore selectors inside :not()
if (this['function'] === null || this['function'].name.toLowerCase() !== 'not') {
if (cleanUnused(node, usageData)) {
shouldRemove = true;
}
}
break;
case 'ClassSelector':
if (usageData.whitelist !== null &&
usageData.whitelist.classes !== null &&
!hasOwnProperty.call(usageData.whitelist.classes, node.name)) {
shouldRemove = true;
}
if (usageData.blacklist !== null &&
usageData.blacklist.classes !== null &&
hasOwnProperty.call(usageData.blacklist.classes, node.name)) {
shouldRemove = true;
}
break;
case 'IdSelector':
if (usageData.whitelist !== null &&
usageData.whitelist.ids !== null &&
!hasOwnProperty.call(usageData.whitelist.ids, node.name)) {
shouldRemove = true;
}
if (usageData.blacklist !== null &&
usageData.blacklist.ids !== null &&
hasOwnProperty.call(usageData.blacklist.ids, node.name)) {
shouldRemove = true;
}
break;
case 'TypeSelector':
// TODO: remove toLowerCase when type selectors will be normalized
// ignore universal selectors
if (node.name.charAt(node.name.length - 1) !== '*') {
if (usageData.whitelist !== null &&
usageData.whitelist.tags !== null &&
!hasOwnProperty.call(usageData.whitelist.tags, node.name.toLowerCase())) {
shouldRemove = true;
}
if (usageData.blacklist !== null &&
usageData.blacklist.tags !== null &&
hasOwnProperty.call(usageData.blacklist.tags, node.name.toLowerCase())) {
shouldRemove = true;
}
}
break;
}
}
});
if (shouldRemove) {
list.remove(item);
}
});
return selectorList.children.isEmpty();
}
module.exports = function cleanRuleset(node, item, list, options) {
var usageData = options.usage;
if (usageData && (usageData.whitelist !== null || usageData.blacklist !== null)) {
cleanUnused(node.prelude, usageData);
}
if (node.prelude.children.isEmpty() ||
node.block.children.isEmpty()) {
list.remove(item);
}
};

View File

@@ -0,0 +1,19 @@
// remove useless universal selector
module.exports = function cleanType(node, item, list) {
var name = item.data.name;
// check it's a non-namespaced universal selector
if (name !== '*') {
return;
}
// remove when universal selector before other selectors
var nextType = item.next && item.next.data.type;
if (nextType === 'IdSelector' ||
nextType === 'ClassSelector' ||
nextType === 'AttributeSelector' ||
nextType === 'PseudoClassSelector' ||
nextType === 'PseudoElementSelector') {
list.remove(item);
}
};

View File

@@ -0,0 +1,19 @@
module.exports = function cleanWhitespace(node, item, list) {
// remove when first or last item in sequence
if (item.next === null || item.prev === null) {
list.remove(item);
return;
}
// remove when previous node is whitespace
if (item.prev.data.type === 'WhiteSpace') {
list.remove(item);
return;
}
if ((this.stylesheet !== null && this.stylesheet.children === list) ||
(this.block !== null && this.block.children === list)) {
list.remove(item);
return;
}
};

View File

@@ -0,0 +1,18 @@
var walk = require('css-tree').walkUp;
var handlers = {
Atrule: require('./Atrule'),
Rule: require('./Rule'),
Declaration: require('./Declaration'),
TypeSelector: require('./TypeSelector'),
Comment: require('./Comment'),
Operator: require('./Operator'),
WhiteSpace: require('./WhiteSpace')
};
module.exports = function(ast, options) {
walk(ast, function(node, item, list) {
if (handlers.hasOwnProperty(node.type)) {
handlers[node.type].call(this, node, item, list, options);
}
});
};

View File

@@ -0,0 +1,192 @@
var List = require('css-tree').List;
var clone = require('css-tree').clone;
var usageUtils = require('./usage');
var clean = require('./clean');
var replace = require('./replace');
var restructure = require('./restructure');
var walkRules = require('css-tree').walkRules;
function readChunk(children, specialComments) {
var buffer = new List();
var nonSpaceTokenInBuffer = false;
var protectedComment;
children.nextUntil(children.head, function(node, item, list) {
if (node.type === 'Comment') {
if (!specialComments || node.value.charAt(0) !== '!') {
list.remove(item);
return;
}
if (nonSpaceTokenInBuffer || protectedComment) {
return true;
}
list.remove(item);
protectedComment = node;
return;
}
if (node.type !== 'WhiteSpace') {
nonSpaceTokenInBuffer = true;
}
buffer.insert(list.remove(item));
});
return {
comment: protectedComment,
stylesheet: {
type: 'StyleSheet',
loc: null,
children: buffer
}
};
}
function compressChunk(ast, firstAtrulesAllowed, num, options) {
options.logger('Compress block #' + num, null, true);
var seed = 1;
if (ast.type === 'StyleSheet') {
ast.firstAtrulesAllowed = firstAtrulesAllowed;
ast.id = seed++;
}
walkRules(ast, function markScopes(node) {
if (node.type === 'Atrule' && node.block !== null) {
node.block.id = seed++;
}
});
options.logger('init', ast);
// remove redundant
clean(ast, options);
options.logger('clean', ast);
// replace nodes for shortened forms
replace(ast, options);
options.logger('replace', ast);
// structure optimisations
if (options.restructuring) {
restructure(ast, options);
}
return ast;
}
function getCommentsOption(options) {
var comments = 'comments' in options ? options.comments : 'exclamation';
if (typeof comments === 'boolean') {
comments = comments ? 'exclamation' : false;
} else if (comments !== 'exclamation' && comments !== 'first-exclamation') {
comments = false;
}
return comments;
}
function getRestructureOption(options) {
return 'restructure' in options ? options.restructure :
'restructuring' in options ? options.restructuring :
true;
}
function wrapBlock(block) {
return new List().appendData({
type: 'Rule',
loc: null,
prelude: {
type: 'SelectorList',
loc: null,
children: new List().appendData({
type: 'Selector',
loc: null,
children: new List().appendData({
type: 'TypeSelector',
loc: null,
name: 'x'
})
})
},
block: block
});
}
module.exports = function compress(ast, options) {
ast = ast || { type: 'StyleSheet', loc: null, children: new List() };
options = options || {};
var compressOptions = {
logger: typeof options.logger === 'function' ? options.logger : function() {},
restructuring: getRestructureOption(options),
forceMediaMerge: Boolean(options.forceMediaMerge),
usage: options.usage ? usageUtils.buildIndex(options.usage) : false
};
var specialComments = getCommentsOption(options);
var firstAtrulesAllowed = true;
var input;
var output = new List();
var chunk;
var chunkNum = 1;
var chunkChildren;
if (options.clone) {
ast = clone(ast);
}
if (ast.type === 'StyleSheet') {
input = ast.children;
ast.children = output;
} else {
input = wrapBlock(ast);
}
do {
chunk = readChunk(input, Boolean(specialComments));
compressChunk(chunk.stylesheet, firstAtrulesAllowed, chunkNum++, compressOptions);
chunkChildren = chunk.stylesheet.children;
if (chunk.comment) {
// add \n before comment if there is another content in output
if (!output.isEmpty()) {
output.insert(List.createItem({
type: 'Raw',
value: '\n'
}));
}
output.insert(List.createItem(chunk.comment));
// add \n after comment if chunk is not empty
if (!chunkChildren.isEmpty()) {
output.insert(List.createItem({
type: 'Raw',
value: '\n'
}));
}
}
if (firstAtrulesAllowed && !chunkChildren.isEmpty()) {
var lastRule = chunkChildren.last();
if (lastRule.type !== 'Atrule' ||
(lastRule.name !== 'import' && lastRule.name !== 'charset')) {
firstAtrulesAllowed = false;
}
}
if (specialComments !== 'exclamation') {
specialComments = false;
}
output.appendList(chunkChildren);
} while (!input.isEmpty());
return {
ast: ast
};
};

View File

@@ -0,0 +1,143 @@
var csstree = require('css-tree');
var parse = csstree.parse;
var compress = require('./compress');
var translate = csstree.translate;
var translateWithSourceMap = csstree.translateWithSourceMap;
function debugOutput(name, options, startTime, data) {
if (options.debug) {
console.error('## ' + name + ' done in %d ms\n', Date.now() - startTime);
}
return data;
}
function createDefaultLogger(level) {
var lastDebug;
return function logger(title, ast) {
var line = title;
if (ast) {
line = '[' + ((Date.now() - lastDebug) / 1000).toFixed(3) + 's] ' + line;
}
if (level > 1 && ast) {
var css = translate(ast, true);
// when level 2, limit css to 256 symbols
if (level === 2 && css.length > 256) {
css = css.substr(0, 256) + '...';
}
line += '\n ' + css + '\n';
}
console.error(line);
lastDebug = Date.now();
};
}
function copy(obj) {
var result = {};
for (var key in obj) {
result[key] = obj[key];
}
return result;
}
function buildCompressOptions(options) {
options = copy(options);
if (typeof options.logger !== 'function' && options.debug) {
options.logger = createDefaultLogger(options.debug);
}
return options;
}
function runHandler(ast, options, handlers) {
if (!Array.isArray(handlers)) {
handlers = [handlers];
}
handlers.forEach(function(fn) {
fn(ast, options);
});
}
function minify(context, source, options) {
options = options || {};
var filename = options.filename || '<unknown>';
var result;
// parse
var ast = debugOutput('parsing', options, Date.now(),
parse(source, {
context: context,
filename: filename,
positions: Boolean(options.sourceMap)
})
);
// before compress handlers
if (options.beforeCompress) {
debugOutput('beforeCompress', options, Date.now(),
runHandler(ast, options, options.beforeCompress)
);
}
// compress
var compressResult = debugOutput('compress', options, Date.now(),
compress(ast, buildCompressOptions(options))
);
// after compress handlers
if (options.afterCompress) {
debugOutput('afterCompress', options, Date.now(),
runHandler(compressResult, options, options.afterCompress)
);
}
// translate
if (options.sourceMap) {
result = debugOutput('translateWithSourceMap', options, Date.now(), (function() {
var tmp = translateWithSourceMap(compressResult.ast);
tmp.map._file = filename; // since other tools can relay on file in source map transform chain
tmp.map.setSourceContent(filename, source);
return tmp;
})());
} else {
result = debugOutput('translate', options, Date.now(), {
css: translate(compressResult.ast),
map: null
});
}
return result;
}
function minifyStylesheet(source, options) {
return minify('stylesheet', source, options);
}
function minifyBlock(source, options) {
return minify('declarationList', source, options);
}
module.exports = {
version: require('../package.json').version,
// main methods
minify: minifyStylesheet,
minifyBlock: minifyBlock,
// compress an AST
compress: compress,
// css syntax parser/walkers/generator/etc
syntax: csstree
};

View File

@@ -0,0 +1,9 @@
var resolveKeyword = require('css-tree').keyword;
var compressKeyframes = require('./atrule/keyframes');
module.exports = function(node) {
// compress @keyframe selectors
if (resolveKeyword(node.name).name === 'keyframes') {
compressKeyframes(node);
}
};

View File

@@ -0,0 +1,33 @@
// Can unquote attribute detection
// Adopted implementation of Mathias Bynens
// https://github.com/mathiasbynens/mothereff.in/blob/master/unquoted-attributes/eff.js
var escapesRx = /\\([0-9A-Fa-f]{1,6})(\r\n|[ \t\n\f\r])?|\\./g;
var blockUnquoteRx = /^(-?\d|--)|[\u0000-\u002c\u002e\u002f\u003A-\u0040\u005B-\u005E\u0060\u007B-\u009f]/;
function canUnquote(value) {
if (value === '' || value === '-') {
return;
}
// Escapes are valid, so replace them with a valid non-empty string
value = value.replace(escapesRx, 'a');
return !blockUnquoteRx.test(value);
}
module.exports = function(node) {
var attrValue = node.value;
if (!attrValue || attrValue.type !== 'String') {
return;
}
var unquotedValue = attrValue.value.replace(/^(.)(.*)\1$/, '$2');
if (canUnquote(unquotedValue)) {
node.value = {
type: 'Identifier',
loc: attrValue.loc,
name: unquotedValue
};
}
};

View File

@@ -0,0 +1,56 @@
var packNumber = require('./Number').pack;
var LENGTH_UNIT = {
// absolute length units
'px': true,
'mm': true,
'cm': true,
'in': true,
'pt': true,
'pc': true,
// relative length units
'em': true,
'ex': true,
'ch': true,
'rem': true,
// viewport-percentage lengths
'vh': true,
'vw': true,
'vmin': true,
'vmax': true,
'vm': true
};
module.exports = function compressDimension(node, item) {
var value = packNumber(node.value, item);
node.value = value;
if (value === '0' && this.declaration !== null && this.atrulePrelude === null) {
var unit = node.unit.toLowerCase();
// only length values can be compressed
if (!LENGTH_UNIT.hasOwnProperty(unit)) {
return;
}
// issue #362: shouldn't remove unit in -ms-flex since it breaks flex in IE10/11
// issue #200: shouldn't remove unit in flex since it breaks flex in IE10/11
if (this.declaration.property === '-ms-flex' ||
this.declaration.property === 'flex') {
return;
}
// issue #222: don't remove units inside calc
if (this['function'] && this['function'].name === 'calc') {
return;
}
item.data = {
type: 'Number',
loc: node.loc,
value: value
};
}
};

View File

@@ -0,0 +1,39 @@
var OMIT_PLUSSIGN = /^(?:\+|(-))?0*(\d*)(?:\.0*|(\.\d*?)0*)?$/;
var KEEP_PLUSSIGN = /^([\+\-])?0*(\d*)(?:\.0*|(\.\d*?)0*)?$/;
var unsafeToRemovePlusSignAfter = {
Dimension: true,
HexColor: true,
Identifier: true,
Number: true,
Raw: true,
UnicodeRange: true
};
function packNumber(value, item) {
// omit plus sign only if no prev or prev is safe type
var regexp = item && item.prev !== null && unsafeToRemovePlusSignAfter.hasOwnProperty(item.prev.data.type)
? KEEP_PLUSSIGN
: OMIT_PLUSSIGN;
// 100 -> '100'
// 00100 -> '100'
// +100 -> '100' (only when safe, e.g. omitting plus sign for 1px+1px leads to single dimension instead of two)
// -100 -> '-100'
// 0.123 -> '.123'
// 0.12300 -> '.123'
// 0.0 -> ''
// 0 -> ''
// -0 -> '-'
value = String(value).replace(regexp, '$1$2$3');
if (value === '' || value === '-') {
value = '0';
}
return value;
}
module.exports = function(node, item) {
node.value = packNumber(node.value, item);
};
module.exports.pack = packNumber;

View File

@@ -0,0 +1,55 @@
var packNumber = require('./Number').pack;
var PERCENTAGE_LENGTH_PROPERTY = {
'margin': true,
'margin-top': true,
'margin-left': true,
'margin-bottom': true,
'margin-right': true,
'padding': true,
'padding-top': true,
'padding-left': true,
'padding-bottom': true,
'padding-right': true,
'top': true,
'left': true,
'bottom': true,
'right': true,
'background-position': true,
'background-position-x': true,
'background-position-y': true,
'background-size': true,
'border': true,
'border-width': true,
'border-top-width': true,
'border-left-width': true,
'border-bottom-width': true,
'border-right-width': true,
'border-image-width': true,
'border-radius': true,
'border-bottom-left-radius': true,
'border-bottom-right-radius': true,
'border-top-left-radius': true,
'border-top-right-radius': true
};
module.exports = function compressPercentage(node, item) {
var value = packNumber(node.value, item);
var property = this.declaration !== null ? this.declaration.property : null;
node.value = value;
if (property !== null && PERCENTAGE_LENGTH_PROPERTY.hasOwnProperty(property)) {
if (value === '0') {
item.data = {
type: 'Number',
loc: node.loc,
value: value
};
}
}
};

View File

@@ -0,0 +1,12 @@
module.exports = function(node) {
var value = node.value;
// remove escaped newlines, i.e.
// .a { content: "foo\
// bar"}
// ->
// .a { content: "foobar" }
value = value.replace(/\\(\r\n|\r|\n|\f)/g, '');
node.value = value;
};

View File

@@ -0,0 +1,33 @@
var UNICODE = '\\\\[0-9a-f]{1,6}(\\r\\n|[ \\n\\r\\t\\f])?';
var ESCAPE = '(' + UNICODE + '|\\\\[^\\n\\r\\f0-9a-fA-F])';
var NONPRINTABLE = '\u0000\u0008\u000b\u000e-\u001f\u007f';
var SAFE_URL = new RegExp('^(' + ESCAPE + '|[^\"\'\\(\\)\\\\\\s' + NONPRINTABLE + '])*$', 'i');
module.exports = function(node) {
var value = node.value;
if (value.type !== 'String') {
return;
}
var quote = value.value[0];
var url = value.value.substr(1, value.value.length - 2);
// convert `\\` to `/`
url = url.replace(/\\\\/g, '/');
// remove quotes when safe
// https://www.w3.org/TR/css-syntax-3/#url-unquoted-diagram
if (SAFE_URL.test(url)) {
node.value = {
type: 'Raw',
loc: node.value.loc,
value: url
};
} else {
// use double quotes if string has no double quotes
// otherwise use original quotes
// TODO: make better quote type selection
node.value.value = url.indexOf('"') === -1 ? '"' + url + '"' : quote + url + quote;
}
};

View File

@@ -0,0 +1,20 @@
var resolveName = require('css-tree').property;
var handlers = {
'font': require('./property/font'),
'font-weight': require('./property/font-weight'),
'background': require('./property/background'),
'border': require('./property/border'),
'outline': require('./property/border')
};
module.exports = function compressValue(node) {
if (!this.declaration) {
return;
}
var property = resolveName(this.declaration.property);
if (handlers.hasOwnProperty(property.name)) {
handlers[property.name](node);
}
};

View File

@@ -0,0 +1,21 @@
module.exports = function(node) {
node.block.children.each(function(rule) {
rule.prelude.children.each(function(simpleselector) {
simpleselector.children.each(function(data, item) {
if (data.type === 'Percentage' && data.value === '100') {
item.data = {
type: 'TypeSelector',
loc: data.loc,
name: 'to'
};
} else if (data.type === 'TypeSelector' && data.name === 'from') {
item.data = {
type: 'Percentage',
loc: data.loc,
value: '0'
};
}
});
});
});
};

View File

@@ -0,0 +1,510 @@
var lexer = require('css-tree').lexer;
var packNumber = require('./Number').pack;
// http://www.w3.org/TR/css3-color/#svg-color
var NAME_TO_HEX = {
'aliceblue': 'f0f8ff',
'antiquewhite': 'faebd7',
'aqua': '0ff',
'aquamarine': '7fffd4',
'azure': 'f0ffff',
'beige': 'f5f5dc',
'bisque': 'ffe4c4',
'black': '000',
'blanchedalmond': 'ffebcd',
'blue': '00f',
'blueviolet': '8a2be2',
'brown': 'a52a2a',
'burlywood': 'deb887',
'cadetblue': '5f9ea0',
'chartreuse': '7fff00',
'chocolate': 'd2691e',
'coral': 'ff7f50',
'cornflowerblue': '6495ed',
'cornsilk': 'fff8dc',
'crimson': 'dc143c',
'cyan': '0ff',
'darkblue': '00008b',
'darkcyan': '008b8b',
'darkgoldenrod': 'b8860b',
'darkgray': 'a9a9a9',
'darkgrey': 'a9a9a9',
'darkgreen': '006400',
'darkkhaki': 'bdb76b',
'darkmagenta': '8b008b',
'darkolivegreen': '556b2f',
'darkorange': 'ff8c00',
'darkorchid': '9932cc',
'darkred': '8b0000',
'darksalmon': 'e9967a',
'darkseagreen': '8fbc8f',
'darkslateblue': '483d8b',
'darkslategray': '2f4f4f',
'darkslategrey': '2f4f4f',
'darkturquoise': '00ced1',
'darkviolet': '9400d3',
'deeppink': 'ff1493',
'deepskyblue': '00bfff',
'dimgray': '696969',
'dimgrey': '696969',
'dodgerblue': '1e90ff',
'firebrick': 'b22222',
'floralwhite': 'fffaf0',
'forestgreen': '228b22',
'fuchsia': 'f0f',
'gainsboro': 'dcdcdc',
'ghostwhite': 'f8f8ff',
'gold': 'ffd700',
'goldenrod': 'daa520',
'gray': '808080',
'grey': '808080',
'green': '008000',
'greenyellow': 'adff2f',
'honeydew': 'f0fff0',
'hotpink': 'ff69b4',
'indianred': 'cd5c5c',
'indigo': '4b0082',
'ivory': 'fffff0',
'khaki': 'f0e68c',
'lavender': 'e6e6fa',
'lavenderblush': 'fff0f5',
'lawngreen': '7cfc00',
'lemonchiffon': 'fffacd',
'lightblue': 'add8e6',
'lightcoral': 'f08080',
'lightcyan': 'e0ffff',
'lightgoldenrodyellow': 'fafad2',
'lightgray': 'd3d3d3',
'lightgrey': 'd3d3d3',
'lightgreen': '90ee90',
'lightpink': 'ffb6c1',
'lightsalmon': 'ffa07a',
'lightseagreen': '20b2aa',
'lightskyblue': '87cefa',
'lightslategray': '789',
'lightslategrey': '789',
'lightsteelblue': 'b0c4de',
'lightyellow': 'ffffe0',
'lime': '0f0',
'limegreen': '32cd32',
'linen': 'faf0e6',
'magenta': 'f0f',
'maroon': '800000',
'mediumaquamarine': '66cdaa',
'mediumblue': '0000cd',
'mediumorchid': 'ba55d3',
'mediumpurple': '9370db',
'mediumseagreen': '3cb371',
'mediumslateblue': '7b68ee',
'mediumspringgreen': '00fa9a',
'mediumturquoise': '48d1cc',
'mediumvioletred': 'c71585',
'midnightblue': '191970',
'mintcream': 'f5fffa',
'mistyrose': 'ffe4e1',
'moccasin': 'ffe4b5',
'navajowhite': 'ffdead',
'navy': '000080',
'oldlace': 'fdf5e6',
'olive': '808000',
'olivedrab': '6b8e23',
'orange': 'ffa500',
'orangered': 'ff4500',
'orchid': 'da70d6',
'palegoldenrod': 'eee8aa',
'palegreen': '98fb98',
'paleturquoise': 'afeeee',
'palevioletred': 'db7093',
'papayawhip': 'ffefd5',
'peachpuff': 'ffdab9',
'peru': 'cd853f',
'pink': 'ffc0cb',
'plum': 'dda0dd',
'powderblue': 'b0e0e6',
'purple': '800080',
'rebeccapurple': '639',
'red': 'f00',
'rosybrown': 'bc8f8f',
'royalblue': '4169e1',
'saddlebrown': '8b4513',
'salmon': 'fa8072',
'sandybrown': 'f4a460',
'seagreen': '2e8b57',
'seashell': 'fff5ee',
'sienna': 'a0522d',
'silver': 'c0c0c0',
'skyblue': '87ceeb',
'slateblue': '6a5acd',
'slategray': '708090',
'slategrey': '708090',
'snow': 'fffafa',
'springgreen': '00ff7f',
'steelblue': '4682b4',
'tan': 'd2b48c',
'teal': '008080',
'thistle': 'd8bfd8',
'tomato': 'ff6347',
'turquoise': '40e0d0',
'violet': 'ee82ee',
'wheat': 'f5deb3',
'white': 'fff',
'whitesmoke': 'f5f5f5',
'yellow': 'ff0',
'yellowgreen': '9acd32'
};
var HEX_TO_NAME = {
'800000': 'maroon',
'800080': 'purple',
'808000': 'olive',
'808080': 'gray',
'00ffff': 'cyan',
'f0ffff': 'azure',
'f5f5dc': 'beige',
'ffe4c4': 'bisque',
'000000': 'black',
'0000ff': 'blue',
'a52a2a': 'brown',
'ff7f50': 'coral',
'ffd700': 'gold',
'008000': 'green',
'4b0082': 'indigo',
'fffff0': 'ivory',
'f0e68c': 'khaki',
'00ff00': 'lime',
'faf0e6': 'linen',
'000080': 'navy',
'ffa500': 'orange',
'da70d6': 'orchid',
'cd853f': 'peru',
'ffc0cb': 'pink',
'dda0dd': 'plum',
'f00': 'red',
'ff0000': 'red',
'fa8072': 'salmon',
'a0522d': 'sienna',
'c0c0c0': 'silver',
'fffafa': 'snow',
'd2b48c': 'tan',
'008080': 'teal',
'ff6347': 'tomato',
'ee82ee': 'violet',
'f5deb3': 'wheat',
'ffffff': 'white',
'ffff00': 'yellow'
};
function hueToRgb(p, q, t) {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
}
function hslToRgb(h, s, l, a) {
var r;
var g;
var b;
if (s === 0) {
r = g = b = l; // achromatic
} else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hueToRgb(p, q, h + 1 / 3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1 / 3);
}
return [
Math.round(r * 255),
Math.round(g * 255),
Math.round(b * 255),
a
];
}
function toHex(value) {
value = value.toString(16);
return value.length === 1 ? '0' + value : value;
}
function parseFunctionArgs(functionArgs, count, rgb) {
var cursor = functionArgs.head;
var args = [];
var wasValue = false;
while (cursor !== null) {
var node = cursor.data;
var type = node.type;
switch (type) {
case 'Number':
case 'Percentage':
if (wasValue) {
return;
}
wasValue = true;
args.push({
type: type,
value: Number(node.value)
});
break;
case 'Operator':
if (node.value === ',') {
if (!wasValue) {
return;
}
wasValue = false;
} else if (wasValue || node.value !== '+') {
return;
}
break;
default:
// something we couldn't understand
return;
}
cursor = cursor.next;
}
if (args.length !== count) {
// invalid arguments count
// TODO: remove those tokens
return;
}
if (args.length === 4) {
if (args[3].type !== 'Number') {
// 4th argument should be a number
// TODO: remove those tokens
return;
}
args[3].type = 'Alpha';
}
if (rgb) {
if (args[0].type !== args[1].type || args[0].type !== args[2].type) {
// invalid color, numbers and percentage shouldn't be mixed
// TODO: remove those tokens
return;
}
} else {
if (args[0].type !== 'Number' ||
args[1].type !== 'Percentage' ||
args[2].type !== 'Percentage') {
// invalid color, for hsl values should be: number, percentage, percentage
// TODO: remove those tokens
return;
}
args[0].type = 'Angle';
}
return args.map(function(arg) {
var value = Math.max(0, arg.value);
switch (arg.type) {
case 'Number':
// fit value to [0..255] range
value = Math.min(value, 255);
break;
case 'Percentage':
// convert 0..100% to value in [0..255] range
value = Math.min(value, 100) / 100;
if (!rgb) {
return value;
}
value = 255 * value;
break;
case 'Angle':
// fit value to (-360..360) range
return (((value % 360) + 360) % 360) / 360;
case 'Alpha':
// fit value to [0..1] range
return Math.min(value, 1);
}
return Math.round(value);
});
}
function compressFunction(node, item, list) {
var functionName = node.name;
var args;
if (functionName === 'rgba' || functionName === 'hsla') {
args = parseFunctionArgs(node.children, 4, functionName === 'rgba');
if (!args) {
// something went wrong
return;
}
if (functionName === 'hsla') {
args = hslToRgb.apply(null, args);
node.name = 'rgba';
}
if (args[3] === 0) {
// try to replace `rgba(x, x, x, 0)` to `transparent`
// always replace `rgba(0, 0, 0, 0)` to `transparent`
// otherwise avoid replacement in gradients since it may break color transition
// http://stackoverflow.com/questions/11829410/css3-gradient-rendering-issues-from-transparent-to-white
var scopeFunctionName = this['function'] && this['function'].name;
if ((args[0] === 0 && args[1] === 0 && args[2] === 0) ||
!/^(?:to|from|color-stop)$|gradient$/i.test(scopeFunctionName)) {
item.data = {
type: 'Identifier',
loc: node.loc,
name: 'transparent'
};
return;
}
}
if (args[3] !== 1) {
// replace argument values for normalized/interpolated
node.children.each(function(node, item, list) {
if (node.type === 'Operator') {
if (node.value !== ',') {
list.remove(item);
}
return;
}
item.data = {
type: 'Number',
loc: node.loc,
value: packNumber(args.shift(), null)
};
});
return;
}
// otherwise convert to rgb, i.e. rgba(255, 0, 0, 1) -> rgb(255, 0, 0)
functionName = 'rgb';
}
if (functionName === 'hsl') {
args = args || parseFunctionArgs(node.children, 3, false);
if (!args) {
// something went wrong
return;
}
// convert to rgb
args = hslToRgb.apply(null, args);
functionName = 'rgb';
}
if (functionName === 'rgb') {
args = args || parseFunctionArgs(node.children, 3, true);
if (!args) {
// something went wrong
return;
}
// check if color is not at the end and not followed by space
var next = item.next;
if (next && next.data.type !== 'WhiteSpace') {
list.insert(list.createItem({
type: 'WhiteSpace',
value: ' '
}), next);
}
item.data = {
type: 'HexColor',
loc: node.loc,
value: toHex(args[0]) + toHex(args[1]) + toHex(args[2])
};
compressHex(item.data, item);
}
}
function compressIdent(node, item) {
if (this.declaration === null) {
return;
}
var color = node.name.toLowerCase();
if (NAME_TO_HEX.hasOwnProperty(color) &&
lexer.matchDeclaration(this.declaration).isType(node, 'color')) {
var hex = NAME_TO_HEX[color];
if (hex.length + 1 <= color.length) {
// replace for shorter hex value
item.data = {
type: 'HexColor',
loc: node.loc,
value: hex
};
} else {
// special case for consistent colors
if (color === 'grey') {
color = 'gray';
}
// just replace value for lower cased name
node.name = color;
}
}
}
function compressHex(node, item) {
var color = node.value.toLowerCase();
// #112233 -> #123
if (color.length === 6 &&
color[0] === color[1] &&
color[2] === color[3] &&
color[4] === color[5]) {
color = color[0] + color[2] + color[4];
}
if (HEX_TO_NAME[color]) {
item.data = {
type: 'Identifier',
loc: node.loc,
name: HEX_TO_NAME[color]
};
} else {
node.value = color;
}
}
module.exports = {
compressFunction: compressFunction,
compressIdent: compressIdent,
compressHex: compressHex
};

View File

@@ -0,0 +1,22 @@
var walk = require('css-tree').walkUp;
var handlers = {
Atrule: require('./Atrule'),
AttributeSelector: require('./AttributeSelector'),
Value: require('./Value'),
Dimension: require('./Dimension'),
Percentage: require('./Percentage'),
Number: require('./Number'),
String: require('./String'),
Url: require('./Url'),
HexColor: require('./color').compressHex,
Identifier: require('./color').compressIdent,
Function: require('./color').compressFunction
};
module.exports = function(ast) {
walk(ast, function(node, item, list) {
if (handlers.hasOwnProperty(node.type)) {
handlers[node.type].call(this, node, item, list);
}
});
};

View File

@@ -0,0 +1,69 @@
var List = require('css-tree').List;
module.exports = function compressBackground(node) {
function lastType() {
if (buffer.length) {
return buffer[buffer.length - 1].type;
}
}
function flush() {
if (lastType() === 'WhiteSpace') {
buffer.pop();
}
if (!buffer.length) {
buffer.unshift(
{
type: 'Number',
loc: null,
value: '0'
},
{
type: 'WhiteSpace',
value: ' '
},
{
type: 'Number',
loc: null,
value: '0'
}
);
}
newValue.push.apply(newValue, buffer);
buffer = [];
}
var newValue = [];
var buffer = [];
node.children.each(function(node) {
if (node.type === 'Operator' && node.value === ',') {
flush();
newValue.push(node);
return;
}
// remove defaults
if (node.type === 'Identifier') {
if (node.name === 'transparent' ||
node.name === 'none' ||
node.name === 'repeat' ||
node.name === 'scroll') {
return;
}
}
// don't add redundant spaces
if (node.type === 'WhiteSpace' && (!buffer.length || lastType() === 'WhiteSpace')) {
return;
}
buffer.push(node);
});
flush();
node.children = new List().fromArray(newValue);
};

View File

@@ -0,0 +1,31 @@
function removeItemAndRedundantWhiteSpace(list, item) {
var prev = item.prev;
var next = item.next;
if (next !== null) {
if (next.data.type === 'WhiteSpace' && (prev === null || prev.data.type === 'WhiteSpace')) {
list.remove(next);
}
} else if (prev !== null && prev.data.type === 'WhiteSpace') {
list.remove(prev);
}
list.remove(item);
}
module.exports = function compressBorder(node) {
node.children.each(function(node, item, list) {
if (node.type === 'Identifier' && node.name.toLowerCase() === 'none') {
if (list.head === list.tail) {
// replace `none` for zero when `none` is a single term
item.data = {
type: 'Number',
loc: node.loc,
value: '0'
};
} else {
removeItemAndRedundantWhiteSpace(list, item);
}
}
});
};

View File

@@ -0,0 +1,22 @@
module.exports = function compressFontWeight(node) {
var value = node.children.head.data;
if (value.type === 'Identifier') {
switch (value.name) {
case 'normal':
node.children.head.data = {
type: 'Number',
loc: value.loc,
value: '400'
};
break;
case 'bold':
node.children.head.data = {
type: 'Number',
loc: value.loc,
value: '700'
};
break;
}
}
};

View File

@@ -0,0 +1,45 @@
module.exports = function compressFont(node) {
var list = node.children;
list.eachRight(function(node, item) {
if (node.type === 'Identifier') {
if (node.name === 'bold') {
item.data = {
type: 'Number',
loc: node.loc,
value: '700'
};
} else if (node.name === 'normal') {
var prev = item.prev;
if (prev && prev.data.type === 'Operator' && prev.data.value === '/') {
this.remove(prev);
}
this.remove(item);
} else if (node.name === 'medium') {
var next = item.next;
if (!next || next.data.type !== 'Operator') {
this.remove(item);
}
}
}
});
// remove redundant spaces
list.each(function(node, item) {
if (node.type === 'WhiteSpace') {
if (!item.prev || !item.next || item.next.data.type === 'WhiteSpace') {
this.remove(item);
}
}
});
if (list.isEmpty()) {
list.insert(list.createItem({
type: 'Identifier',
name: 'normal'
}));
}
};

View File

@@ -0,0 +1,104 @@
var List = require('css-tree').List;
var resolveKeyword = require('css-tree').keyword;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var walkRulesRight = require('css-tree').walkRulesRight;
function addRuleToMap(map, item, list, single) {
var node = item.data;
var name = resolveKeyword(node.name).name;
var id = node.name.toLowerCase() + '/' + (node.prelude ? node.prelude.id : null);
if (!hasOwnProperty.call(map, name)) {
map[name] = Object.create(null);
}
if (single) {
delete map[name][id];
}
if (!hasOwnProperty.call(map[name], id)) {
map[name][id] = new List();
}
map[name][id].append(list.remove(item));
}
function relocateAtrules(ast, options) {
var collected = Object.create(null);
var topInjectPoint = null;
ast.children.each(function(node, item, list) {
if (node.type === 'Atrule') {
var keyword = resolveKeyword(node.name);
switch (keyword.name) {
case 'keyframes':
addRuleToMap(collected, item, list, true);
return;
case 'media':
if (options.forceMediaMerge) {
addRuleToMap(collected, item, list, false);
return;
}
break;
}
if (topInjectPoint === null &&
keyword.name !== 'charset' &&
keyword.name !== 'import') {
topInjectPoint = item;
}
} else {
if (topInjectPoint === null) {
topInjectPoint = item;
}
}
});
for (var atrule in collected) {
for (var id in collected[atrule]) {
ast.children.insertList(collected[atrule][id], atrule === 'media' ? null : topInjectPoint);
}
}
};
function isMediaRule(node) {
return node.type === 'Atrule' && node.name === 'media';
}
function processAtrule(node, item, list) {
if (!isMediaRule(node)) {
return;
}
var prev = item.prev && item.prev.data;
if (!prev || !isMediaRule(prev)) {
return;
}
// merge @media with same query
if (node.prelude &&
prev.prelude &&
node.prelude.id === prev.prelude.id) {
prev.block.children.appendList(node.block.children);
list.remove(item);
// TODO: use it when we can refer to several points in source
// prev.loc = {
// primary: prev.loc,
// merged: node.loc
// };
}
}
module.exports = function rejoinAtrule(ast, options) {
relocateAtrules(ast, options);
walkRulesRight(ast, function(node, item, list) {
if (node.type === 'Atrule') {
processAtrule(node, item, list);
}
});
};

View File

@@ -0,0 +1,48 @@
var walkRules = require('css-tree').walkRules;
var utils = require('./utils');
function processRule(node, item, list) {
var selectors = node.prelude.children;
var declarations = node.block.children;
list.prevUntil(item.prev, function(prev) {
// skip non-ruleset node if safe
if (prev.type !== 'Rule') {
return utils.unsafeToSkipNode.call(selectors, prev);
}
var prevSelectors = prev.prelude.children;
var prevDeclarations = prev.block.children;
// try to join rulesets with equal pseudo signature
if (node.pseudoSignature === prev.pseudoSignature) {
// try to join by selectors
if (utils.isEqualSelectors(prevSelectors, selectors)) {
prevDeclarations.appendList(declarations);
list.remove(item);
return true;
}
// try to join by declarations
if (utils.isEqualDeclarations(declarations, prevDeclarations)) {
utils.addSelectors(prevSelectors, selectors);
list.remove(item);
return true;
}
}
// go to prev ruleset if has no selector similarities
return utils.hasSimilarSelectors(selectors, prevSelectors);
});
}
// NOTE: direction should be left to right, since rulesets merge to left
// ruleset. When direction right to left unmerged rulesets may prevent lookup
// TODO: remove initial merge
module.exports = function initialMergeRule(ast) {
walkRules(ast, function(node, item, list) {
if (node.type === 'Rule') {
processRule(node, item, list);
}
});
};

View File

@@ -0,0 +1,42 @@
var List = require('css-tree').List;
var walkRulesRight = require('css-tree').walkRulesRight;
function processRule(node, item, list) {
var selectors = node.prelude.children;
// generate new rule sets:
// .a, .b { color: red; }
// ->
// .a { color: red; }
// .b { color: red; }
// while there are more than 1 simple selector split for rulesets
while (selectors.head !== selectors.tail) {
var newSelectors = new List();
newSelectors.insert(selectors.remove(selectors.head));
list.insert(list.createItem({
type: 'Rule',
loc: node.loc,
prelude: {
type: 'SelectorList',
loc: node.prelude.loc,
children: newSelectors
},
block: {
type: 'Block',
loc: node.block.loc,
children: node.block.children.copy()
},
pseudoSignature: node.pseudoSignature
}), item);
}
}
module.exports = function disjoinRule(ast) {
walkRulesRight(ast, function(node, item, list) {
if (node.type === 'Rule') {
processRule(node, item, list);
}
});
};

View File

@@ -0,0 +1,428 @@
var List = require('css-tree').List;
var translate = require('css-tree').translate;
var walkRulesRight = require('css-tree').walkRulesRight;
var REPLACE = 1;
var REMOVE = 2;
var TOP = 0;
var RIGHT = 1;
var BOTTOM = 2;
var LEFT = 3;
var SIDES = ['top', 'right', 'bottom', 'left'];
var SIDE = {
'margin-top': 'top',
'margin-right': 'right',
'margin-bottom': 'bottom',
'margin-left': 'left',
'padding-top': 'top',
'padding-right': 'right',
'padding-bottom': 'bottom',
'padding-left': 'left',
'border-top-color': 'top',
'border-right-color': 'right',
'border-bottom-color': 'bottom',
'border-left-color': 'left',
'border-top-width': 'top',
'border-right-width': 'right',
'border-bottom-width': 'bottom',
'border-left-width': 'left',
'border-top-style': 'top',
'border-right-style': 'right',
'border-bottom-style': 'bottom',
'border-left-style': 'left'
};
var MAIN_PROPERTY = {
'margin': 'margin',
'margin-top': 'margin',
'margin-right': 'margin',
'margin-bottom': 'margin',
'margin-left': 'margin',
'padding': 'padding',
'padding-top': 'padding',
'padding-right': 'padding',
'padding-bottom': 'padding',
'padding-left': 'padding',
'border-color': 'border-color',
'border-top-color': 'border-color',
'border-right-color': 'border-color',
'border-bottom-color': 'border-color',
'border-left-color': 'border-color',
'border-width': 'border-width',
'border-top-width': 'border-width',
'border-right-width': 'border-width',
'border-bottom-width': 'border-width',
'border-left-width': 'border-width',
'border-style': 'border-style',
'border-top-style': 'border-style',
'border-right-style': 'border-style',
'border-bottom-style': 'border-style',
'border-left-style': 'border-style'
};
function TRBL(name) {
this.name = name;
this.loc = null;
this.iehack = undefined;
this.sides = {
'top': null,
'right': null,
'bottom': null,
'left': null
};
}
TRBL.prototype.getValueSequence = function(declaration, count) {
var values = [];
var iehack = '';
var hasBadValues = declaration.value.children.some(function(child) {
var special = false;
switch (child.type) {
case 'Identifier':
switch (child.name) {
case '\\0':
case '\\9':
iehack = child.name;
return;
case 'inherit':
case 'initial':
case 'unset':
case 'revert':
special = child.name;
break;
}
break;
case 'Dimension':
switch (child.unit) {
// is not supported until IE11
case 'rem':
// v* units is too buggy across browsers and better
// don't merge values with those units
case 'vw':
case 'vh':
case 'vmin':
case 'vmax':
case 'vm': // IE9 supporting "vm" instead of "vmin".
special = child.unit;
break;
}
break;
case 'HexColor': // color
case 'Number':
case 'Percentage':
break;
case 'Function':
special = child.name;
break;
case 'WhiteSpace':
return false; // ignore space
default:
return true; // bad value
}
values.push({
node: child,
special: special,
important: declaration.important
});
});
if (hasBadValues || values.length > count) {
return false;
}
if (typeof this.iehack === 'string' && this.iehack !== iehack) {
return false;
}
this.iehack = iehack; // move outside
return values;
};
TRBL.prototype.canOverride = function(side, value) {
var currentValue = this.sides[side];
return !currentValue || (value.important && !currentValue.important);
};
TRBL.prototype.add = function(name, declaration) {
function attemptToAdd() {
var sides = this.sides;
var side = SIDE[name];
if (side) {
if (side in sides === false) {
return false;
}
var values = this.getValueSequence(declaration, 1);
if (!values || !values.length) {
return false;
}
// can mix only if specials are equal
for (var key in sides) {
if (sides[key] !== null && sides[key].special !== values[0].special) {
return false;
}
}
if (!this.canOverride(side, values[0])) {
return true;
}
sides[side] = values[0];
return true;
} else if (name === this.name) {
var values = this.getValueSequence(declaration, 4);
if (!values || !values.length) {
return false;
}
switch (values.length) {
case 1:
values[RIGHT] = values[TOP];
values[BOTTOM] = values[TOP];
values[LEFT] = values[TOP];
break;
case 2:
values[BOTTOM] = values[TOP];
values[LEFT] = values[RIGHT];
break;
case 3:
values[LEFT] = values[RIGHT];
break;
}
// can mix only if specials are equal
for (var i = 0; i < 4; i++) {
for (var key in sides) {
if (sides[key] !== null && sides[key].special !== values[i].special) {
return false;
}
}
}
for (var i = 0; i < 4; i++) {
if (this.canOverride(SIDES[i], values[i])) {
sides[SIDES[i]] = values[i];
}
}
return true;
}
}
if (!attemptToAdd.call(this)) {
return false;
}
// TODO: use it when we can refer to several points in source
// if (this.loc) {
// this.loc = {
// primary: this.loc,
// merged: declaration.loc
// };
// } else {
// this.loc = declaration.loc;
// }
if (!this.loc) {
this.loc = declaration.loc;
}
return true;
};
TRBL.prototype.isOkToMinimize = function() {
var top = this.sides.top;
var right = this.sides.right;
var bottom = this.sides.bottom;
var left = this.sides.left;
if (top && right && bottom && left) {
var important =
top.important +
right.important +
bottom.important +
left.important;
return important === 0 || important === 4;
}
return false;
};
TRBL.prototype.getValue = function() {
var result = new List();
var sides = this.sides;
var values = [
sides.top,
sides.right,
sides.bottom,
sides.left
];
var stringValues = [
translate(sides.top.node),
translate(sides.right.node),
translate(sides.bottom.node),
translate(sides.left.node)
];
if (stringValues[LEFT] === stringValues[RIGHT]) {
values.pop();
if (stringValues[BOTTOM] === stringValues[TOP]) {
values.pop();
if (stringValues[RIGHT] === stringValues[TOP]) {
values.pop();
}
}
}
for (var i = 0; i < values.length; i++) {
if (i) {
result.appendData({ type: 'WhiteSpace', value: ' ' });
}
result.appendData(values[i].node);
}
if (this.iehack) {
result.appendData({ type: 'WhiteSpace', value: ' ' });
result.appendData({
type: 'Identifier',
loc: null,
name: this.iehack
});
}
return {
type: 'Value',
loc: null,
children: result
};
};
TRBL.prototype.getDeclaration = function() {
return {
type: 'Declaration',
loc: this.loc,
important: this.sides.top.important,
property: this.name,
value: this.getValue()
};
};
function processRule(rule, shorts, shortDeclarations, lastShortSelector) {
var declarations = rule.block.children;
var selector = rule.prelude.children.first().id;
rule.block.children.eachRight(function(declaration, item) {
var property = declaration.property;
if (!MAIN_PROPERTY.hasOwnProperty(property)) {
return;
}
var key = MAIN_PROPERTY[property];
var shorthand;
var operation;
if (!lastShortSelector || selector === lastShortSelector) {
if (key in shorts) {
operation = REMOVE;
shorthand = shorts[key];
}
}
if (!shorthand || !shorthand.add(property, declaration)) {
operation = REPLACE;
shorthand = new TRBL(key);
// if can't parse value ignore it and break shorthand children
if (!shorthand.add(property, declaration)) {
lastShortSelector = null;
return;
}
}
shorts[key] = shorthand;
shortDeclarations.push({
operation: operation,
block: declarations,
item: item,
shorthand: shorthand
});
lastShortSelector = selector;
});
return lastShortSelector;
}
function processShorthands(shortDeclarations, markDeclaration) {
shortDeclarations.forEach(function(item) {
var shorthand = item.shorthand;
if (!shorthand.isOkToMinimize()) {
return;
}
if (item.operation === REPLACE) {
item.item.data = markDeclaration(shorthand.getDeclaration());
} else {
item.block.remove(item.item);
}
});
}
module.exports = function restructBlock(ast, indexer) {
var stylesheetMap = {};
var shortDeclarations = [];
walkRulesRight(ast, function(node) {
if (node.type !== 'Rule') {
return;
}
var stylesheet = this.block || this.stylesheet;
var ruleId = (node.pseudoSignature || '') + '|' + node.prelude.children.first().id;
var ruleMap;
var shorts;
if (!stylesheetMap.hasOwnProperty(stylesheet.id)) {
ruleMap = {
lastShortSelector: null
};
stylesheetMap[stylesheet.id] = ruleMap;
} else {
ruleMap = stylesheetMap[stylesheet.id];
}
if (ruleMap.hasOwnProperty(ruleId)) {
shorts = ruleMap[ruleId];
} else {
shorts = {};
ruleMap[ruleId] = shorts;
}
ruleMap.lastShortSelector = processRule.call(this, node, shorts, shortDeclarations, ruleMap.lastShortSelector);
});
processShorthands(shortDeclarations, indexer.declaration);
};

View File

@@ -0,0 +1,296 @@
var resolveProperty = require('css-tree').property;
var resolveKeyword = require('css-tree').keyword;
var walkRulesRight = require('css-tree').walkRulesRight;
var translate = require('css-tree').translate;
var fingerprintId = 1;
var dontRestructure = {
'src': 1 // https://github.com/afelix/csso/issues/50
};
var DONT_MIX_VALUE = {
// https://developer.mozilla.org/en-US/docs/Web/CSS/display#Browser_compatibility
'display': /table|ruby|flex|-(flex)?box$|grid|contents|run-in/i,
// https://developer.mozilla.org/en/docs/Web/CSS/text-align
'text-align': /^(start|end|match-parent|justify-all)$/i
};
var CURSOR_SAFE_VALUE = [
'auto', 'crosshair', 'default', 'move', 'text', 'wait', 'help',
'n-resize', 'e-resize', 's-resize', 'w-resize',
'ne-resize', 'nw-resize', 'se-resize', 'sw-resize',
'pointer', 'progress', 'not-allowed', 'no-drop', 'vertical-text', 'all-scroll',
'col-resize', 'row-resize'
];
var POSITION_SAFE_VALUE = [
'static', 'relative', 'absolute', 'fixed'
];
var NEEDLESS_TABLE = {
'border-width': ['border'],
'border-style': ['border'],
'border-color': ['border'],
'border-top': ['border'],
'border-right': ['border'],
'border-bottom': ['border'],
'border-left': ['border'],
'border-top-width': ['border-top', 'border-width', 'border'],
'border-right-width': ['border-right', 'border-width', 'border'],
'border-bottom-width': ['border-bottom', 'border-width', 'border'],
'border-left-width': ['border-left', 'border-width', 'border'],
'border-top-style': ['border-top', 'border-style', 'border'],
'border-right-style': ['border-right', 'border-style', 'border'],
'border-bottom-style': ['border-bottom', 'border-style', 'border'],
'border-left-style': ['border-left', 'border-style', 'border'],
'border-top-color': ['border-top', 'border-color', 'border'],
'border-right-color': ['border-right', 'border-color', 'border'],
'border-bottom-color': ['border-bottom', 'border-color', 'border'],
'border-left-color': ['border-left', 'border-color', 'border'],
'margin-top': ['margin'],
'margin-right': ['margin'],
'margin-bottom': ['margin'],
'margin-left': ['margin'],
'padding-top': ['padding'],
'padding-right': ['padding'],
'padding-bottom': ['padding'],
'padding-left': ['padding'],
'font-style': ['font'],
'font-variant': ['font'],
'font-weight': ['font'],
'font-size': ['font'],
'font-family': ['font'],
'list-style-type': ['list-style'],
'list-style-position': ['list-style'],
'list-style-image': ['list-style']
};
function getPropertyFingerprint(propertyName, declaration, fingerprints) {
var realName = resolveProperty(propertyName).name;
if (realName === 'background') {
return propertyName + ':' + translate(declaration.value);
}
var declarationId = declaration.id;
var fingerprint = fingerprints[declarationId];
if (!fingerprint) {
switch (declaration.value.type) {
case 'Value':
var vendorId = '';
var iehack = '';
var special = {};
var raw = false;
declaration.value.children.each(function walk(node) {
switch (node.type) {
case 'Value':
case 'Brackets':
case 'Parentheses':
node.children.each(walk);
break;
case 'Raw':
raw = true;
break;
case 'Identifier':
var name = node.name;
if (!vendorId) {
vendorId = resolveKeyword(name).vendor;
}
if (/\\[09]/.test(name)) {
iehack = RegExp.lastMatch;
}
if (realName === 'cursor') {
if (CURSOR_SAFE_VALUE.indexOf(name) === -1) {
special[name] = true;
}
} else if (realName === 'position') {
if (POSITION_SAFE_VALUE.indexOf(name) === -1) {
special[name] = true;
}
} else if (DONT_MIX_VALUE.hasOwnProperty(realName)) {
if (DONT_MIX_VALUE[realName].test(name)) {
special[name] = true;
}
}
break;
case 'Function':
var name = node.name;
if (!vendorId) {
vendorId = resolveKeyword(name).vendor;
}
if (name === 'rect') {
// there are 2 forms of rect:
// rect(<top>, <right>, <bottom>, <left>) - standart
// rect(<top> <right> <bottom> <left>) backwards compatible syntax
// only the same form values can be merged
var hasComma = node.children.some(function(node) {
return node.type === 'Operator' && node.value === ',';
});
if (!hasComma) {
name = 'rect-backward';
}
}
special[name + '()'] = true;
// check nested tokens too
node.children.each(walk);
break;
case 'Dimension':
var unit = node.unit;
switch (unit) {
// is not supported until IE11
case 'rem':
// v* units is too buggy across browsers and better
// don't merge values with those units
case 'vw':
case 'vh':
case 'vmin':
case 'vmax':
case 'vm': // IE9 supporting "vm" instead of "vmin".
special[unit] = true;
break;
}
break;
}
});
fingerprint = raw
? '!' + fingerprintId++
: '!' + Object.keys(special).sort() + '|' + iehack + vendorId;
break;
case 'Raw':
fingerprint = '!' + declaration.value.value;
break;
default:
fingerprint = translate(declaration.value);
}
fingerprints[declarationId] = fingerprint;
}
return propertyName + fingerprint;
}
function needless(props, declaration, fingerprints) {
var property = resolveProperty(declaration.property);
if (NEEDLESS_TABLE.hasOwnProperty(property.name)) {
var table = NEEDLESS_TABLE[property.name];
for (var i = 0; i < table.length; i++) {
var ppre = getPropertyFingerprint(property.prefix + table[i], declaration, fingerprints);
var prev = props.hasOwnProperty(ppre) ? props[ppre] : null;
if (prev && (!declaration.important || prev.item.data.important)) {
return prev;
}
}
}
}
function processRule(rule, item, list, props, fingerprints) {
var declarations = rule.block.children;
declarations.eachRight(function(declaration, declarationItem) {
var property = declaration.property;
var fingerprint = getPropertyFingerprint(property, declaration, fingerprints);
var prev = props[fingerprint];
if (prev && !dontRestructure.hasOwnProperty(property)) {
if (declaration.important && !prev.item.data.important) {
props[fingerprint] = {
block: declarations,
item: declarationItem
};
prev.block.remove(prev.item);
// TODO: use it when we can refer to several points in source
// declaration.loc = {
// primary: declaration.loc,
// merged: prev.item.data.loc
// };
} else {
declarations.remove(declarationItem);
// TODO: use it when we can refer to several points in source
// prev.item.data.loc = {
// primary: prev.item.data.loc,
// merged: declaration.loc
// };
}
} else {
var prev = needless(props, declaration, fingerprints);
if (prev) {
declarations.remove(declarationItem);
// TODO: use it when we can refer to several points in source
// prev.item.data.loc = {
// primary: prev.item.data.loc,
// merged: declaration.loc
// };
} else {
declaration.fingerprint = fingerprint;
props[fingerprint] = {
block: declarations,
item: declarationItem
};
}
}
});
if (declarations.isEmpty()) {
list.remove(item);
}
}
module.exports = function restructBlock(ast) {
var stylesheetMap = {};
var fingerprints = Object.create(null);
walkRulesRight(ast, function(node, item, list) {
if (node.type !== 'Rule') {
return;
}
var stylesheet = this.block || this.stylesheet;
var ruleId = (node.pseudoSignature || '') + '|' + node.prelude.children.first().id;
var ruleMap;
var props;
if (!stylesheetMap.hasOwnProperty(stylesheet.id)) {
ruleMap = {};
stylesheetMap[stylesheet.id] = ruleMap;
} else {
ruleMap = stylesheetMap[stylesheet.id];
}
if (ruleMap.hasOwnProperty(ruleId)) {
props = ruleMap[ruleId];
} else {
props = {};
ruleMap[ruleId] = props;
}
processRule.call(this, node, item, list, props, fingerprints);
});
};

View File

@@ -0,0 +1,87 @@
var walkRules = require('css-tree').walkRules;
var utils = require('./utils');
/*
At this step all rules has single simple selector. We try to join by equal
declaration blocks to first rule, e.g.
.a { color: red }
b { ... }
.b { color: red }
->
.a, .b { color: red }
b { ... }
*/
function processRule(node, item, list) {
var selectors = node.prelude.children;
var declarations = node.block.children;
var nodeCompareMarker = selectors.first().compareMarker;
var skippedCompareMarkers = {};
list.nextUntil(item.next, function(next, nextItem) {
// skip non-ruleset node if safe
if (next.type !== 'Rule') {
return utils.unsafeToSkipNode.call(selectors, next);
}
if (node.pseudoSignature !== next.pseudoSignature) {
return true;
}
var nextFirstSelector = next.prelude.children.head;
var nextDeclarations = next.block.children;
var nextCompareMarker = nextFirstSelector.data.compareMarker;
// if next ruleset has same marked as one of skipped then stop joining
if (nextCompareMarker in skippedCompareMarkers) {
return true;
}
// try to join by selectors
if (selectors.head === selectors.tail) {
if (selectors.first().id === nextFirstSelector.data.id) {
declarations.appendList(nextDeclarations);
list.remove(nextItem);
return;
}
}
// try to join by properties
if (utils.isEqualDeclarations(declarations, nextDeclarations)) {
var nextStr = nextFirstSelector.data.id;
selectors.some(function(data, item) {
var curStr = data.id;
if (nextStr < curStr) {
selectors.insert(nextFirstSelector, item);
return true;
}
if (!item.next) {
selectors.insert(nextFirstSelector);
return true;
}
});
list.remove(nextItem);
return;
}
// go to next ruleset if current one can be skipped (has no equal specificity nor element selector)
if (nextCompareMarker === nodeCompareMarker) {
return true;
}
skippedCompareMarkers[nextCompareMarker] = true;
});
}
module.exports = function mergeRule(ast) {
walkRules(ast, function(node, item, list) {
if (node.type === 'Rule') {
processRule(node, item, list);
}
});
};

View File

@@ -0,0 +1,157 @@
var List = require('css-tree').List;
var walkRulesRight = require('css-tree').walkRulesRight;
var utils = require('./utils');
function calcSelectorLength(list) {
var length = 0;
list.each(function(data) {
length += data.id.length + 1;
});
return length - 1;
}
function calcDeclarationsLength(tokens) {
var length = 0;
for (var i = 0; i < tokens.length; i++) {
length += tokens[i].length;
}
return (
length + // declarations
tokens.length - 1 // delimeters
);
}
function processRule(node, item, list) {
var avoidRulesMerge = this.block !== null ? this.block.avoidRulesMerge : false;
var selectors = node.prelude.children;
var block = node.block;
var disallowDownMarkers = Object.create(null);
var allowMergeUp = true;
var allowMergeDown = true;
list.prevUntil(item.prev, function(prev, prevItem) {
// skip non-ruleset node if safe
if (prev.type !== 'Rule') {
return utils.unsafeToSkipNode.call(selectors, prev);
}
var prevSelectors = prev.prelude.children;
var prevBlock = prev.block;
if (node.pseudoSignature !== prev.pseudoSignature) {
return true;
}
allowMergeDown = !prevSelectors.some(function(selector) {
return selector.compareMarker in disallowDownMarkers;
});
// try prev ruleset if simpleselectors has no equal specifity and element selector
if (!allowMergeDown && !allowMergeUp) {
return true;
}
// try to join by selectors
if (allowMergeUp && utils.isEqualSelectors(prevSelectors, selectors)) {
prevBlock.children.appendList(block.children);
list.remove(item);
return true;
}
// try to join by properties
var diff = utils.compareDeclarations(block.children, prevBlock.children);
// console.log(diff.eq, diff.ne1, diff.ne2);
if (diff.eq.length) {
if (!diff.ne1.length && !diff.ne2.length) {
// equal blocks
if (allowMergeDown) {
utils.addSelectors(selectors, prevSelectors);
list.remove(prevItem);
}
return true;
} else if (!avoidRulesMerge) { /* probably we don't need to prevent those merges for @keyframes
TODO: need to be checked */
if (diff.ne1.length && !diff.ne2.length) {
// prevBlock is subset block
var selectorLength = calcSelectorLength(selectors);
var blockLength = calcDeclarationsLength(diff.eq); // declarations length
if (allowMergeUp && selectorLength < blockLength) {
utils.addSelectors(prevSelectors, selectors);
block.children = new List().fromArray(diff.ne1);
}
} else if (!diff.ne1.length && diff.ne2.length) {
// node is subset of prevBlock
var selectorLength = calcSelectorLength(prevSelectors);
var blockLength = calcDeclarationsLength(diff.eq); // declarations length
if (allowMergeDown && selectorLength < blockLength) {
utils.addSelectors(selectors, prevSelectors);
prevBlock.children = new List().fromArray(diff.ne2);
}
} else {
// diff.ne1.length && diff.ne2.length
// extract equal block
var newSelector = {
type: 'SelectorList',
loc: null,
children: utils.addSelectors(prevSelectors.copy(), selectors)
};
var newBlockLength = calcSelectorLength(newSelector.children) + 2; // selectors length + curly braces length
var blockLength = calcDeclarationsLength(diff.eq); // declarations length
// create new ruleset if declarations length greater than
// ruleset description overhead
if (allowMergeDown && blockLength >= newBlockLength) {
var newRule = {
type: 'Rule',
loc: null,
prelude: newSelector,
block: {
type: 'Block',
loc: null,
children: new List().fromArray(diff.eq)
},
pseudoSignature: node.pseudoSignature
};
block.children = new List().fromArray(diff.ne1);
prevBlock.children = new List().fromArray(diff.ne2.concat(diff.ne2overrided));
list.insert(list.createItem(newRule), prevItem);
return true;
}
}
}
}
if (allowMergeUp) {
// TODO: disallow up merge only if any property interception only (i.e. diff.ne2overrided.length > 0);
// await property families to find property interception correctly
allowMergeUp = !prevSelectors.some(function(prevSelector) {
return selectors.some(function(selector) {
return selector.compareMarker === prevSelector.compareMarker;
});
});
}
prevSelectors.each(function(data) {
disallowDownMarkers[data.compareMarker] = true;
});
});
}
module.exports = function restructRule(ast) {
walkRulesRight(ast, function(node, item, list) {
if (node.type === 'Rule') {
processRule.call(this, node, item, list);
}
});
};

View File

@@ -0,0 +1,35 @@
var prepare = require('./prepare/index');
var mergeAtrule = require('./1-mergeAtrule');
var initialMergeRuleset = require('./2-initialMergeRuleset');
var disjoinRuleset = require('./3-disjoinRuleset');
var restructShorthand = require('./4-restructShorthand');
var restructBlock = require('./6-restructBlock');
var mergeRuleset = require('./7-mergeRuleset');
var restructRuleset = require('./8-restructRuleset');
module.exports = function(ast, options) {
// prepare ast for restructing
var indexer = prepare(ast, options);
options.logger('prepare', ast);
mergeAtrule(ast, options);
options.logger('mergeAtrule', ast);
initialMergeRuleset(ast);
options.logger('initialMergeRuleset', ast);
disjoinRuleset(ast);
options.logger('disjoinRuleset', ast);
restructShorthand(ast, indexer);
options.logger('restructShorthand', ast);
restructBlock(ast);
options.logger('restructBlock', ast);
mergeRuleset(ast);
options.logger('mergeRuleset', ast);
restructRuleset(ast);
options.logger('restructRuleset', ast);
};

View File

@@ -0,0 +1,31 @@
var translate = require('css-tree').translate;
function Index() {
this.seed = 0;
this.map = Object.create(null);
}
Index.prototype.resolve = function(str) {
var index = this.map[str];
if (!index) {
index = ++this.seed;
this.map[str] = index;
}
return index;
};
module.exports = function createDeclarationIndexer() {
var ids = new Index();
return function markDeclaration(node) {
var id = translate(node);
node.id = ids.resolve(id);
node.length = id.length;
node.fingerprint = null;
return node;
};
};

View File

@@ -0,0 +1,45 @@
var resolveKeyword = require('css-tree').keyword;
var walkRules = require('css-tree').walkRules;
var translate = require('css-tree').translate;
var createDeclarationIndexer = require('./createDeclarationIndexer');
var processSelector = require('./processSelector');
function walk(node, markDeclaration, options) {
switch (node.type) {
case 'Rule':
node.block.children.each(markDeclaration);
processSelector(node, options.usage);
break;
case 'Atrule':
if (node.prelude) {
node.prelude.id = null; // pre-init property to avoid multiple hidden class for translate
node.prelude.id = translate(node.prelude);
}
// compare keyframe selectors by its values
// NOTE: still no clarification about problems with keyframes selector grouping (issue #197)
if (resolveKeyword(node.name).name === 'keyframes') {
node.block.avoidRulesMerge = true; /* probably we don't need to prevent those merges for @keyframes
TODO: need to be checked */
node.block.children.each(function(rule) {
rule.prelude.children.each(function(simpleselector) {
simpleselector.compareMarker = simpleselector.id;
});
});
}
break;
}
}
module.exports = function prepare(ast, options) {
var markDeclaration = createDeclarationIndexer();
walkRules(ast, function(node) {
walk(node, markDeclaration, options);
});
return {
declaration: markDeclaration
};
};

View File

@@ -0,0 +1,94 @@
var translate = require('css-tree').translate;
var specificity = require('./specificity');
var nonFreezePseudoElements = {
'first-letter': true,
'first-line': true,
'after': true,
'before': true
};
var nonFreezePseudoClasses = {
'link': true,
'visited': true,
'hover': true,
'active': true,
'first-letter': true,
'first-line': true,
'after': true,
'before': true
};
module.exports = function freeze(node, usageData) {
var pseudos = Object.create(null);
var hasPseudo = false;
node.prelude.children.each(function(simpleSelector) {
var tagName = '*';
var scope = 0;
simpleSelector.children.each(function(node) {
switch (node.type) {
case 'ClassSelector':
if (usageData && usageData.scopes) {
var classScope = usageData.scopes[node.name] || 0;
if (scope !== 0 && classScope !== scope) {
throw new Error('Selector can\'t has classes from different scopes: ' + translate(simpleSelector));
}
scope = classScope;
}
break;
case 'PseudoClassSelector':
var name = node.name.toLowerCase();
if (!nonFreezePseudoClasses.hasOwnProperty(name)) {
pseudos[name] = true;
hasPseudo = true;
}
break;
case 'PseudoElementSelector':
var name = node.name.toLowerCase();
if (!nonFreezePseudoElements.hasOwnProperty(name)) {
pseudos[name] = true;
hasPseudo = true;
}
break;
case 'TypeSelector':
tagName = node.name.toLowerCase();
break;
case 'AttributeSelector':
if (node.flags) {
pseudos['[' + node.flags.toLowerCase() + ']'] = true;
hasPseudo = true;
}
break;
case 'WhiteSpace':
case 'Combinator':
tagName = '*';
break;
}
});
simpleSelector.compareMarker = specificity(simpleSelector).toString();
simpleSelector.id = null; // pre-init property to avoid multiple hidden class
simpleSelector.id = translate(simpleSelector);
if (scope) {
simpleSelector.compareMarker += ':' + scope;
}
if (tagName !== '*') {
simpleSelector.compareMarker += ',' + tagName;
}
});
// add property to all rule nodes to avoid multiple hidden class
node.pseudoSignature = hasPseudo && Object.keys(pseudos).sort().join(',');
};

View File

@@ -0,0 +1,57 @@
module.exports = function specificity(simpleSelector) {
var A = 0;
var B = 0;
var C = 0;
simpleSelector.children.each(function walk(node) {
switch (node.type) {
case 'SelectorList':
case 'Selector':
node.children.each(walk);
break;
case 'IdSelector':
A++;
break;
case 'ClassSelector':
case 'AttributeSelector':
B++;
break;
case 'PseudoClassSelector':
switch (node.name.toLowerCase()) {
case 'not':
node.children.each(walk);
break;
case 'before':
case 'after':
case 'first-line':
case 'first-letter':
C++;
break;
// TODO: support for :nth-*(.. of <SelectorList>), :matches(), :has()
default:
B++;
}
break;
case 'PseudoElementSelector':
C++;
break;
case 'TypeSelector':
// ignore universal selector
if (node.name.charAt(node.name.length - 1) !== '*') {
C++;
}
break;
}
});
return [A, B, C];
};

View File

@@ -0,0 +1,151 @@
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEqualSelectors(a, b) {
var cursor1 = a.head;
var cursor2 = b.head;
while (cursor1 !== null && cursor2 !== null && cursor1.data.id === cursor2.data.id) {
cursor1 = cursor1.next;
cursor2 = cursor2.next;
}
return cursor1 === null && cursor2 === null;
}
function isEqualDeclarations(a, b) {
var cursor1 = a.head;
var cursor2 = b.head;
while (cursor1 !== null && cursor2 !== null && cursor1.data.id === cursor2.data.id) {
cursor1 = cursor1.next;
cursor2 = cursor2.next;
}
return cursor1 === null && cursor2 === null;
}
function compareDeclarations(declarations1, declarations2) {
var result = {
eq: [],
ne1: [],
ne2: [],
ne2overrided: []
};
var fingerprints = Object.create(null);
var declarations2hash = Object.create(null);
for (var cursor = declarations2.head; cursor; cursor = cursor.next) {
declarations2hash[cursor.data.id] = true;
}
for (var cursor = declarations1.head; cursor; cursor = cursor.next) {
var data = cursor.data;
if (data.fingerprint) {
fingerprints[data.fingerprint] = data.important;
}
if (declarations2hash[data.id]) {
declarations2hash[data.id] = false;
result.eq.push(data);
} else {
result.ne1.push(data);
}
}
for (var cursor = declarations2.head; cursor; cursor = cursor.next) {
var data = cursor.data;
if (declarations2hash[data.id]) {
// if declarations1 has overriding declaration, this is not a difference
// but take in account !important - prev should be equal or greater than follow
if (hasOwnProperty.call(fingerprints, data.fingerprint) &&
Number(fingerprints[data.fingerprint]) >= Number(data.important)) {
result.ne2overrided.push(data);
} else {
result.ne2.push(data);
}
}
}
return result;
}
function addSelectors(dest, source) {
source.each(function(sourceData) {
var newStr = sourceData.id;
var cursor = dest.head;
while (cursor) {
var nextStr = cursor.data.id;
if (nextStr === newStr) {
return;
}
if (nextStr > newStr) {
break;
}
cursor = cursor.next;
}
dest.insert(dest.createItem(sourceData), cursor);
});
return dest;
}
// check if simpleselectors has no equal specificity and element selector
function hasSimilarSelectors(selectors1, selectors2) {
var cursor1 = selectors1.head;
while (cursor1 !== null) {
var cursor2 = selectors2.head;
while (cursor2 !== null) {
if (cursor1.data.compareMarker === cursor2.data.compareMarker) {
return true;
}
cursor2 = cursor2.next;
}
cursor1 = cursor1.next;
}
return false;
}
// test node can't to be skipped
function unsafeToSkipNode(node) {
switch (node.type) {
case 'Rule':
// unsafe skip ruleset with selector similarities
return hasSimilarSelectors(node.prelude.children, this);
case 'Atrule':
// can skip at-rules with blocks
if (node.block) {
// unsafe skip at-rule if block contains something unsafe to skip
return node.block.children.some(unsafeToSkipNode, this);
}
break;
case 'Declaration':
return false;
}
// unsafe by default
return true;
}
module.exports = {
isEqualSelectors: isEqualSelectors,
isEqualDeclarations: isEqualDeclarations,
compareDeclarations: compareDeclarations,
addSelectors: addSelectors,
hasSimilarSelectors: hasSimilarSelectors,
unsafeToSkipNode: unsafeToSkipNode
};

View File

@@ -0,0 +1,79 @@
var hasOwnProperty = Object.prototype.hasOwnProperty;
function buildMap(list, caseInsensitive) {
var map = Object.create(null);
if (!Array.isArray(list)) {
return null;
}
for (var i = 0; i < list.length; i++) {
var name = list[i];
if (caseInsensitive) {
name = name.toLowerCase();
}
map[name] = true;
}
return map;
}
function buildList(data) {
if (!data) {
return null;
}
var tags = buildMap(data.tags, true);
var ids = buildMap(data.ids);
var classes = buildMap(data.classes);
if (tags === null &&
ids === null &&
classes === null) {
return null;
}
return {
tags: tags,
ids: ids,
classes: classes
};
}
function buildIndex(data) {
var scopes = false;
if (data.scopes && Array.isArray(data.scopes)) {
scopes = Object.create(null);
for (var i = 0; i < data.scopes.length; i++) {
var list = data.scopes[i];
if (!list || !Array.isArray(list)) {
throw new Error('Wrong usage format');
}
for (var j = 0; j < list.length; j++) {
var name = list[j];
if (hasOwnProperty.call(scopes, name)) {
throw new Error('Class can\'t be used for several scopes: ' + name);
}
scopes[name] = i + 1;
}
}
}
return {
whitelist: buildList(data),
blacklist: buildList(data.blacklist),
scopes: scopes
};
}
module.exports = {
buildIndex: buildIndex
};

View File

@@ -0,0 +1,114 @@
{
"_from": "csso@^3.3.1",
"_id": "csso@3.4.0",
"_inBundle": false,
"_integrity": "sha1-V7J+9VPMy/WqlkxkF0hkHprxE/M=",
"_location": "/imagemin-svgo/csso",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "csso@^3.3.1",
"name": "csso",
"escapedName": "csso",
"rawSpec": "^3.3.1",
"saveSpec": null,
"fetchSpec": "^3.3.1"
},
"_requiredBy": [
"/imagemin-svgo/svgo"
],
"_resolved": "https://registry.npmjs.org/csso/-/csso-3.4.0.tgz",
"_shasum": "57b27ef553cccbf5aa964c641748641e9af113f3",
"_spec": "csso@^3.3.1",
"_where": "/Users/asciidisco/Desktop/asciidisco.com/build/node_modules/imagemin-svgo/node_modules/svgo",
"author": {
"name": "Sergey Kryzhanovsky",
"email": "skryzhanovsky@ya.ru",
"url": "https://github.com/afelix"
},
"bugs": {
"url": "https://github.com/css/csso/issues"
},
"bundleDependencies": false,
"dependencies": {
"css-tree": "1.0.0-alpha25"
},
"deprecated": false,
"description": "CSS minifier with structural optimisations",
"devDependencies": {
"browserify": "^13.0.0",
"coveralls": "^2.11.6",
"eslint": "^2.2.0",
"istanbul": "^0.4.2",
"jscs": "~2.10.0",
"mocha": "~2.4.2",
"package-json-versionify": "^1.0.4",
"source-map": "^0.5.6",
"uglify-js": "^2.6.1"
},
"engines": {
"node": ">=0.10.0"
},
"eslintConfig": {
"env": {
"node": true,
"mocha": true,
"es6": true
},
"rules": {
"no-duplicate-case": 2,
"no-undef": 2,
"no-unused-vars": [
2,
{
"vars": "all",
"args": "after-used"
}
]
}
},
"files": [
"dist/csso-browser.js",
"lib",
"HISTORY.md",
"LICENSE",
"README.md"
],
"homepage": "https://github.com/css/csso",
"keywords": [
"css",
"compress",
"minifier",
"minify",
"optimise",
"optimisation",
"csstree"
],
"license": "MIT",
"main": "./lib/index",
"maintainers": [
{
"name": "Roman Dvornov",
"email": "rdvornov@gmail.com"
}
],
"name": "csso",
"repository": {
"type": "git",
"url": "git+https://github.com/css/csso.git"
},
"scripts": {
"browserify": "browserify -t package-json-versionify --standalone csso lib/index.js | uglifyjs --compress --mangle -o dist/csso-browser.js",
"codestyle": "jscs lib test && eslint lib test",
"codestyle-and-test": "npm run codestyle && npm test",
"coverage": "istanbul cover _mocha -- -R dot",
"coveralls": "istanbul cover _mocha --report lcovonly -- -R dot && cat ./coverage/lcov.info | coveralls",
"gh-pages": "git clone -b gh-pages https://github.com/css/csso.git .gh-pages && npm run browserify && cp dist/csso-browser.js .gh-pages/ && cd .gh-pages && git commit -am \"update\" && git push && cd .. && rm -rf .gh-pages",
"hydrogen": "node --trace-hydrogen --trace-phase=Z --trace-deopt --code-comments --hydrogen-track-positions --redirect-code-traces --redirect-code-traces-to=code.asm --trace_hydrogen_file=code.cfg --print-opt-code bin/csso --stat -o /dev/null",
"prepublish": "npm run browserify",
"test": "mocha --reporter dot",
"travis": "npm run codestyle-and-test && npm run coveralls"
},
"version": "3.4.0"
}

View File

@@ -0,0 +1,225 @@
2017-06-10: Version 4.0.0
* Support ES2017 async function and await expression (issue 1079)
* Support ES2017 trailing commas in function parameters (issue 1550)
* Explicitly distinguish parsing a module vs a script (issue 1576)
* Fix JSX non-empty container (issue 1786)
* Allow JSX element in a yield expression (issue 1765)
* Allow `in` expression in a concise body with a function body (issue 1793)
* Setter function argument must not be a rest parameter (issue 1693)
* Limit strict mode directive to functions with a simple parameter list (issue 1677)
* Prohibit any escape sequence in a reserved word (issue 1612)
* Only permit hex digits in hex escape sequence (issue 1619)
* Prohibit labelled class/generator/function declaration (issue 1484)
* Limit function declaration as if statement clause only in non-strict mode (issue 1657)
* Tolerate missing ) in a with and do-while statement (issue 1481)
2016-12-22: Version 3.1.3
* Support binding patterns as rest element (issue 1681)
* Account for different possible arguments of a yield expression (issue 1469)
2016-11-24: Version 3.1.2
* Ensure that import specifier is more restrictive (issue 1615)
* Fix duplicated JSX tokens (issue 1613)
* Scan template literal in a JSX expression container (issue 1622)
* Improve XHTML entity scanning in JSX (issue 1629)
2016-10-31: Version 3.1.1
* Fix assignment expression problem in an export declaration (issue 1596)
* Fix incorrect tokenization of hex digits (issue 1605)
2016-10-09: Version 3.1.0
* Do not implicitly collect comments when comment attachment is specified (issue 1553)
* Fix incorrect handling of duplicated proto shorthand fields (issue 1485)
* Prohibit initialization in some variants of for statements (issue 1309, 1561)
* Fix incorrect parsing of export specifier (issue 1578)
* Fix ESTree compatibility for assignment pattern (issue 1575)
2016-09-03: Version 3.0.0
* Support ES2016 exponentiation expression (issue 1490)
* Support JSX syntax (issue 1467)
* Use the latest Unicode 8.0 (issue 1475)
* Add the support for syntax node delegate (issue 1435)
* Fix ESTree compatibility on meta property (issue 1338)
* Fix ESTree compatibility on default parameter value (issue 1081)
* Fix ESTree compatibility on try handler (issue 1030)
2016-08-23: Version 2.7.3
* Fix tokenizer confusion with a comment (issue 1493, 1516)
2016-02-02: Version 2.7.2
* Fix out-of-bound error location in an invalid string literal (issue 1457)
* Fix shorthand object destructuring defaults in variable declarations (issue 1459)
2015-12-10: Version 2.7.1
* Do not allow trailing comma in a variable declaration (issue 1360)
* Fix assignment to `let` in non-strict mode (issue 1376)
* Fix missing delegate property in YieldExpression (issue 1407)
2015-10-22: Version 2.7.0
* Fix the handling of semicolon in a break statement (issue 1044)
* Run the test suite with major web browsers (issue 1259, 1317)
* Allow `let` as an identifier in non-strict mode (issue 1289)
* Attach orphaned comments as `innerComments` (issue 1328)
* Add the support for token delegator (issue 1332)
2015-09-01: Version 2.6.0
* Properly allow or prohibit `let` in a binding identifier/pattern (issue 1048, 1098)
* Add sourceType field for Program node (issue 1159)
* Ensure that strict mode reserved word binding throw an error (issue 1171)
* Run the test suite with Node.js and IE 11 on Windows (issue 1294)
* Allow binding pattern with no initializer in a for statement (issue 1301)
2015-07-31: Version 2.5.0
* Run the test suite in a browser environment (issue 1004)
* Ensure a comma between imported default binding and named imports (issue 1046)
* Distinguish `yield` as a keyword vs an identifier (issue 1186)
* Support ES6 meta property `new.target` (issue 1203)
* Fix the syntax node for yield with expression (issue 1223)
* Fix the check of duplicated proto in property names (issue 1225)
* Fix ES6 Unicode escape in identifier name (issue 1229)
* Support ES6 IdentifierStart and IdentifierPart (issue 1232)
* Treat await as a reserved word when parsing as a module (issue 1234)
* Recognize identifier characters from Unicode SMP (issue 1244)
* Ensure that export and import can be followed by a comma (issue 1250)
* Fix yield operator precedence (issue 1262)
2015-07-01: Version 2.4.1
* Fix some cases of comment attachment (issue 1071, 1175)
* Fix the handling of destructuring in function arguments (issue 1193)
* Fix invalid ranges in assignment expression (issue 1201)
2015-06-26: Version 2.4.0
* Support ES6 for-of iteration (issue 1047)
* Support ES6 spread arguments (issue 1169)
* Minimize npm payload (issue 1191)
2015-06-16: Version 2.3.0
* Support ES6 generator (issue 1033)
* Improve parsing of regular expressions with `u` flag (issue 1179)
2015-04-17: Version 2.2.0
* Support ES6 import and export declarations (issue 1000)
* Fix line terminator before arrow not recognized as error (issue 1009)
* Support ES6 destructuring (issue 1045)
* Support ES6 template literal (issue 1074)
* Fix the handling of invalid/incomplete string escape sequences (issue 1106)
* Fix ES3 static member access restriction (issue 1120)
* Support for `super` in ES6 class (issue 1147)
2015-03-09: Version 2.1.0
* Support ES6 class (issue 1001)
* Support ES6 rest parameter (issue 1011)
* Expand the location of property getter, setter, and methods (issue 1029)
* Enable TryStatement transition to a single handler (issue 1031)
* Support ES6 computed property name (issue 1037)
* Tolerate unclosed block comment (issue 1041)
* Support ES6 lexical declaration (issue 1065)
2015-02-06: Version 2.0.0
* Support ES6 arrow function (issue 517)
* Support ES6 Unicode code point escape (issue 521)
* Improve the speed and accuracy of comment attachment (issue 522)
* Support ES6 default parameter (issue 519)
* Support ES6 regular expression flags (issue 557)
* Fix scanning of implicit octal literals (issue 565)
* Fix the handling of automatic semicolon insertion (issue 574)
* Support ES6 method definition (issue 620)
* Support ES6 octal integer literal (issue 621)
* Support ES6 binary integer literal (issue 622)
* Support ES6 object literal property value shorthand (issue 624)
2015-03-03: Version 1.2.5
* Fix scanning of implicit octal literals (issue 565)
2015-02-05: Version 1.2.4
* Fix parsing of LeftHandSideExpression in ForInStatement (issue 560)
* Fix the handling of automatic semicolon insertion (issue 574)
2015-01-18: Version 1.2.3
* Fix division by this (issue 616)
2014-05-18: Version 1.2.2
* Fix duplicated tokens when collecting comments (issue 537)
2014-05-04: Version 1.2.1
* Ensure that Program node may still have leading comments (issue 536)
2014-04-29: Version 1.2.0
* Fix semicolon handling for expression statement (issue 462, 533)
* Disallow escaped characters in regular expression flags (issue 503)
* Performance improvement for location tracking (issue 520)
* Improve the speed of comment attachment (issue 522)
2014-03-26: Version 1.1.1
* Fix token handling of forward slash after an array literal (issue 512)
2014-03-23: Version 1.1.0
* Optionally attach comments to the owning syntax nodes (issue 197)
* Simplify binary parsing with stack-based shift reduce (issue 352)
* Always include the raw source of literals (issue 376)
* Add optional input source information (issue 386)
* Tokenizer API for pure lexical scanning (issue 398)
* Improve the web site and its online demos (issue 337, 400, 404)
* Performance improvement for location tracking (issue 417, 424)
* Support HTML comment syntax (issue 451)
* Drop support for legacy browsers (issue 474)
2013-08-27: Version 1.0.4
* Minimize the payload for packages (issue 362)
* Fix missing cases on an empty switch statement (issue 436)
* Support escaped ] in regexp literal character classes (issue 442)
* Tolerate invalid left-hand side expression (issue 130)
2013-05-17: Version 1.0.3
* Variable declaration needs at least one declarator (issue 391)
* Fix benchmark's variance unit conversion (issue 397)
* IE < 9: \v should be treated as vertical tab (issue 405)
* Unary expressions should always have prefix: true (issue 418)
* Catch clause should only accept an identifier (issue 423)
* Tolerate setters without parameter (issue 426)
2012-11-02: Version 1.0.2
Improvement:
* Fix esvalidate JUnit output upon a syntax error (issue 374)
2012-10-28: Version 1.0.1
Improvements:
* esvalidate understands shebang in a Unix shell script (issue 361)
* esvalidate treats fatal parsing failure as an error (issue 361)
* Reduce Node.js package via .npmignore (issue 362)
2012-10-22: Version 1.0.0
Initial release.

View File

@@ -0,0 +1,21 @@
Copyright JS Foundation and other contributors, https://js.foundation/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,46 @@
[![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima)
[![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima)
[![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima)
[![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima)
**Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance,
standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
parser written in ECMAScript (also popularly known as
[JavaScript](https://en.wikipedia.org/wiki/JavaScript)).
Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat),
with the help of [many contributors](https://github.com/jquery/esprima/contributors).
### Features
- Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm))
- Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree)
- Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/)
- Optional tracking of syntax node location (index-based and line-column)
- [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima))
### API
Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program.
A simple example on Node.js REPL:
```javascript
> var esprima = require('esprima');
> var program = 'const answer = 42';
> esprima.tokenize(program);
[ { type: 'Keyword', value: 'const' },
{ type: 'Identifier', value: 'answer' },
{ type: 'Punctuator', value: '=' },
{ type: 'Numeric', value: '42' } ]
> esprima.parseScript(program);
{ type: 'Program',
body:
[ { type: 'VariableDeclaration',
declarations: [Object],
kind: 'const' } ],
sourceType: 'script' }
```
For more information, please read the [complete documentation](http://esprima.org/doc).

View File

@@ -0,0 +1,139 @@
#!/usr/bin/env node
/*
Copyright JS Foundation and other contributors, https://js.foundation/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint sloppy:true node:true rhino:true */
var fs, esprima, fname, forceFile, content, options, syntax;
if (typeof require === 'function') {
fs = require('fs');
try {
esprima = require('esprima');
} catch (e) {
esprima = require('../');
}
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = { argv: arguments, exit: quit };
process.argv.unshift('esparse.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esparse [options] [file.js]');
console.log();
console.log('Available options:');
console.log();
console.log(' --comment Gather all line and block comments in an array');
console.log(' --loc Include line-column location info for each syntax node');
console.log(' --range Include index-based range for each syntax node');
console.log(' --raw Display the raw value of literals');
console.log(' --tokens List all tokens in an array');
console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)');
console.log(' -v, --version Shows program version');
console.log();
process.exit(1);
}
options = {};
process.argv.splice(2).forEach(function (entry) {
if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') {
if (typeof fname === 'string') {
console.log('Error: more than one input file.');
process.exit(1);
} else {
fname = entry;
}
} else if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Parser (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry === '--comment') {
options.comment = true;
} else if (entry === '--loc') {
options.loc = true;
} else if (entry === '--range') {
options.range = true;
} else if (entry === '--raw') {
options.raw = true;
} else if (entry === '--tokens') {
options.tokens = true;
} else if (entry === '--tolerant') {
options.tolerant = true;
} else if (entry === '--') {
forceFile = true;
} else {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
}
});
// Special handling for regular expression literal since we need to
// convert it to a string literal, otherwise it will be decoded
// as object "{}" and the regular expression would be lost.
function adjustRegexLiteral(key, value) {
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
}
return value;
}
function run(content) {
syntax = esprima.parse(content, options);
console.log(JSON.stringify(syntax, adjustRegexLiteral, 4));
}
try {
if (fname && (fname !== '-' || forceFile)) {
run(fs.readFileSync(fname, 'utf-8'));
} else {
var content = '';
process.stdin.resume();
process.stdin.on('data', function(chunk) {
content += chunk;
});
process.stdin.on('end', function() {
run(content);
});
}
} catch (e) {
console.log('Error: ' + e.message);
process.exit(1);
}

View File

@@ -0,0 +1,236 @@
#!/usr/bin/env node
/*
Copyright JS Foundation and other contributors, https://js.foundation/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint sloppy:true plusplus:true node:true rhino:true */
/*global phantom:true */
var fs, system, esprima, options, fnames, forceFile, count;
if (typeof esprima === 'undefined') {
// PhantomJS can only require() relative files
if (typeof phantom === 'object') {
fs = require('fs');
system = require('system');
esprima = require('./esprima');
} else if (typeof require === 'function') {
fs = require('fs');
try {
esprima = require('esprima');
} catch (e) {
esprima = require('../');
}
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
}
// Shims to Node.js objects when running under PhantomJS 1.7+.
if (typeof phantom === 'object') {
fs.readFileSync = fs.read;
process = {
argv: [].slice.call(system.args),
exit: phantom.exit,
on: function (evt, callback) {
callback();
}
};
process.argv.unshift('phantomjs');
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = {
argv: arguments,
exit: quit,
on: function (evt, callback) {
callback();
}
};
process.argv.unshift('esvalidate.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esvalidate [options] [file.js...]');
console.log();
console.log('Available options:');
console.log();
console.log(' --format=type Set the report format, plain (default) or junit');
console.log(' -v, --version Print program version');
console.log();
process.exit(1);
}
options = {
format: 'plain'
};
fnames = [];
process.argv.splice(2).forEach(function (entry) {
if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') {
fnames.push(entry);
} else if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Validator (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry.slice(0, 9) === '--format=') {
options.format = entry.slice(9);
if (options.format !== 'plain' && options.format !== 'junit') {
console.log('Error: unknown report format ' + options.format + '.');
process.exit(1);
}
} else if (entry === '--') {
forceFile = true;
} else {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
}
});
if (fnames.length === 0) {
fnames.push('');
}
if (options.format === 'junit') {
console.log('<?xml version="1.0" encoding="UTF-8"?>');
console.log('<testsuites>');
}
count = 0;
function run(fname, content) {
var timestamp, syntax, name;
try {
if (typeof content !== 'string') {
throw content;
}
if (content[0] === '#' && content[1] === '!') {
content = '//' + content.substr(2, content.length);
}
timestamp = Date.now();
syntax = esprima.parse(content, { tolerant: true });
if (options.format === 'junit') {
name = fname;
if (name.lastIndexOf('/') >= 0) {
name = name.slice(name.lastIndexOf('/') + 1);
}
console.log('<testsuite name="' + fname + '" errors="0" ' +
' failures="' + syntax.errors.length + '" ' +
' tests="' + syntax.errors.length + '" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) +
'">');
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
console.log(' <testcase name="Line ' + error.lineNumber + ': ' + msg + '" ' +
' time="0">');
console.log(' <error type="SyntaxError" message="' + error.message + '">' +
error.message + '(' + name + ':' + error.lineNumber + ')' +
'</error>');
console.log(' </testcase>');
});
console.log('</testsuite>');
} else if (options.format === 'plain') {
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
msg = fname + ':' + error.lineNumber + ': ' + msg;
console.log(msg);
++count;
});
}
} catch (e) {
++count;
if (options.format === 'junit') {
console.log('<testsuite name="' + fname + '" errors="1" failures="0" tests="1" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) + '">');
console.log(' <testcase name="' + e.message + '" ' + ' time="0">');
console.log(' <error type="ParseError" message="' + e.message + '">' +
e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') +
')</error>');
console.log(' </testcase>');
console.log('</testsuite>');
} else {
console.log(fname + ':' + e.lineNumber + ': ' + e.message.replace(/^Line\ [0-9]*\:\ /, ''));
}
}
}
fnames.forEach(function (fname) {
var content = '';
try {
if (fname && (fname !== '-' || forceFile)) {
content = fs.readFileSync(fname, 'utf-8');
} else {
fname = '';
process.stdin.resume();
process.stdin.on('data', function(chunk) {
content += chunk;
});
process.stdin.on('end', function() {
run(fname, content);
});
return;
}
} catch (e) {
content = e;
}
run(fname, content);
});
process.on('exit', function () {
if (options.format === 'junit') {
console.log('</testsuites>');
}
if (count > 0) {
process.exit(1);
}
if (count === 0 && typeof phantom === 'object') {
process.exit(0);
}
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,137 @@
{
"_from": "esprima@^4.0.0",
"_id": "esprima@4.0.0",
"_inBundle": false,
"_integrity": "sha512-oftTcaMu/EGrEIu904mWteKIv8vMuOgGYo7EhVJJN00R/EED9DCua/xxHRdYnKtcECzVg7xOWhflvJMnqcFZjw==",
"_location": "/imagemin-svgo/esprima",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "esprima@^4.0.0",
"name": "esprima",
"escapedName": "esprima",
"rawSpec": "^4.0.0",
"saveSpec": null,
"fetchSpec": "^4.0.0"
},
"_requiredBy": [
"/imagemin-svgo/js-yaml"
],
"_resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz",
"_shasum": "4499eddcd1110e0b218bacf2fa7f7f59f55ca804",
"_spec": "esprima@^4.0.0",
"_where": "/Users/asciidisco/Desktop/asciidisco.com/build/node_modules/imagemin-svgo/node_modules/js-yaml",
"author": {
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com"
},
"bin": {
"esparse": "./bin/esparse.js",
"esvalidate": "./bin/esvalidate.js"
},
"bugs": {
"url": "https://github.com/jquery/esprima/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "ECMAScript parsing infrastructure for multipurpose analysis",
"devDependencies": {
"codecov.io": "~0.1.6",
"escomplex-js": "1.2.0",
"everything.js": "~1.0.3",
"glob": "~7.1.0",
"istanbul": "~0.4.0",
"json-diff": "~0.3.1",
"karma": "~1.3.0",
"karma-chrome-launcher": "~2.0.0",
"karma-detect-browsers": "~2.2.3",
"karma-edge-launcher": "~0.2.0",
"karma-firefox-launcher": "~1.0.0",
"karma-ie-launcher": "~1.0.0",
"karma-mocha": "~1.3.0",
"karma-safari-launcher": "~1.0.0",
"karma-safaritechpreview-launcher": "~0.0.4",
"karma-sauce-launcher": "~1.1.0",
"lodash": "~3.10.1",
"mocha": "~3.2.0",
"node-tick-processor": "~0.0.2",
"regenerate": "~1.3.2",
"temp": "~0.8.3",
"tslint": "~5.1.0",
"typescript": "~2.3.2",
"typescript-formatter": "~5.1.3",
"unicode-8.0.0": "~0.7.0",
"webpack": "~1.14.0"
},
"engines": {
"node": ">=4"
},
"files": [
"bin",
"dist/esprima.js"
],
"homepage": "http://esprima.org",
"keywords": [
"ast",
"ecmascript",
"esprima",
"javascript",
"parser",
"syntax"
],
"license": "BSD-2-Clause",
"main": "dist/esprima.js",
"maintainers": [
{
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com",
"url": "http://ariya.ofilabs.com"
}
],
"name": "esprima",
"repository": {
"type": "git",
"url": "git+https://github.com/jquery/esprima.git"
},
"scripts": {
"all-tests": "npm run verify-line-ending && npm run generate-fixtures && npm run unit-tests && npm run api-tests && npm run grammar-tests && npm run regression-tests && npm run hostile-env-tests",
"analyze-coverage": "istanbul cover test/unit-tests.js",
"api-tests": "mocha -R dot test/api-tests.js",
"appveyor": "npm run compile && npm run all-tests && npm run browser-tests",
"benchmark": "npm run benchmark-parser && npm run benchmark-tokenizer",
"benchmark-parser": "node -expose_gc test/benchmark-parser.js",
"benchmark-tokenizer": "node --expose_gc test/benchmark-tokenizer.js",
"browser-tests": "npm run compile && npm run generate-fixtures && cd test && karma start --single-run",
"check-coverage": "istanbul check-coverage --statement 100 --branch 100 --function 100",
"check-version": "node test/check-version.js",
"circleci": "npm test && npm run codecov && npm run downstream",
"code-style": "tsfmt --verify src/*.ts && tsfmt --verify test/*.js",
"codecov": "istanbul report cobertura && codecov < ./coverage/cobertura-coverage.xml",
"compile": "tsc -p src/ && webpack && node tools/fixupbundle.js",
"complexity": "node test/check-complexity.js",
"downstream": "node test/downstream.js",
"droneio": "npm run compile && npm run all-tests && npm run saucelabs",
"dynamic-analysis": "npm run analyze-coverage && npm run check-coverage",
"format-code": "tsfmt -r src/*.ts && tsfmt -r test/*.js",
"generate-fixtures": "node tools/generate-fixtures.js",
"generate-regex": "node tools/generate-identifier-regex.js",
"generate-xhtml-entities": "node tools/generate-xhtml-entities.js",
"grammar-tests": "node test/grammar-tests.js",
"hostile-env-tests": "node test/hostile-environment-tests.js",
"prepublish": "npm run compile",
"profile": "node --prof test/profile.js && mv isolate*.log v8.log && node-tick-processor",
"regression-tests": "node test/regression-tests.js",
"saucelabs": "npm run saucelabs-evergreen && npm run saucelabs-ie && npm run saucelabs-safari",
"saucelabs-evergreen": "cd test && karma start saucelabs-evergreen.conf.js",
"saucelabs-ie": "cd test && karma start saucelabs-ie.conf.js",
"saucelabs-safari": "cd test && karma start saucelabs-safari.conf.js",
"static-analysis": "npm run check-version && npm run tslint && npm run code-style && npm run complexity",
"test": "npm run compile && npm run all-tests && npm run static-analysis && npm run dynamic-analysis",
"travis": "npm test",
"tslint": "tslint src/*.ts",
"unit-tests": "node test/unit-tests.js",
"verify-line-ending": "node test/verify-line-ending.js"
},
"version": "4.0.0"
}

View File

@@ -0,0 +1,463 @@
3.10.0 / 2017-09-10
-------------------
- Fix `condenseFlow` output (quote keys for sure, instead of spaces), #371, #370.
- Dump astrals as codepoints instead of surrogate pair, #368.
3.9.1 / 2017-07-08
------------------
- Ensure stack is present for custom errors in node 7.+, #351.
3.9.0 / 2017-07-08
------------------
- Add `condenseFlow` option (to create pretty URL query params), #346.
- Support array return from safeLoadAll/loadAll, #350.
3.8.4 / 2017-05-08
------------------
- Dumper: prevent space after dash for arrays that wrap, #343.
3.8.3 / 2017-04-05
------------------
- Should not allow numbers to begin and end with underscore, #335.
3.8.2 / 2017-03-02
------------------
- Fix `!!float 123` (integers) parse, #333.
- Don't allow leading zeros in floats (except 0, 0.xxx).
- Allow positive exponent without sign in floats.
3.8.1 / 2017-02-07
------------------
- Maintenance: update browserified build.
3.8.0 / 2017-02-07
------------------
- Fix reported position for `duplicated mapping key` errors.
Now points to block start instead of block end.
(#243, thanks to @shockey).
3.7.0 / 2016-11-12
------------------
- Fix parsing of quotes followed by newlines (#304, thanks to @dplepage).
- Support polymorphism for tags (#300, thanks to @monken).
3.6.1 / 2016-05-11
------------------
- Fix output cut on a pipe, #286.
3.6.0 / 2016-04-16
------------------
- Dumper rewrite, fix multiple bugs with trailing `\n`.
Big thanks to @aepsilon!
- Loader: fix leading/trailing newlines in block scalars, @aepsilon.
3.5.5 / 2016-03-17
------------------
- Date parse fix: don't allow dates with on digit in month and day, #268.
3.5.4 / 2016-03-09
------------------
- `noCompatMode` for dumper, to disable quoting YAML 1.1 values.
3.5.3 / 2016-02-11
------------------
- Maintenance release.
3.5.2 / 2016-01-11
------------------
- Maintenance: missed comma in bower config.
3.5.1 / 2016-01-11
------------------
- Removed `inherit` dependency, #239.
- Better browserify workaround for esprima load.
- Demo rewrite.
3.5.0 / 2016-01-10
------------------
- Dumper. Fold strings only, #217.
- Dumper. `norefs` option, to clone linked objects, #229.
- Loader. Throw a warning for duplicate keys, #166.
- Improved browserify support (mark `esprima` & `Buffer` excluded).
3.4.6 / 2015-11-26
------------------
- Use standalone `inherit` to keep browserified files clear.
3.4.5 / 2015-11-23
------------------
- Added `lineWidth` option to dumper.
3.4.4 / 2015-11-21
------------------
- Fixed floats dump (missed dot for scientific format), #220.
- Allow non-printable characters inside quoted scalars, #192.
3.4.3 / 2015-10-10
------------------
- Maintenance release - deps bump (esprima, argparse).
3.4.2 / 2015-09-09
------------------
- Fixed serialization of duplicated entries in sequences, #205.
Thanks to @vogelsgesang.
3.4.1 / 2015-09-05
------------------
- Fixed stacktrace handling in generated errors, for browsers (FF/IE).
3.4.0 / 2015-08-23
------------------
- Fixed multiline keys dump, #197. Thanks to @tcr.
- Don't throw on warnongs anymore. Use `onWarning` option to catch.
- Throw error on unknown tags (was warning before).
- Fixed heading line breaks in some scalars (regression).
- Reworked internals of error class.
3.3.1 / 2015-05-13
------------------
- Added `.sortKeys` dumper option, thanks to @rjmunro.
- Fixed astral characters support, #191.
3.3.0 / 2015-04-26
------------------
- Significantly improved long strings formatting in dumper, thanks to @isaacs.
- Strip BOM if exists.
3.2.7 / 2015-02-19
------------------
- Maintenance release.
- Updated dependencies.
- HISTORY.md -> CHANGELOG.md
3.2.6 / 2015-02-07
------------------
- Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE).
- Fixed demo dates dump (#113, thanks to @Hypercubed).
3.2.5 / 2014-12-28
------------------
- Fixed resolving of all built-in types on empty nodes.
- Fixed invalid warning on empty lines within quoted scalars and flow collections.
- Fixed bug: Tag on an empty node didn't resolve in some cases.
3.2.4 / 2014-12-19
------------------
- Fixed resolving of !!null tag on an empty node.
3.2.3 / 2014-11-08
------------------
- Implemented dumping of objects with circular and cross references.
- Partially fixed aliasing of constructed objects. (see issue #141 for details)
3.2.2 / 2014-09-07
------------------
- Fixed infinite loop on unindented block scalars.
- Rewritten base64 encode/decode in binary type, to keep code licence clear.
3.2.1 / 2014-08-24
------------------
- Nothig new. Just fix npm publish error.
3.2.0 / 2014-08-24
------------------
- Added input piping support to CLI.
- Fixed typo, that could cause hand on initial indent (#139).
3.1.0 / 2014-07-07
------------------
- 1.5x-2x speed boost.
- Removed deprecated `require('xxx.yml')` support.
- Significant code cleanup and refactoring.
- Internal API changed. If you used custom types - see updated examples.
Others are not affected.
- Even if the input string has no trailing line break character,
it will be parsed as if it has one.
- Added benchmark scripts.
- Moved bower files to /dist folder
- Bugfixes.
3.0.2 / 2014-02-27
------------------
- Fixed bug: "constructor" string parsed as `null`.
3.0.1 / 2013-12-22
------------------
- Fixed parsing of literal scalars. (issue #108)
- Prevented adding unnecessary spaces in object dumps. (issue #68)
- Fixed dumping of objects with very long (> 1024 in length) keys.
3.0.0 / 2013-12-16
------------------
- Refactored code. Changed API for custom types.
- Removed output colors in CLI, dump json by default.
- Removed big dependencies from browser version (esprima, buffer)
- load `esprima` manually, if !!js/function needed
- !!bin now returns Array in browser
- AMD support.
- Don't quote dumped strings because of `-` & `?` (if not first char).
- __Deprecated__ loading yaml files via `require()`, as not recommended
behaviour for node.
2.1.3 / 2013-10-16
------------------
- Fix wrong loading of empty block scalars.
2.1.2 / 2013-10-07
------------------
- Fix unwanted line breaks in folded scalars.
2.1.1 / 2013-10-02
------------------
- Dumper now respects deprecated booleans syntax from YAML 1.0/1.1
- Fixed reader bug in JSON-like sequences/mappings.
2.1.0 / 2013-06-05
------------------
- Add standard YAML schemas: Failsafe (`FAILSAFE_SCHEMA`),
JSON (`JSON_SCHEMA`) and Core (`CORE_SCHEMA`).
- Rename `DEFAULT_SCHEMA` to `DEFAULT_FULL_SCHEMA`
and `SAFE_SCHEMA` to `DEFAULT_SAFE_SCHEMA`.
- Bug fix: export `NIL` constant from the public interface.
- Add `skipInvalid` dumper option.
- Use `safeLoad` for `require` extension.
2.0.5 / 2013-04-26
------------------
- Close security issue in !!js/function constructor.
Big thanks to @nealpoole for security audit.
2.0.4 / 2013-04-08
------------------
- Updated .npmignore to reduce package size
2.0.3 / 2013-02-26
------------------
- Fixed dumping of empty arrays ans objects. ([] and {} instead of null)
2.0.2 / 2013-02-15
------------------
- Fixed input validation: tabs are printable characters.
2.0.1 / 2013-02-09
------------------
- Fixed error, when options not passed to function cass
2.0.0 / 2013-02-09
------------------
- Full rewrite. New architecture. Fast one-stage parsing.
- Changed custom types API.
- Added YAML dumper.
1.0.3 / 2012-11-05
------------------
- Fixed utf-8 files loading.
1.0.2 / 2012-08-02
------------------
- Pull out hand-written shims. Use ES5-Shims for old browsers support. See #44.
- Fix timstamps incorectly parsed in local time when no time part specified.
1.0.1 / 2012-07-07
------------------
- Fixes `TypeError: 'undefined' is not an object` under Safari. Thanks Phuong.
- Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46.
1.0.0 / 2012-07-01
------------------
- `y`, `yes`, `n`, `no`, `on`, `off` are not converted to Booleans anymore.
Fixes #42.
- `require(filename)` now returns a single document and throws an Error if
file contains more than one document.
- CLI was merged back from js-yaml.bin
0.3.7 / 2012-02-28
------------------
- Fix export of `addConstructor()`. Closes #39.
0.3.6 / 2012-02-22
------------------
- Removed AMD parts - too buggy to use. Need help to rewrite from scratch
- Removed YUI compressor warning (renamed `double` variable). Closes #40.
0.3.5 / 2012-01-10
------------------
- Workagound for .npmignore fuckup under windows. Thanks to airportyh.
0.3.4 / 2011-12-24
------------------
- Fixes str[] for oldIEs support.
- Adds better has change support for browserified demo.
- improves compact output of Error. Closes #33.
0.3.3 / 2011-12-20
------------------
- jsyaml executable moved to separate module.
- adds `compact` stringification of Errors.
0.3.2 / 2011-12-16
------------------
- Fixes ug with block style scalars. Closes #26.
- All sources are passing JSLint now.
- Fixes bug in Safari. Closes #28.
- Fixes bug in Opers. Closes #29.
- Improves browser support. Closes #20.
- Added jsyaml executable.
- Added !!js/function support. Closes #12.
0.3.1 / 2011-11-18
------------------
- Added AMD support for browserified version.
- Wrapped browserified js-yaml into closure.
- Fixed the resolvement of non-specific tags. Closes #17.
- Added permalinks for online demo YAML snippets. Now we have YPaste service, lol.
- Added !!js/regexp and !!js/undefined types. Partially solves #12.
- Fixed !!set mapping.
- Fixed month parse in dates. Closes #19.
0.3.0 / 2011-11-09
------------------
- Removed JS.Class dependency. Closes #3.
- Added browserified version. Closes #13.
- Added live demo of browserified version.
- Ported some of the PyYAML tests. See #14.
- Fixed timestamp bug when fraction was given.
0.2.2 / 2011-11-06
------------------
- Fixed crash on docs without ---. Closes #8.
- Fixed miltiline string parse
- Fixed tests/comments for using array as key
0.2.1 / 2011-11-02
------------------
- Fixed short file read (<4k). Closes #9.
0.2.0 / 2011-11-02
------------------
- First public release

View File

@@ -0,0 +1,21 @@
(The MIT License)
Copyright (C) 2011-2015 by Vitaly Puzrin
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,313 @@
JS-YAML - YAML 1.2 parser / writer for JavaScript
=================================================
[![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml)
[![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml)
__[Online Demo](http://nodeca.github.com/js-yaml/)__
This is an implementation of [YAML](http://yaml.org/), a human-friendly data
serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was
completely rewritten from scratch. Now it's very fast, and supports 1.2 spec.
Installation
------------
### YAML module for node.js
```
npm install js-yaml
```
### CLI executable
If you want to inspect your YAML files from CLI, install js-yaml globally:
```
npm install -g js-yaml
```
#### Usage
```
usage: js-yaml [-h] [-v] [-c] [-t] file
Positional arguments:
file File with YAML document(s)
Optional arguments:
-h, --help Show this help message and exit.
-v, --version Show program's version number and exit.
-c, --compact Display errors in compact mode
-t, --trace Show stack trace on error
```
### Bundled YAML library for browsers
``` html
<!-- esprima required only for !!js/function -->
<script src="esprima.js"></script>
<script src="js-yaml.min.js"></script>
<script type="text/javascript">
var doc = jsyaml.load('greeting: hello\nname: world');
</script>
```
Browser support was done mostly for the online demo. If you find any errors - feel
free to send pull requests with fixes. Also note, that IE and other old browsers
needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate.
Notes:
1. We have no resources to support browserified version. Don't expect it to be
well tested. Don't expect fast fixes if something goes wrong there.
2. `!!js/function` in browser bundle will not work by default. If you really need
it - load `esprima` parser first (via amd or directly).
3. `!!bin` in browser will return `Array`, because browsers do not support
node.js `Buffer` and adding Buffer shims is completely useless on practice.
API
---
Here we cover the most 'useful' methods. If you need advanced details (creating
your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and
[examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more
info.
``` javascript
yaml = require('js-yaml');
fs = require('fs');
// Get document, or throw exception on error
try {
var doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
console.log(doc);
} catch (e) {
console.log(e);
}
```
### safeLoad (string [ , options ])
**Recommended loading way.** Parses `string` as single YAML document. Returns a JavaScript
object or throws `YAMLException` on error. By default, does not support regexps,
functions and undefined. This method is safe for untrusted data.
options:
- `filename` _(default: null)_ - string to be used as a file path in
error/warning messages.
- `onWarning` _(default: null)_ - function to call on warning messages.
Loader will throw on warnings if this function is not provided.
- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use.
- `FAILSAFE_SCHEMA` - only strings, arrays and plain objects:
http://www.yaml.org/spec/1.2/spec.html#id2802346
- `JSON_SCHEMA` - all JSON-supported types:
http://www.yaml.org/spec/1.2/spec.html#id2803231
- `CORE_SCHEMA` - same as `JSON_SCHEMA`:
http://www.yaml.org/spec/1.2/spec.html#id2804923
- `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones
(`!!js/undefined`, `!!js/regexp` and `!!js/function`):
http://yaml.org/type/
- `DEFAULT_FULL_SCHEMA` - all supported YAML types.
- `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error.
NOTE: This function **does not** understand multi-document sources, it throws
exception on those.
NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions.
So, the JSON schema is not as strictly defined in the YAML specification.
It allows numbers in any notation, use `Null` and `NULL` as `null`, etc.
The core schema also has no such restrictions. It allows binary notation for integers.
### load (string [ , options ])
**Use with care with untrusted sources**. The same as `safeLoad()` but uses
`DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types:
`!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you
must additionally validate object structure to avoid injections:
``` javascript
var untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"';
// I'm just converting that string, what could possibly go wrong?
require('js-yaml').load(untrusted_code) + ''
```
### safeLoadAll (string [, iterator] [, options ])
Same as `safeLoad()`, but understands multi-document sources. Applies
`iterator` to each document if specified, or returns array of documents.
``` javascript
var yaml = require('js-yaml');
yaml.safeLoadAll(data, function (doc) {
console.log(doc);
});
```
### loadAll (string [, iterator] [ , options ])
Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default.
### safeDump (object [ , options ])
Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will
throw an exception if you try to dump regexps or functions. However, you can
disable exceptions by setting the `skipInvalid` option to `true`.
options:
- `indent` _(default: 2)_ - indentation width to use (in spaces).
- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function
in the safe schema) and skip pairs and single values with such types.
- `flowLevel` (default: -1) - specifies level of nesting, when to switch from
block to flow style for collections. -1 means block style everwhere
- `styles` - "tag" => "style" map. Each tag may have own set of styles.
- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use.
- `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a
function, use the function to sort the keys.
- `lineWidth` _(default: `80`)_ - set max line width.
- `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references
- `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older
yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1
- `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded.
The following table show availlable styles (e.g. "canonical",
"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml
ouput is shown on the right side after `=>` (default setting) or `->`:
``` none
!!null
"canonical" -> "~"
"lowercase" => "null"
"uppercase" -> "NULL"
"camelcase" -> "Null"
!!int
"binary" -> "0b1", "0b101010", "0b1110001111010"
"octal" -> "01", "052", "016172"
"decimal" => "1", "42", "7290"
"hexadecimal" -> "0x1", "0x2A", "0x1C7A"
!!bool
"lowercase" => "true", "false"
"uppercase" -> "TRUE", "FALSE"
"camelcase" -> "True", "False"
!!float
"lowercase" => ".nan", '.inf'
"uppercase" -> ".NAN", '.INF'
"camelcase" -> ".NaN", '.Inf'
```
Example:
``` javascript
safeDump (object, {
'styles': {
'!!null': 'canonical' // dump null as ~
},
'sortKeys': true // sort object keys
});
```
### dump (object [ , options ])
Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default).
Supported YAML types
--------------------
The list of standard YAML tags and corresponding JavaScipt types. See also
[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and
[YAML types repository](http://yaml.org/type/).
```
!!null '' # null
!!bool 'yes' # bool
!!int '3...' # number
!!float '3.14...' # number
!!binary '...base64...' # buffer
!!timestamp 'YYYY-...' # date
!!omap [ ... ] # array of key-value pairs
!!pairs [ ... ] # array or array pairs
!!set { ... } # array of objects with given keys and null values
!!str '...' # string
!!seq [ ... ] # array
!!map { ... } # object
```
**JavaScript-specific tags**
```
!!js/regexp /pattern/gim # RegExp
!!js/undefined '' # Undefined
!!js/function 'function () {...}' # Function
```
Caveats
-------
Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects
or arrays as keys, and stringifies (by calling `toString()` method) them at the
moment of adding them.
``` yaml
---
? [ foo, bar ]
: - baz
? { foo: bar }
: - baz
- baz
```
``` javascript
{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] }
```
Also, reading of properties on implicit block mapping keys is not supported yet.
So, the following YAML document cannot be loaded.
``` yaml
&anchor foo:
foo: bar
*anchor: duplicate key
baz: bat
*anchor: duplicate key
```
Breaking changes in 2.x.x -> 3.x.x
----------------------------------
If you have not used __custom__ tags or loader classes and not loaded yaml
files via `require()`, no changes are needed. Just upgrade the library.
Otherwise, you should:
1. Replace all occurrences of `require('xxxx.yml')` by `fs.readFileSync()` +
`yaml.safeLoad()`.
2. rewrite your custom tags constructors and custom loader
classes, to conform the new API. See
[examples](https://github.com/nodeca/js-yaml/tree/master/examples) and
[wiki](https://github.com/nodeca/js-yaml/wiki) for details.
License
-------
View the [LICENSE](https://github.com/nodeca/js-yaml/blob/master/LICENSE) file
(MIT).

View File

@@ -0,0 +1,132 @@
#!/usr/bin/env node
'use strict';
/*eslint-disable no-console*/
// stdlib
var fs = require('fs');
// 3rd-party
var argparse = require('argparse');
// internal
var yaml = require('..');
////////////////////////////////////////////////////////////////////////////////
var cli = new argparse.ArgumentParser({
prog: 'js-yaml',
version: require('../package.json').version,
addHelp: true
});
cli.addArgument([ '-c', '--compact' ], {
help: 'Display errors in compact mode',
action: 'storeTrue'
});
// deprecated (not needed after we removed output colors)
// option suppressed, but not completely removed for compatibility
cli.addArgument([ '-j', '--to-json' ], {
help: argparse.Const.SUPPRESS,
dest: 'json',
action: 'storeTrue'
});
cli.addArgument([ '-t', '--trace' ], {
help: 'Show stack trace on error',
action: 'storeTrue'
});
cli.addArgument([ 'file' ], {
help: 'File to read, utf-8 encoded without BOM',
nargs: '?',
defaultValue: '-'
});
////////////////////////////////////////////////////////////////////////////////
var options = cli.parseArgs();
////////////////////////////////////////////////////////////////////////////////
function readFile(filename, encoding, callback) {
if (options.file === '-') {
// read from stdin
var chunks = [];
process.stdin.on('data', function (chunk) {
chunks.push(chunk);
});
process.stdin.on('end', function () {
return callback(null, Buffer.concat(chunks).toString(encoding));
});
} else {
fs.readFile(filename, encoding, callback);
}
}
readFile(options.file, 'utf8', function (error, input) {
var output, isYaml;
if (error) {
if (error.code === 'ENOENT') {
console.error('File not found: ' + options.file);
process.exit(2);
}
console.error(
options.trace && error.stack ||
error.message ||
String(error));
process.exit(1);
}
try {
output = JSON.parse(input);
isYaml = false;
} catch (err) {
if (err instanceof SyntaxError) {
try {
output = [];
yaml.loadAll(input, function (doc) { output.push(doc); }, {});
isYaml = true;
if (output.length === 0) output = null;
else if (output.length === 1) output = output[0];
} catch (e) {
if (options.trace && err.stack) console.error(e.stack);
else console.error(e.toString(options.compact));
process.exit(1);
}
} else {
console.error(
options.trace && err.stack ||
err.message ||
String(err));
process.exit(1);
}
}
if (isYaml) console.log(JSON.stringify(output, null, ' '));
else console.log(yaml.dump(output));
});

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
'use strict';
var yaml = require('./lib/js-yaml.js');
module.exports = yaml;

View File

@@ -0,0 +1,39 @@
'use strict';
var loader = require('./js-yaml/loader');
var dumper = require('./js-yaml/dumper');
function deprecated(name) {
return function () {
throw new Error('Function ' + name + ' is deprecated and cannot be used.');
};
}
module.exports.Type = require('./js-yaml/type');
module.exports.Schema = require('./js-yaml/schema');
module.exports.FAILSAFE_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.JSON_SCHEMA = require('./js-yaml/schema/json');
module.exports.CORE_SCHEMA = require('./js-yaml/schema/core');
module.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full');
module.exports.load = loader.load;
module.exports.loadAll = loader.loadAll;
module.exports.safeLoad = loader.safeLoad;
module.exports.safeLoadAll = loader.safeLoadAll;
module.exports.dump = dumper.dump;
module.exports.safeDump = dumper.safeDump;
module.exports.YAMLException = require('./js-yaml/exception');
// Deprecated schema names from JS-YAML 2.0.x
module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');
// Deprecated functions from JS-YAML 1.x.x
module.exports.scan = deprecated('scan');
module.exports.parse = deprecated('parse');
module.exports.compose = deprecated('compose');
module.exports.addConstructor = deprecated('addConstructor');

View File

@@ -0,0 +1,59 @@
'use strict';
function isNothing(subject) {
return (typeof subject === 'undefined') || (subject === null);
}
function isObject(subject) {
return (typeof subject === 'object') && (subject !== null);
}
function toArray(sequence) {
if (Array.isArray(sequence)) return sequence;
else if (isNothing(sequence)) return [];
return [ sequence ];
}
function extend(target, source) {
var index, length, key, sourceKeys;
if (source) {
sourceKeys = Object.keys(source);
for (index = 0, length = sourceKeys.length; index < length; index += 1) {
key = sourceKeys[index];
target[key] = source[key];
}
}
return target;
}
function repeat(string, count) {
var result = '', cycle;
for (cycle = 0; cycle < count; cycle += 1) {
result += string;
}
return result;
}
function isNegativeZero(number) {
return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
}
module.exports.isNothing = isNothing;
module.exports.isObject = isObject;
module.exports.toArray = toArray;
module.exports.repeat = repeat;
module.exports.isNegativeZero = isNegativeZero;
module.exports.extend = extend;

View File

@@ -0,0 +1,819 @@
'use strict';
/*eslint-disable no-use-before-define*/
var common = require('./common');
var YAMLException = require('./exception');
var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
var _toString = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var CHAR_TAB = 0x09; /* Tab */
var CHAR_LINE_FEED = 0x0A; /* LF */
var CHAR_SPACE = 0x20; /* Space */
var CHAR_EXCLAMATION = 0x21; /* ! */
var CHAR_DOUBLE_QUOTE = 0x22; /* " */
var CHAR_SHARP = 0x23; /* # */
var CHAR_PERCENT = 0x25; /* % */
var CHAR_AMPERSAND = 0x26; /* & */
var CHAR_SINGLE_QUOTE = 0x27; /* ' */
var CHAR_ASTERISK = 0x2A; /* * */
var CHAR_COMMA = 0x2C; /* , */
var CHAR_MINUS = 0x2D; /* - */
var CHAR_COLON = 0x3A; /* : */
var CHAR_GREATER_THAN = 0x3E; /* > */
var CHAR_QUESTION = 0x3F; /* ? */
var CHAR_COMMERCIAL_AT = 0x40; /* @ */
var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
var CHAR_GRAVE_ACCENT = 0x60; /* ` */
var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
var CHAR_VERTICAL_LINE = 0x7C; /* | */
var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
var ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0x00] = '\\0';
ESCAPE_SEQUENCES[0x07] = '\\a';
ESCAPE_SEQUENCES[0x08] = '\\b';
ESCAPE_SEQUENCES[0x09] = '\\t';
ESCAPE_SEQUENCES[0x0A] = '\\n';
ESCAPE_SEQUENCES[0x0B] = '\\v';
ESCAPE_SEQUENCES[0x0C] = '\\f';
ESCAPE_SEQUENCES[0x0D] = '\\r';
ESCAPE_SEQUENCES[0x1B] = '\\e';
ESCAPE_SEQUENCES[0x22] = '\\"';
ESCAPE_SEQUENCES[0x5C] = '\\\\';
ESCAPE_SEQUENCES[0x85] = '\\N';
ESCAPE_SEQUENCES[0xA0] = '\\_';
ESCAPE_SEQUENCES[0x2028] = '\\L';
ESCAPE_SEQUENCES[0x2029] = '\\P';
var DEPRECATED_BOOLEANS_SYNTAX = [
'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
];
function compileStyleMap(schema, map) {
var result, keys, index, length, tag, style, type;
if (map === null) return {};
result = {};
keys = Object.keys(map);
for (index = 0, length = keys.length; index < length; index += 1) {
tag = keys[index];
style = String(map[tag]);
if (tag.slice(0, 2) === '!!') {
tag = 'tag:yaml.org,2002:' + tag.slice(2);
}
type = schema.compiledTypeMap['fallback'][tag];
if (type && _hasOwnProperty.call(type.styleAliases, style)) {
style = type.styleAliases[style];
}
result[tag] = style;
}
return result;
}
function encodeHex(character) {
var string, handle, length;
string = character.toString(16).toUpperCase();
if (character <= 0xFF) {
handle = 'x';
length = 2;
} else if (character <= 0xFFFF) {
handle = 'u';
length = 4;
} else if (character <= 0xFFFFFFFF) {
handle = 'U';
length = 8;
} else {
throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
}
return '\\' + handle + common.repeat('0', length - string.length) + string;
}
function State(options) {
this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
this.indent = Math.max(1, (options['indent'] || 2));
this.skipInvalid = options['skipInvalid'] || false;
this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
this.sortKeys = options['sortKeys'] || false;
this.lineWidth = options['lineWidth'] || 80;
this.noRefs = options['noRefs'] || false;
this.noCompatMode = options['noCompatMode'] || false;
this.condenseFlow = options['condenseFlow'] || false;
this.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit;
this.tag = null;
this.result = '';
this.duplicates = [];
this.usedDuplicates = null;
}
// Indents every line in a string. Empty lines (\n only) are not indented.
function indentString(string, spaces) {
var ind = common.repeat(' ', spaces),
position = 0,
next = -1,
result = '',
line,
length = string.length;
while (position < length) {
next = string.indexOf('\n', position);
if (next === -1) {
line = string.slice(position);
position = length;
} else {
line = string.slice(position, next + 1);
position = next + 1;
}
if (line.length && line !== '\n') result += ind;
result += line;
}
return result;
}
function generateNextLine(state, level) {
return '\n' + common.repeat(' ', state.indent * level);
}
function testImplicitResolving(state, str) {
var index, length, type;
for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
type = state.implicitTypes[index];
if (type.resolve(str)) {
return true;
}
}
return false;
}
// [33] s-white ::= s-space | s-tab
function isWhitespace(c) {
return c === CHAR_SPACE || c === CHAR_TAB;
}
// Returns true if the character can be printed without escaping.
// From YAML 1.2: "any allowed characters known to be non-printable
// should also be escaped. [However,] This isnt mandatory"
// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
function isPrintable(c) {
return (0x00020 <= c && c <= 0x00007E)
|| ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
|| ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
|| (0x10000 <= c && c <= 0x10FFFF);
}
// Simplified test for values allowed after the first character in plain style.
function isPlainSafe(c) {
// Uses a subset of nb-char - c-flow-indicator - ":" - "#"
// where nb-char ::= c-printable - b-char - c-byte-order-mark.
return isPrintable(c) && c !== 0xFEFF
// - c-flow-indicator
&& c !== CHAR_COMMA
&& c !== CHAR_LEFT_SQUARE_BRACKET
&& c !== CHAR_RIGHT_SQUARE_BRACKET
&& c !== CHAR_LEFT_CURLY_BRACKET
&& c !== CHAR_RIGHT_CURLY_BRACKET
// - ":" - "#"
&& c !== CHAR_COLON
&& c !== CHAR_SHARP;
}
// Simplified test for values allowed as the first character in plain style.
function isPlainSafeFirst(c) {
// Uses a subset of ns-char - c-indicator
// where ns-char = nb-char - s-white.
return isPrintable(c) && c !== 0xFEFF
&& !isWhitespace(c) // - s-white
// - (c-indicator ::=
// “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
&& c !== CHAR_MINUS
&& c !== CHAR_QUESTION
&& c !== CHAR_COLON
&& c !== CHAR_COMMA
&& c !== CHAR_LEFT_SQUARE_BRACKET
&& c !== CHAR_RIGHT_SQUARE_BRACKET
&& c !== CHAR_LEFT_CURLY_BRACKET
&& c !== CHAR_RIGHT_CURLY_BRACKET
// | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
&& c !== CHAR_SHARP
&& c !== CHAR_AMPERSAND
&& c !== CHAR_ASTERISK
&& c !== CHAR_EXCLAMATION
&& c !== CHAR_VERTICAL_LINE
&& c !== CHAR_GREATER_THAN
&& c !== CHAR_SINGLE_QUOTE
&& c !== CHAR_DOUBLE_QUOTE
// | “%” | “@” | “`”)
&& c !== CHAR_PERCENT
&& c !== CHAR_COMMERCIAL_AT
&& c !== CHAR_GRAVE_ACCENT;
}
var STYLE_PLAIN = 1,
STYLE_SINGLE = 2,
STYLE_LITERAL = 3,
STYLE_FOLDED = 4,
STYLE_DOUBLE = 5;
// Determines which scalar styles are possible and returns the preferred style.
// lineWidth = -1 => no limit.
// Pre-conditions: str.length > 0.
// Post-conditions:
// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
var i;
var char;
var hasLineBreak = false;
var hasFoldableLine = false; // only checked if shouldTrackWidth
var shouldTrackWidth = lineWidth !== -1;
var previousLineBreak = -1; // count the first line correctly
var plain = isPlainSafeFirst(string.charCodeAt(0))
&& !isWhitespace(string.charCodeAt(string.length - 1));
if (singleLineOnly) {
// Case: no block styles.
// Check for disallowed characters to rule out plain and single.
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char);
}
} else {
// Case: block styles permitted.
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char === CHAR_LINE_FEED) {
hasLineBreak = true;
// Check if any line can be folded.
if (shouldTrackWidth) {
hasFoldableLine = hasFoldableLine ||
// Foldable line = too long, and not more-indented.
(i - previousLineBreak - 1 > lineWidth &&
string[previousLineBreak + 1] !== ' ');
previousLineBreak = i;
}
} else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char);
}
// in case the end is missing a \n
hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
(i - previousLineBreak - 1 > lineWidth &&
string[previousLineBreak + 1] !== ' '));
}
// Although every style can represent \n without escaping, prefer block styles
// for multiline, since they're more readable and they don't add empty lines.
// Also prefer folding a super-long line.
if (!hasLineBreak && !hasFoldableLine) {
// Strings interpretable as another type have to be quoted;
// e.g. the string 'true' vs. the boolean true.
return plain && !testAmbiguousType(string)
? STYLE_PLAIN : STYLE_SINGLE;
}
// Edge case: block indentation indicator can only have one digit.
if (string[0] === ' ' && indentPerLevel > 9) {
return STYLE_DOUBLE;
}
// At this point we know block styles are valid.
// Prefer literal style unless we want to fold.
return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
}
// Note: line breaking/folding is implemented for only the folded style.
// NB. We drop the last trailing newline (if any) of a returned block scalar
// since the dumper adds its own newline. This always works:
// • No ending newline => unaffected; already using strip "-" chomping.
// • Ending newline => removed then restored.
// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
function writeScalar(state, string, level, iskey) {
state.dump = (function () {
if (string.length === 0) {
return "''";
}
if (!state.noCompatMode &&
DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
return "'" + string + "'";
}
var indent = state.indent * Math.max(1, level); // no 0-indent scalars
// As indentation gets deeper, let the width decrease monotonically
// to the lower bound min(state.lineWidth, 40).
// Note that this implies
// state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
// state.lineWidth > 40 + state.indent: width decreases until the lower bound.
// This behaves better than a constant minimum width which disallows narrower options,
// or an indent threshold which causes the width to suddenly increase.
var lineWidth = state.lineWidth === -1
? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
// Without knowing if keys are implicit/explicit, assume implicit for safety.
var singleLineOnly = iskey
// No block styles in flow mode.
|| (state.flowLevel > -1 && level >= state.flowLevel);
function testAmbiguity(string) {
return testImplicitResolving(state, string);
}
switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
case STYLE_PLAIN:
return string;
case STYLE_SINGLE:
return "'" + string.replace(/'/g, "''") + "'";
case STYLE_LITERAL:
return '|' + blockHeader(string, state.indent)
+ dropEndingNewline(indentString(string, indent));
case STYLE_FOLDED:
return '>' + blockHeader(string, state.indent)
+ dropEndingNewline(indentString(foldString(string, lineWidth), indent));
case STYLE_DOUBLE:
return '"' + escapeString(string, lineWidth) + '"';
default:
throw new YAMLException('impossible error: invalid scalar style');
}
}());
}
// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
function blockHeader(string, indentPerLevel) {
var indentIndicator = (string[0] === ' ') ? String(indentPerLevel) : '';
// note the special case: the string '\n' counts as a "trailing" empty line.
var clip = string[string.length - 1] === '\n';
var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
var chomp = keep ? '+' : (clip ? '' : '-');
return indentIndicator + chomp + '\n';
}
// (See the note for writeScalar.)
function dropEndingNewline(string) {
return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
}
// Note: a long line without a suitable break point will exceed the width limit.
// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
function foldString(string, width) {
// In folded style, $k$ consecutive newlines output as $k+1$ newlines—
// unless they're before or after a more-indented line, or at the very
// beginning or end, in which case $k$ maps to $k$.
// Therefore, parse each chunk as newline(s) followed by a content line.
var lineRe = /(\n+)([^\n]*)/g;
// first line (possibly an empty line)
var result = (function () {
var nextLF = string.indexOf('\n');
nextLF = nextLF !== -1 ? nextLF : string.length;
lineRe.lastIndex = nextLF;
return foldLine(string.slice(0, nextLF), width);
}());
// If we haven't reached the first content line yet, don't add an extra \n.
var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
var moreIndented;
// rest of the lines
var match;
while ((match = lineRe.exec(string))) {
var prefix = match[1], line = match[2];
moreIndented = (line[0] === ' ');
result += prefix
+ (!prevMoreIndented && !moreIndented && line !== ''
? '\n' : '')
+ foldLine(line, width);
prevMoreIndented = moreIndented;
}
return result;
}
// Greedy line breaking.
// Picks the longest line under the limit each time,
// otherwise settles for the shortest line over the limit.
// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
function foldLine(line, width) {
if (line === '' || line[0] === ' ') return line;
// Since a more-indented line adds a \n, breaks can't be followed by a space.
var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
var match;
// start is an inclusive index. end, curr, and next are exclusive.
var start = 0, end, curr = 0, next = 0;
var result = '';
// Invariants: 0 <= start <= length-1.
// 0 <= curr <= next <= max(0, length-2). curr - start <= width.
// Inside the loop:
// A match implies length >= 2, so curr and next are <= length-2.
while ((match = breakRe.exec(line))) {
next = match.index;
// maintain invariant: curr - start <= width
if (next - start > width) {
end = (curr > start) ? curr : next; // derive end <= length-2
result += '\n' + line.slice(start, end);
// skip the space that was output as \n
start = end + 1; // derive start <= length-1
}
curr = next;
}
// By the invariants, start <= length-1, so there is something left over.
// It is either the whole string or a part starting from non-whitespace.
result += '\n';
// Insert a break if the remainder is too long and there is a break available.
if (line.length - start > width && curr > start) {
result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
} else {
result += line.slice(start);
}
return result.slice(1); // drop extra \n joiner
}
// Escapes a double-quoted string.
function escapeString(string) {
var result = '';
var char, nextChar;
var escapeSeq;
for (var i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
// Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
nextChar = string.charCodeAt(i + 1);
if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
// Combine the surrogate pair and store it escaped.
result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
// Advance index one extra since we already used that char here.
i++; continue;
}
}
escapeSeq = ESCAPE_SEQUENCES[char];
result += !escapeSeq && isPrintable(char)
? string[i]
: escapeSeq || encodeHex(char);
}
return result;
}
function writeFlowSequence(state, level, object) {
var _result = '',
_tag = state.tag,
index,
length;
for (index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements.
if (writeNode(state, level, object[index], false, false)) {
if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
_result += state.dump;
}
}
state.tag = _tag;
state.dump = '[' + _result + ']';
}
function writeBlockSequence(state, level, object, compact) {
var _result = '',
_tag = state.tag,
index,
length;
for (index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements.
if (writeNode(state, level + 1, object[index], true, true)) {
if (!compact || index !== 0) {
_result += generateNextLine(state, level);
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
_result += '-';
} else {
_result += '- ';
}
_result += state.dump;
}
}
state.tag = _tag;
state.dump = _result || '[]'; // Empty sequence if no valid values.
}
function writeFlowMapping(state, level, object) {
var _result = '',
_tag = state.tag,
objectKeyList = Object.keys(object),
index,
length,
objectKey,
objectValue,
pairBuffer;
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = state.condenseFlow ? '"' : '';
if (index !== 0) pairBuffer += ', ';
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (!writeNode(state, level, objectKey, false, false)) {
continue; // Skip this pair because of invalid key;
}
if (state.dump.length > 1024) pairBuffer += '? ';
pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
if (!writeNode(state, level, objectValue, false, false)) {
continue; // Skip this pair because of invalid value.
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = '{' + _result + '}';
}
function writeBlockMapping(state, level, object, compact) {
var _result = '',
_tag = state.tag,
objectKeyList = Object.keys(object),
index,
length,
objectKey,
objectValue,
explicitPair,
pairBuffer;
// Allow sorting keys so that the output file is deterministic
if (state.sortKeys === true) {
// Default sorting
objectKeyList.sort();
} else if (typeof state.sortKeys === 'function') {
// Custom sort function
objectKeyList.sort(state.sortKeys);
} else if (state.sortKeys) {
// Something is wrong
throw new YAMLException('sortKeys must be a boolean or a function');
}
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = '';
if (!compact || index !== 0) {
pairBuffer += generateNextLine(state, level);
}
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (!writeNode(state, level + 1, objectKey, true, true, true)) {
continue; // Skip this pair because of invalid key.
}
explicitPair = (state.tag !== null && state.tag !== '?') ||
(state.dump && state.dump.length > 1024);
if (explicitPair) {
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += '?';
} else {
pairBuffer += '? ';
}
}
pairBuffer += state.dump;
if (explicitPair) {
pairBuffer += generateNextLine(state, level);
}
if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
continue; // Skip this pair because of invalid value.
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += ':';
} else {
pairBuffer += ': ';
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = _result || '{}'; // Empty mapping if no valid pairs.
}
function detectType(state, object, explicit) {
var _result, typeList, index, length, type, style;
typeList = explicit ? state.explicitTypes : state.implicitTypes;
for (index = 0, length = typeList.length; index < length; index += 1) {
type = typeList[index];
if ((type.instanceOf || type.predicate) &&
(!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
(!type.predicate || type.predicate(object))) {
state.tag = explicit ? type.tag : '?';
if (type.represent) {
style = state.styleMap[type.tag] || type.defaultStyle;
if (_toString.call(type.represent) === '[object Function]') {
_result = type.represent(object, style);
} else if (_hasOwnProperty.call(type.represent, style)) {
_result = type.represent[style](object, style);
} else {
throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
}
state.dump = _result;
}
return true;
}
}
return false;
}
// Serializes `object` and writes it to global `result`.
// Returns true on success, or false on invalid object.
//
function writeNode(state, level, object, block, compact, iskey) {
state.tag = null;
state.dump = object;
if (!detectType(state, object, false)) {
detectType(state, object, true);
}
var type = _toString.call(state.dump);
if (block) {
block = (state.flowLevel < 0 || state.flowLevel > level);
}
var objectOrArray = type === '[object Object]' || type === '[object Array]',
duplicateIndex,
duplicate;
if (objectOrArray) {
duplicateIndex = state.duplicates.indexOf(object);
duplicate = duplicateIndex !== -1;
}
if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
compact = false;
}
if (duplicate && state.usedDuplicates[duplicateIndex]) {
state.dump = '*ref_' + duplicateIndex;
} else {
if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
state.usedDuplicates[duplicateIndex] = true;
}
if (type === '[object Object]') {
if (block && (Object.keys(state.dump).length !== 0)) {
writeBlockMapping(state, level, state.dump, compact);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + state.dump;
}
} else {
writeFlowMapping(state, level, state.dump);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
}
}
} else if (type === '[object Array]') {
if (block && (state.dump.length !== 0)) {
writeBlockSequence(state, level, state.dump, compact);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + state.dump;
}
} else {
writeFlowSequence(state, level, state.dump);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
}
}
} else if (type === '[object String]') {
if (state.tag !== '?') {
writeScalar(state, state.dump, level, iskey);
}
} else {
if (state.skipInvalid) return false;
throw new YAMLException('unacceptable kind of an object to dump ' + type);
}
if (state.tag !== null && state.tag !== '?') {
state.dump = '!<' + state.tag + '> ' + state.dump;
}
}
return true;
}
function getDuplicateReferences(object, state) {
var objects = [],
duplicatesIndexes = [],
index,
length;
inspectNode(object, objects, duplicatesIndexes);
for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
state.duplicates.push(objects[duplicatesIndexes[index]]);
}
state.usedDuplicates = new Array(length);
}
function inspectNode(object, objects, duplicatesIndexes) {
var objectKeyList,
index,
length;
if (object !== null && typeof object === 'object') {
index = objects.indexOf(object);
if (index !== -1) {
if (duplicatesIndexes.indexOf(index) === -1) {
duplicatesIndexes.push(index);
}
} else {
objects.push(object);
if (Array.isArray(object)) {
for (index = 0, length = object.length; index < length; index += 1) {
inspectNode(object[index], objects, duplicatesIndexes);
}
} else {
objectKeyList = Object.keys(object);
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
}
}
}
}
}
function dump(input, options) {
options = options || {};
var state = new State(options);
if (!state.noRefs) getDuplicateReferences(input, state);
if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
return '';
}
function safeDump(input, options) {
return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
module.exports.dump = dump;
module.exports.safeDump = safeDump;

View File

@@ -0,0 +1,43 @@
// YAML error class. http://stackoverflow.com/questions/8458984
//
'use strict';
function YAMLException(reason, mark) {
// Super constructor
Error.call(this);
this.name = 'YAMLException';
this.reason = reason;
this.mark = mark;
this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
// Include stack trace in error object
if (Error.captureStackTrace) {
// Chrome and NodeJS
Error.captureStackTrace(this, this.constructor);
} else {
// FF, IE 10+ and Safari 6+. Fallback for others
this.stack = (new Error()).stack || '';
}
}
// Inherit from Error
YAMLException.prototype = Object.create(Error.prototype);
YAMLException.prototype.constructor = YAMLException;
YAMLException.prototype.toString = function toString(compact) {
var result = this.name + ': ';
result += this.reason || '(unknown reason)';
if (!compact && this.mark) {
result += ' ' + this.mark.toString();
}
return result;
};
module.exports = YAMLException;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,76 @@
'use strict';
var common = require('./common');
function Mark(name, buffer, position, line, column) {
this.name = name;
this.buffer = buffer;
this.position = position;
this.line = line;
this.column = column;
}
Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
var head, start, tail, end, snippet;
if (!this.buffer) return null;
indent = indent || 4;
maxLength = maxLength || 75;
head = '';
start = this.position;
while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
start -= 1;
if (this.position - start > (maxLength / 2 - 1)) {
head = ' ... ';
start += 5;
break;
}
}
tail = '';
end = this.position;
while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
end += 1;
if (end - this.position > (maxLength / 2 - 1)) {
tail = ' ... ';
end -= 5;
break;
}
}
snippet = this.buffer.slice(start, end);
return common.repeat(' ', indent) + head + snippet + tail + '\n' +
common.repeat(' ', indent + this.position - start + head.length) + '^';
};
Mark.prototype.toString = function toString(compact) {
var snippet, where = '';
if (this.name) {
where += 'in "' + this.name + '" ';
}
where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
if (!compact) {
snippet = this.getSnippet();
if (snippet) {
where += ':\n' + snippet;
}
}
return where;
};
module.exports = Mark;

View File

@@ -0,0 +1,108 @@
'use strict';
/*eslint-disable max-len*/
var common = require('./common');
var YAMLException = require('./exception');
var Type = require('./type');
function compileList(schema, name, result) {
var exclude = [];
schema.include.forEach(function (includedSchema) {
result = compileList(includedSchema, name, result);
});
schema[name].forEach(function (currentType) {
result.forEach(function (previousType, previousIndex) {
if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
exclude.push(previousIndex);
}
});
result.push(currentType);
});
return result.filter(function (type, index) {
return exclude.indexOf(index) === -1;
});
}
function compileMap(/* lists... */) {
var result = {
scalar: {},
sequence: {},
mapping: {},
fallback: {}
}, index, length;
function collectType(type) {
result[type.kind][type.tag] = result['fallback'][type.tag] = type;
}
for (index = 0, length = arguments.length; index < length; index += 1) {
arguments[index].forEach(collectType);
}
return result;
}
function Schema(definition) {
this.include = definition.include || [];
this.implicit = definition.implicit || [];
this.explicit = definition.explicit || [];
this.implicit.forEach(function (type) {
if (type.loadKind && type.loadKind !== 'scalar') {
throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
}
});
this.compiledImplicit = compileList(this, 'implicit', []);
this.compiledExplicit = compileList(this, 'explicit', []);
this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
}
Schema.DEFAULT = null;
Schema.create = function createSchema() {
var schemas, types;
switch (arguments.length) {
case 1:
schemas = Schema.DEFAULT;
types = arguments[0];
break;
case 2:
schemas = arguments[0];
types = arguments[1];
break;
default:
throw new YAMLException('Wrong number of arguments for Schema.create function');
}
schemas = common.toArray(schemas);
types = common.toArray(types);
if (!schemas.every(function (schema) { return schema instanceof Schema; })) {
throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
}
if (!types.every(function (type) { return type instanceof Type; })) {
throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
}
return new Schema({
include: schemas,
explicit: types
});
};
module.exports = Schema;

View File

@@ -0,0 +1,18 @@
// Standard YAML's Core schema.
// http://www.yaml.org/spec/1.2/spec.html#id2804923
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, Core schema has no distinctions from JSON schema is JS-YAML.
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
include: [
require('./json')
]
});

View File

@@ -0,0 +1,25 @@
// JS-YAML's default schema for `load` function.
// It is not described in the YAML specification.
//
// This schema is based on JS-YAML's default safe schema and includes
// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.
//
// Also this schema is used as default base schema at `Schema.create` function.
'use strict';
var Schema = require('../schema');
module.exports = Schema.DEFAULT = new Schema({
include: [
require('./default_safe')
],
explicit: [
require('../type/js/undefined'),
require('../type/js/regexp'),
require('../type/js/function')
]
});

View File

@@ -0,0 +1,28 @@
// JS-YAML's default schema for `safeLoad` function.
// It is not described in the YAML specification.
//
// This schema is based on standard YAML's Core schema and includes most of
// extra types described at YAML tag repository. (http://yaml.org/type/)
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
include: [
require('./core')
],
implicit: [
require('../type/timestamp'),
require('../type/merge')
],
explicit: [
require('../type/binary'),
require('../type/omap'),
require('../type/pairs'),
require('../type/set')
]
});

View File

@@ -0,0 +1,17 @@
// Standard YAML's Failsafe schema.
// http://www.yaml.org/spec/1.2/spec.html#id2802346
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
explicit: [
require('../type/str'),
require('../type/seq'),
require('../type/map')
]
});

View File

@@ -0,0 +1,25 @@
// Standard YAML's JSON schema.
// http://www.yaml.org/spec/1.2/spec.html#id2803231
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, this schema is not such strict as defined in the YAML specification.
// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
include: [
require('./failsafe')
],
implicit: [
require('../type/null'),
require('../type/bool'),
require('../type/int'),
require('../type/float')
]
});

View File

@@ -0,0 +1,61 @@
'use strict';
var YAMLException = require('./exception');
var TYPE_CONSTRUCTOR_OPTIONS = [
'kind',
'resolve',
'construct',
'instanceOf',
'predicate',
'represent',
'defaultStyle',
'styleAliases'
];
var YAML_NODE_KINDS = [
'scalar',
'sequence',
'mapping'
];
function compileStyleAliases(map) {
var result = {};
if (map !== null) {
Object.keys(map).forEach(function (style) {
map[style].forEach(function (alias) {
result[String(alias)] = style;
});
});
}
return result;
}
function Type(tag, options) {
options = options || {};
Object.keys(options).forEach(function (name) {
if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
}
});
// TODO: Add tag format check.
this.tag = tag;
this.kind = options['kind'] || null;
this.resolve = options['resolve'] || function () { return true; };
this.construct = options['construct'] || function (data) { return data; };
this.instanceOf = options['instanceOf'] || null;
this.predicate = options['predicate'] || null;
this.represent = options['represent'] || null;
this.defaultStyle = options['defaultStyle'] || null;
this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
}
}
module.exports = Type;

View File

@@ -0,0 +1,138 @@
'use strict';
/*eslint-disable no-bitwise*/
var NodeBuffer;
try {
// A trick for browserified version, to not include `Buffer` shim
var _require = require;
NodeBuffer = _require('buffer').Buffer;
} catch (__) {}
var Type = require('../type');
// [ 64, 65, 66 ] -> [ padding, CR, LF ]
var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
function resolveYamlBinary(data) {
if (data === null) return false;
var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
// Convert one by one.
for (idx = 0; idx < max; idx++) {
code = map.indexOf(data.charAt(idx));
// Skip CR/LF
if (code > 64) continue;
// Fail on illegal characters
if (code < 0) return false;
bitlen += 6;
}
// If there are any bits left, source was corrupted
return (bitlen % 8) === 0;
}
function constructYamlBinary(data) {
var idx, tailbits,
input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
max = input.length,
map = BASE64_MAP,
bits = 0,
result = [];
// Collect by 6*4 bits (3 bytes)
for (idx = 0; idx < max; idx++) {
if ((idx % 4 === 0) && idx) {
result.push((bits >> 16) & 0xFF);
result.push((bits >> 8) & 0xFF);
result.push(bits & 0xFF);
}
bits = (bits << 6) | map.indexOf(input.charAt(idx));
}
// Dump tail
tailbits = (max % 4) * 6;
if (tailbits === 0) {
result.push((bits >> 16) & 0xFF);
result.push((bits >> 8) & 0xFF);
result.push(bits & 0xFF);
} else if (tailbits === 18) {
result.push((bits >> 10) & 0xFF);
result.push((bits >> 2) & 0xFF);
} else if (tailbits === 12) {
result.push((bits >> 4) & 0xFF);
}
// Wrap into Buffer for NodeJS and leave Array for browser
if (NodeBuffer) {
// Support node 6.+ Buffer API when available
return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
}
return result;
}
function representYamlBinary(object /*, style*/) {
var result = '', bits = 0, idx, tail,
max = object.length,
map = BASE64_MAP;
// Convert every three bytes to 4 ASCII characters.
for (idx = 0; idx < max; idx++) {
if ((idx % 3 === 0) && idx) {
result += map[(bits >> 18) & 0x3F];
result += map[(bits >> 12) & 0x3F];
result += map[(bits >> 6) & 0x3F];
result += map[bits & 0x3F];
}
bits = (bits << 8) + object[idx];
}
// Dump tail
tail = max % 3;
if (tail === 0) {
result += map[(bits >> 18) & 0x3F];
result += map[(bits >> 12) & 0x3F];
result += map[(bits >> 6) & 0x3F];
result += map[bits & 0x3F];
} else if (tail === 2) {
result += map[(bits >> 10) & 0x3F];
result += map[(bits >> 4) & 0x3F];
result += map[(bits << 2) & 0x3F];
result += map[64];
} else if (tail === 1) {
result += map[(bits >> 2) & 0x3F];
result += map[(bits << 4) & 0x3F];
result += map[64];
result += map[64];
}
return result;
}
function isBinary(object) {
return NodeBuffer && NodeBuffer.isBuffer(object);
}
module.exports = new Type('tag:yaml.org,2002:binary', {
kind: 'scalar',
resolve: resolveYamlBinary,
construct: constructYamlBinary,
predicate: isBinary,
represent: representYamlBinary
});

View File

@@ -0,0 +1,35 @@
'use strict';
var Type = require('../type');
function resolveYamlBoolean(data) {
if (data === null) return false;
var max = data.length;
return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
(max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
}
function constructYamlBoolean(data) {
return data === 'true' ||
data === 'True' ||
data === 'TRUE';
}
function isBoolean(object) {
return Object.prototype.toString.call(object) === '[object Boolean]';
}
module.exports = new Type('tag:yaml.org,2002:bool', {
kind: 'scalar',
resolve: resolveYamlBoolean,
construct: constructYamlBoolean,
predicate: isBoolean,
represent: {
lowercase: function (object) { return object ? 'true' : 'false'; },
uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
camelcase: function (object) { return object ? 'True' : 'False'; }
},
defaultStyle: 'lowercase'
});

View File

@@ -0,0 +1,116 @@
'use strict';
var common = require('../common');
var Type = require('../type');
var YAML_FLOAT_PATTERN = new RegExp(
// 2.5e4, 2.5 and integers
'^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
// .2e4, .2
// special case, seems not from spec
'|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
// 20:59
'|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
// .inf
'|[-+]?\\.(?:inf|Inf|INF)' +
// .nan
'|\\.(?:nan|NaN|NAN))$');
function resolveYamlFloat(data) {
if (data === null) return false;
if (!YAML_FLOAT_PATTERN.test(data) ||
// Quick hack to not allow integers end with `_`
// Probably should update regexp & check speed
data[data.length - 1] === '_') {
return false;
}
return true;
}
function constructYamlFloat(data) {
var value, sign, base, digits;
value = data.replace(/_/g, '').toLowerCase();
sign = value[0] === '-' ? -1 : 1;
digits = [];
if ('+-'.indexOf(value[0]) >= 0) {
value = value.slice(1);
}
if (value === '.inf') {
return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
} else if (value === '.nan') {
return NaN;
} else if (value.indexOf(':') >= 0) {
value.split(':').forEach(function (v) {
digits.unshift(parseFloat(v, 10));
});
value = 0.0;
base = 1;
digits.forEach(function (d) {
value += d * base;
base *= 60;
});
return sign * value;
}
return sign * parseFloat(value, 10);
}
var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
function representYamlFloat(object, style) {
var res;
if (isNaN(object)) {
switch (style) {
case 'lowercase': return '.nan';
case 'uppercase': return '.NAN';
case 'camelcase': return '.NaN';
}
} else if (Number.POSITIVE_INFINITY === object) {
switch (style) {
case 'lowercase': return '.inf';
case 'uppercase': return '.INF';
case 'camelcase': return '.Inf';
}
} else if (Number.NEGATIVE_INFINITY === object) {
switch (style) {
case 'lowercase': return '-.inf';
case 'uppercase': return '-.INF';
case 'camelcase': return '-.Inf';
}
} else if (common.isNegativeZero(object)) {
return '-0.0';
}
res = object.toString(10);
// JS stringifier can build scientific format without dots: 5e-100,
// while YAML requres dot: 5.e-100. Fix it with simple hack
return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
}
function isFloat(object) {
return (Object.prototype.toString.call(object) === '[object Number]') &&
(object % 1 !== 0 || common.isNegativeZero(object));
}
module.exports = new Type('tag:yaml.org,2002:float', {
kind: 'scalar',
resolve: resolveYamlFloat,
construct: constructYamlFloat,
predicate: isFloat,
represent: representYamlFloat,
defaultStyle: 'lowercase'
});

View File

@@ -0,0 +1,172 @@
'use strict';
var common = require('../common');
var Type = require('../type');
function isHexCode(c) {
return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
((0x61/* a */ <= c) && (c <= 0x66/* f */));
}
function isOctCode(c) {
return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
}
function isDecCode(c) {
return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
}
function resolveYamlInteger(data) {
if (data === null) return false;
var max = data.length,
index = 0,
hasDigits = false,
ch;
if (!max) return false;
ch = data[index];
// sign
if (ch === '-' || ch === '+') {
ch = data[++index];
}
if (ch === '0') {
// 0
if (index + 1 === max) return true;
ch = data[++index];
// base 2, base 8, base 16
if (ch === 'b') {
// base 2
index++;
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (ch !== '0' && ch !== '1') return false;
hasDigits = true;
}
return hasDigits && ch !== '_';
}
if (ch === 'x') {
// base 16
index++;
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (!isHexCode(data.charCodeAt(index))) return false;
hasDigits = true;
}
return hasDigits && ch !== '_';
}
// base 8
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (!isOctCode(data.charCodeAt(index))) return false;
hasDigits = true;
}
return hasDigits && ch !== '_';
}
// base 10 (except 0) or base 60
// value should not start with `_`;
if (ch === '_') return false;
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (ch === ':') break;
if (!isDecCode(data.charCodeAt(index))) {
return false;
}
hasDigits = true;
}
// Should have digits and should not end with `_`
if (!hasDigits || ch === '_') return false;
// if !base60 - done;
if (ch !== ':') return true;
// base60 almost not used, no needs to optimize
return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
}
function constructYamlInteger(data) {
var value = data, sign = 1, ch, base, digits = [];
if (value.indexOf('_') !== -1) {
value = value.replace(/_/g, '');
}
ch = value[0];
if (ch === '-' || ch === '+') {
if (ch === '-') sign = -1;
value = value.slice(1);
ch = value[0];
}
if (value === '0') return 0;
if (ch === '0') {
if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
if (value[1] === 'x') return sign * parseInt(value, 16);
return sign * parseInt(value, 8);
}
if (value.indexOf(':') !== -1) {
value.split(':').forEach(function (v) {
digits.unshift(parseInt(v, 10));
});
value = 0;
base = 1;
digits.forEach(function (d) {
value += (d * base);
base *= 60;
});
return sign * value;
}
return sign * parseInt(value, 10);
}
function isInteger(object) {
return (Object.prototype.toString.call(object)) === '[object Number]' &&
(object % 1 === 0 && !common.isNegativeZero(object));
}
module.exports = new Type('tag:yaml.org,2002:int', {
kind: 'scalar',
resolve: resolveYamlInteger,
construct: constructYamlInteger,
predicate: isInteger,
represent: {
binary: function (object) { return '0b' + object.toString(2); },
octal: function (object) { return '0' + object.toString(8); },
decimal: function (object) { return object.toString(10); },
hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); }
},
defaultStyle: 'decimal',
styleAliases: {
binary: [ 2, 'bin' ],
octal: [ 8, 'oct' ],
decimal: [ 10, 'dec' ],
hexadecimal: [ 16, 'hex' ]
}
});

View File

@@ -0,0 +1,84 @@
'use strict';
var esprima;
// Browserified version does not have esprima
//
// 1. For node.js just require module as deps
// 2. For browser try to require mudule via external AMD system.
// If not found - try to fallback to window.esprima. If not
// found too - then fail to parse.
//
try {
// workaround to exclude package from browserify list.
var _require = require;
esprima = _require('esprima');
} catch (_) {
/*global window */
if (typeof window !== 'undefined') esprima = window.esprima;
}
var Type = require('../../type');
function resolveJavascriptFunction(data) {
if (data === null) return false;
try {
var source = '(' + data + ')',
ast = esprima.parse(source, { range: true });
if (ast.type !== 'Program' ||
ast.body.length !== 1 ||
ast.body[0].type !== 'ExpressionStatement' ||
ast.body[0].expression.type !== 'FunctionExpression') {
return false;
}
return true;
} catch (err) {
return false;
}
}
function constructJavascriptFunction(data) {
/*jslint evil:true*/
var source = '(' + data + ')',
ast = esprima.parse(source, { range: true }),
params = [],
body;
if (ast.type !== 'Program' ||
ast.body.length !== 1 ||
ast.body[0].type !== 'ExpressionStatement' ||
ast.body[0].expression.type !== 'FunctionExpression') {
throw new Error('Failed to resolve function');
}
ast.body[0].expression.params.forEach(function (param) {
params.push(param.name);
});
body = ast.body[0].expression.body.range;
// Esprima's ranges include the first '{' and the last '}' characters on
// function expressions. So cut them out.
/*eslint-disable no-new-func*/
return new Function(params, source.slice(body[0] + 1, body[1] - 1));
}
function representJavascriptFunction(object /*, style*/) {
return object.toString();
}
function isFunction(object) {
return Object.prototype.toString.call(object) === '[object Function]';
}
module.exports = new Type('tag:yaml.org,2002:js/function', {
kind: 'scalar',
resolve: resolveJavascriptFunction,
construct: constructJavascriptFunction,
predicate: isFunction,
represent: representJavascriptFunction
});

View File

@@ -0,0 +1,60 @@
'use strict';
var Type = require('../../type');
function resolveJavascriptRegExp(data) {
if (data === null) return false;
if (data.length === 0) return false;
var regexp = data,
tail = /\/([gim]*)$/.exec(data),
modifiers = '';
// if regexp starts with '/' it can have modifiers and must be properly closed
// `/foo/gim` - modifiers tail can be maximum 3 chars
if (regexp[0] === '/') {
if (tail) modifiers = tail[1];
if (modifiers.length > 3) return false;
// if expression starts with /, is should be properly terminated
if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
}
return true;
}
function constructJavascriptRegExp(data) {
var regexp = data,
tail = /\/([gim]*)$/.exec(data),
modifiers = '';
// `/foo/gim` - tail can be maximum 4 chars
if (regexp[0] === '/') {
if (tail) modifiers = tail[1];
regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
}
return new RegExp(regexp, modifiers);
}
function representJavascriptRegExp(object /*, style*/) {
var result = '/' + object.source + '/';
if (object.global) result += 'g';
if (object.multiline) result += 'm';
if (object.ignoreCase) result += 'i';
return result;
}
function isRegExp(object) {
return Object.prototype.toString.call(object) === '[object RegExp]';
}
module.exports = new Type('tag:yaml.org,2002:js/regexp', {
kind: 'scalar',
resolve: resolveJavascriptRegExp,
construct: constructJavascriptRegExp,
predicate: isRegExp,
represent: representJavascriptRegExp
});

View File

@@ -0,0 +1,28 @@
'use strict';
var Type = require('../../type');
function resolveJavascriptUndefined() {
return true;
}
function constructJavascriptUndefined() {
/*eslint-disable no-undefined*/
return undefined;
}
function representJavascriptUndefined() {
return '';
}
function isUndefined(object) {
return typeof object === 'undefined';
}
module.exports = new Type('tag:yaml.org,2002:js/undefined', {
kind: 'scalar',
resolve: resolveJavascriptUndefined,
construct: constructJavascriptUndefined,
predicate: isUndefined,
represent: representJavascriptUndefined
});

View File

@@ -0,0 +1,8 @@
'use strict';
var Type = require('../type');
module.exports = new Type('tag:yaml.org,2002:map', {
kind: 'mapping',
construct: function (data) { return data !== null ? data : {}; }
});

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