fix npm security audit warning

This commit is contained in:
olevole
2020-10-04 00:40:03 +03:00
parent 6c8f6aa318
commit 74a2a22a71
58 changed files with 9719 additions and 37516 deletions

235
node/node_modules/esprima/ChangeLog generated vendored Normal file
View File

@@ -0,0 +1,235 @@
2018-06-17: Version 4.0.1
* Fix parsing async get/set in a class (issue 1861, 1875)
* Account for different return statement argument (issue 1829, 1897, 1928)
* Correct the handling of HTML comment when parsing a module (issue 1841)
* Fix incorrect parse async with proto-identifier-shorthand (issue 1847)
* Fix negative column in binary expression (issue 1844)
* Fix incorrect YieldExpression in object methods (issue 1834)
* Various documentation fixes
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.

21
node/node_modules/esprima/LICENSE.BSD generated vendored Normal file
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.

48
node/node_modules/esprima/README.md generated vendored
View File

@@ -1,24 +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, **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) standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
parser written in ECMAScript (also popularly known as parser written in ECMAScript (also popularly known as
[JavaScript](http://en.wikipedia.org/wiki/JavaScript>JavaScript)). [JavaScript](https://en.wikipedia.org/wiki/JavaScript)).
Esprima is created and maintained by [Ariya Hidayat](http://twitter.com/ariyahidayat), Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat),
with the help of [many contributors](https://github.com/jquery/esprima/contributors). with the help of [many contributors](https://github.com/jquery/esprima/contributors).
### Features ### Features
- Full support for ECMAScript 5.1 ([ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) - Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm))
- Sensible [syntax tree format](http://esprima.org/doc/index.html#ast) compatible with Mozilla - Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree)
[Parser AST](https://developer.mozilla.org/en/SpiderMonkey/Parser_API) - 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) - Optional tracking of syntax node location (index-based and line-column)
- Heavily tested (> 700 [unit tests](http://esprima.org/test/) with [full code coverage](http://esprima.org/test/coverage.html)) - [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))
- [Partial support](http://esprima.org/doc/es6.html) for ECMAScript 6
Esprima serves as a **building block** for some JavaScript ### API
language tools, from [code instrumentation](http://esprima.org/demo/functiontrace.html)
to [editor autocompletion](http://esprima.org/demo/autocomplete.html).
Esprima runs on many popular web browsers, as well as other ECMAScript platforms such as 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.
[Rhino](http://www.mozilla.org/rhino), [Nashorn](http://openjdk.java.net/projects/nashorn/), and [Node.js](https://npmjs.org/package/esprima).
For more information, check the web site [esprima.org](http://esprima.org). 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

@@ -1,7 +1,6 @@
#!/usr/bin/env node #!/usr/bin/env node
/* /*
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright JS Foundation and other contributors, https://js.foundation/
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: modification, are permitted provided that the following conditions are met:
@@ -26,11 +25,15 @@
/*jslint sloppy:true node:true rhino:true */ /*jslint sloppy:true node:true rhino:true */
var fs, esprima, fname, content, options, syntax; var fs, esprima, fname, forceFile, content, options, syntax;
if (typeof require === 'function') { if (typeof require === 'function') {
fs = require('fs'); fs = require('fs');
try {
esprima = require('esprima'); esprima = require('esprima');
} catch (e) {
esprima = require('../');
}
} else if (typeof load === 'function') { } else if (typeof load === 'function') {
try { try {
load('esprima.js'); load('esprima.js');
@@ -50,7 +53,7 @@ if (typeof console === 'undefined' && typeof process === 'undefined') {
function showUsage() { function showUsage() {
console.log('Usage:'); console.log('Usage:');
console.log(' esparse [options] file.js'); console.log(' esparse [options] [file.js]');
console.log(); console.log();
console.log('Available options:'); console.log('Available options:');
console.log(); console.log();
@@ -65,15 +68,18 @@ function showUsage() {
process.exit(1); process.exit(1);
} }
if (process.argv.length <= 2) {
showUsage();
}
options = {}; options = {};
process.argv.splice(2).forEach(function (entry) { process.argv.splice(2).forEach(function (entry) {
if (entry === '-h' || entry === '--help') { 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(); showUsage();
} else if (entry === '-v' || entry === '--version') { } else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); console.log('ECMAScript Parser (using Esprima version', esprima.version, ')');
@@ -91,22 +97,14 @@ process.argv.splice(2).forEach(function (entry) {
options.tokens = true; options.tokens = true;
} else if (entry === '--tolerant') { } else if (entry === '--tolerant') {
options.tolerant = true; options.tolerant = true;
} else if (entry.slice(0, 2) === '--') { } else if (entry === '--') {
forceFile = true;
} else {
console.log('Error: unknown option ' + entry + '.'); console.log('Error: unknown option ' + entry + '.');
process.exit(1); process.exit(1);
} else if (typeof fname === 'string') {
console.log('Error: more than one input file.');
process.exit(1);
} else {
fname = entry;
} }
}); });
if (typeof fname !== 'string') {
console.log('Error: no input file.');
process.exit(1);
}
// Special handling for regular expression literal since we need to // Special handling for regular expression literal since we need to
// convert it to a string literal, otherwise it will be decoded // convert it to a string literal, otherwise it will be decoded
// as object "{}" and the regular expression would be lost. // as object "{}" and the regular expression would be lost.
@@ -117,10 +115,24 @@ function adjustRegexLiteral(key, value) {
return value; return value;
} }
try { function run(content) {
content = fs.readFileSync(fname, 'utf-8');
syntax = esprima.parse(content, options); syntax = esprima.parse(content, options);
console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); 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) { } catch (e) {
console.log('Error: ' + e.message); console.log('Error: ' + e.message);
process.exit(1); process.exit(1);

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env node #!/usr/bin/env node
/* /*
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright JS Foundation and other contributors, https://js.foundation/
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: modification, are permitted provided that the following conditions are met:
@@ -26,7 +26,7 @@
/*jslint sloppy:true plusplus:true node:true rhino:true */ /*jslint sloppy:true plusplus:true node:true rhino:true */
/*global phantom:true */ /*global phantom:true */
var fs, system, esprima, options, fnames, count; var fs, system, esprima, options, fnames, forceFile, count;
if (typeof esprima === 'undefined') { if (typeof esprima === 'undefined') {
// PhantomJS can only require() relative files // PhantomJS can only require() relative files
@@ -36,7 +36,11 @@ if (typeof esprima === 'undefined') {
esprima = require('./esprima'); esprima = require('./esprima');
} else if (typeof require === 'function') { } else if (typeof require === 'function') {
fs = require('fs'); fs = require('fs');
try {
esprima = require('esprima'); esprima = require('esprima');
} catch (e) {
esprima = require('../');
}
} else if (typeof load === 'function') { } else if (typeof load === 'function') {
try { try {
load('esprima.js'); load('esprima.js');
@@ -51,7 +55,10 @@ if (typeof phantom === 'object') {
fs.readFileSync = fs.read; fs.readFileSync = fs.read;
process = { process = {
argv: [].slice.call(system.args), argv: [].slice.call(system.args),
exit: phantom.exit exit: phantom.exit,
on: function (evt, callback) {
callback();
}
}; };
process.argv.unshift('phantomjs'); process.argv.unshift('phantomjs');
} }
@@ -60,14 +67,20 @@ if (typeof phantom === 'object') {
if (typeof console === 'undefined' && typeof process === 'undefined') { if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print }; console = { log: print };
fs = { readFileSync: readFile }; fs = { readFileSync: readFile };
process = { argv: arguments, exit: quit }; process = {
argv: arguments,
exit: quit,
on: function (evt, callback) {
callback();
}
};
process.argv.unshift('esvalidate.js'); process.argv.unshift('esvalidate.js');
process.argv.unshift('rhino'); process.argv.unshift('rhino');
} }
function showUsage() { function showUsage() {
console.log('Usage:'); console.log('Usage:');
console.log(' esvalidate [options] file.js'); console.log(' esvalidate [options] [file.js...]');
console.log(); console.log();
console.log('Available options:'); console.log('Available options:');
console.log(); console.log();
@@ -77,10 +90,6 @@ function showUsage() {
process.exit(1); process.exit(1);
} }
if (process.argv.length <= 2) {
showUsage();
}
options = { options = {
format: 'plain' format: 'plain'
}; };
@@ -89,7 +98,9 @@ fnames = [];
process.argv.splice(2).forEach(function (entry) { process.argv.splice(2).forEach(function (entry) {
if (entry === '-h' || entry === '--help') { if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') {
fnames.push(entry);
} else if (entry === '-h' || entry === '--help') {
showUsage(); showUsage();
} else if (entry === '-v' || entry === '--version') { } else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); console.log('ECMAScript Validator (using Esprima version', esprima.version, ')');
@@ -101,17 +112,16 @@ process.argv.splice(2).forEach(function (entry) {
console.log('Error: unknown report format ' + options.format + '.'); console.log('Error: unknown report format ' + options.format + '.');
process.exit(1); process.exit(1);
} }
} else if (entry.slice(0, 2) === '--') { } else if (entry === '--') {
forceFile = true;
} else {
console.log('Error: unknown option ' + entry + '.'); console.log('Error: unknown option ' + entry + '.');
process.exit(1); process.exit(1);
} else {
fnames.push(entry);
} }
}); });
if (fnames.length === 0) { if (fnames.length === 0) {
console.log('Error: no input file.'); fnames.push('');
process.exit(1);
} }
if (options.format === 'junit') { if (options.format === 'junit') {
@@ -120,10 +130,13 @@ if (options.format === 'junit') {
} }
count = 0; count = 0;
fnames.forEach(function (fname) {
var content, timestamp, syntax, name; function run(fname, content) {
var timestamp, syntax, name;
try { try {
content = fs.readFileSync(fname, 'utf-8'); if (typeof content !== 'string') {
throw content;
}
if (content[0] === '#' && content[1] === '!') { if (content[0] === '#' && content[1] === '!') {
content = '//' + content.substr(2, content.length); content = '//' + content.substr(2, content.length);
@@ -181,19 +194,43 @@ fnames.forEach(function (fname) {
console.log(' </testcase>'); console.log(' </testcase>');
console.log('</testsuite>'); console.log('</testsuite>');
} else { } else {
console.log('Error: ' + e.message); 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);
}); });
if (options.format === 'junit') { process.on('exit', function () {
if (options.format === 'junit') {
console.log('</testsuites>'); console.log('</testsuites>');
} }
if (count > 0) { if (count > 0) {
process.exit(1); process.exit(1);
} }
if (count === 0 && typeof phantom === 'object') { if (count === 0 && typeof phantom === 'object') {
process.exit(0); process.exit(0);
} }
});

6709
node/node_modules/esprima/dist/esprima.js generated vendored Normal file

File diff suppressed because one or more lines are too long

4156
node/node_modules/esprima/esprima.js generated vendored

File diff suppressed because one or more lines are too long

View File

@@ -1,79 +1,87 @@
{ {
"_from": "esprima@~ 2.0.0", "_from": "esprima@^4.0.0",
"_id": "esprima@2.0.0", "_id": "esprima@4.0.1",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha1-YJrFwmZ+rlQztB657OziMxtBSY8=", "_integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
"_location": "/esprima", "_location": "/esprima",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "range", "type": "range",
"registry": true, "registry": true,
"raw": "esprima@~ 2.0.0", "raw": "esprima@^4.0.0",
"name": "esprima", "name": "esprima",
"escapedName": "esprima", "escapedName": "esprima",
"rawSpec": "~ 2.0.0", "rawSpec": "^4.0.0",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "~ 2.0.0" "fetchSpec": "^4.0.0"
}, },
"_requiredBy": [ "_requiredBy": [
"/js-yaml" "/js-yaml"
], ],
"_resolved": "https://registry.npmjs.org/esprima/-/esprima-2.0.0.tgz", "_resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"_shasum": "609ac5c2667eae5433b41eb9ecece2331b41498f", "_shasum": "13b04cdb3e6c5d19df91ab6987a8695619b0aa71",
"_spec": "esprima@~ 2.0.0", "_spec": "esprima@^4.0.0",
"_where": "/usr/home/web/cp/clonos/node/node_modules/js-yaml", "_where": "/usr/local/www/clonos/node/node_modules/js-yaml",
"author": { "author": {
"name": "Ariya Hidayat", "name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com" "email": "ariya.hidayat@gmail.com"
}, },
"bin": { "bin": {
"esparse": "./bin/esparse.js", "esparse": "bin/esparse.js",
"esvalidate": "./bin/esvalidate.js" "esvalidate": "bin/esvalidate.js"
}, },
"bugs": { "bugs": {
"url": "http://issues.esprima.org" "url": "https://github.com/jquery/esprima/issues"
}, },
"bundleDependencies": false, "bundleDependencies": false,
"deprecated": false, "deprecated": false,
"description": "ECMAScript parsing infrastructure for multipurpose analysis", "description": "ECMAScript parsing infrastructure for multipurpose analysis",
"devDependencies": { "devDependencies": {
"complexity-report": "~1.1.1", "codecov.io": "~0.1.6",
"escomplex-js": "1.0.0", "escomplex-js": "1.2.0",
"eslint": "~0.12.0", "everything.js": "~1.0.3",
"istanbul": "~0.2.6", "glob": "~7.1.0",
"jscs": "~1.10.0", "istanbul": "~0.4.0",
"json-diff": "~0.3.1", "json-diff": "~0.3.1",
"optimist": "~0.6.0", "karma": "~1.3.0",
"regenerate": "~0.6.2", "karma-chrome-launcher": "~2.0.0",
"unicode-7.0.0": "~0.1.5" "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": { "engines": {
"node": ">=0.4.0" "node": ">=4"
}, },
"files": [ "files": [
"bin", "bin",
"test/run.js", "dist/esprima.js"
"test/runner.js",
"test/test.js",
"test/compat.js",
"test/reflect.js",
"esprima.js"
], ],
"homepage": "http://esprima.org", "homepage": "http://esprima.org",
"keywords": [ "keywords": [
"ast", "ast",
"ecmascript", "ecmascript",
"esprima",
"javascript", "javascript",
"parser", "parser",
"syntax" "syntax"
], ],
"licenses": [ "license": "BSD-2-Clause",
{ "main": "dist/esprima.js",
"type": "BSD",
"url": "https://github.com/jquery/esprima/raw/master/LICENSE.BSD"
}
],
"main": "esprima.js",
"maintainers": [ "maintainers": [
{ {
"name": "Ariya Hidayat", "name": "Ariya Hidayat",
@@ -87,18 +95,43 @@
"url": "git+https://github.com/jquery/esprima.git" "url": "git+https://github.com/jquery/esprima.git"
}, },
"scripts": { "scripts": {
"analyze-coverage": "node node_modules/istanbul/lib/cli.js cover test/runner.js", "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",
"benchmark": "node test/benchmarks.js", "analyze-coverage": "istanbul cover test/unit-tests.js",
"benchmark-quick": "node test/benchmarks.js quick", "api-tests": "mocha -R dot test/api-tests.js",
"check-coverage": "node node_modules/istanbul/lib/cli.js check-coverage --statement 100 --branch 100 --function 100", "appveyor": "npm run compile && npm run all-tests && npm run browser-tests",
"check-version": "node tools/check-version.js", "benchmark": "npm run benchmark-parser && npm run benchmark-tokenizer",
"complexity": "node tools/list-complexity.js && cr -s -l -w --maxcyc 16 esprima.js", "benchmark-parser": "node -expose_gc test/benchmark-parser.js",
"coverage": "npm run analyze-coverage && npm run check-coverage", "benchmark-tokenizer": "node --expose_gc test/benchmark-tokenizer.js",
"eslint": "node node_modules/eslint/bin/eslint.js esprima.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-regex": "node tools/generate-identifier-regex.js",
"jscs": "jscs esprima.js test/*test.js", "generate-xhtml-entities": "node tools/generate-xhtml-entities.js",
"lint": "npm run check-version && npm run eslint && npm run jscs && npm run complexity", "grammar-tests": "node test/grammar-tests.js",
"test": "node test/run.js && npm run lint && npm run coverage" "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": "2.0.0" "version": "4.0.1"
} }

View File

@@ -1,244 +0,0 @@
/*
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint node: true */
/*global document: true, window:true, esprima: true, testReflect: true */
var runTests;
function getContext(esprima, reportCase, reportFailure) {
'use strict';
var Reflect, Pattern;
// Maps Mozilla Reflect object to our Esprima parser.
Reflect = {
parse: function (code) {
var result;
reportCase(code);
try {
result = esprima.parse(code);
} catch (error) {
result = error;
}
return result;
}
};
// This is used by Reflect test suite to match a syntax tree.
Pattern = function (obj) {
var pattern;
// Poor man's deep object cloning.
pattern = JSON.parse(JSON.stringify(obj));
// 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.
if (obj.type && obj.type === 'Literal') {
if (obj.value instanceof RegExp) {
pattern = {
type: obj.type,
value: obj.value.toString()
};
}
}
// Special handling for branch statement because SpiderMonkey
// prefers to put the 'alternate' property before 'consequent'.
if (obj.type && obj.type === 'IfStatement') {
pattern = {
type: pattern.type,
test: pattern.test,
consequent: pattern.consequent,
alternate: pattern.alternate
};
}
// Special handling for do while statement because SpiderMonkey
// prefers to put the 'test' property before 'body'.
if (obj.type && obj.type === 'DoWhileStatement') {
pattern = {
type: pattern.type,
body: pattern.body,
test: pattern.test
};
}
function adjustRegexLiteralAndRaw(key, value) {
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
} else if (key === 'raw' && typeof value === "string") {
// Ignore Esprima-specific 'raw' property.
return undefined;
} else if (key === 'regex' && typeof value === "object") {
// Ignore Esprima-specific 'regex' property.
return undefined;
}
return value;
}
if (obj.type && (obj.type === 'Program')) {
pattern.assert = function (tree) {
var actual, expected;
actual = JSON.stringify(tree, adjustRegexLiteralAndRaw, 4);
expected = JSON.stringify(obj, null, 4);
if (expected !== actual) {
reportFailure(expected, actual);
}
};
}
return pattern;
};
return {
Reflect: Reflect,
Pattern: Pattern
};
}
if (typeof window !== 'undefined') {
// Run all tests in a browser environment.
runTests = function () {
'use strict';
var total = 0,
failures = 0;
function setText(el, str) {
if (typeof el.innerText === 'string') {
el.innerText = str;
} else {
el.textContent = str;
}
}
function reportCase(code) {
var report, e;
report = document.getElementById('report');
e = document.createElement('pre');
e.setAttribute('class', 'code');
setText(e, code);
report.appendChild(e);
total += 1;
}
function reportFailure(expected, actual) {
var report, e;
failures += 1;
report = document.getElementById('report');
e = document.createElement('p');
setText(e, 'Expected');
report.appendChild(e);
e = document.createElement('pre');
e.setAttribute('class', 'expected');
setText(e, expected);
report.appendChild(e);
e = document.createElement('p');
setText(e, 'Actual');
report.appendChild(e);
e = document.createElement('pre');
e.setAttribute('class', 'actual');
setText(e, actual);
report.appendChild(e);
}
setText(document.getElementById('version'), esprima.version);
window.setTimeout(function () {
var tick, context = getContext(esprima, reportCase, reportFailure);
tick = new Date();
testReflect(context.Reflect, context.Pattern);
tick = (new Date()) - tick;
if (failures > 0) {
document.getElementById('status').className = 'alert-box alert';
setText(document.getElementById('status'), total + ' tests. ' +
'Failures: ' + failures + '. ' + tick + ' ms');
} else {
document.getElementById('status').className = 'alert-box success';
setText(document.getElementById('status'), total + ' tests. ' +
'No failure. ' + tick + ' ms');
}
}, 11);
};
} else {
(function (global) {
'use strict';
var esprima = require('../esprima'),
tick,
total = 0,
failures = [],
header,
current,
context;
function reportCase(code) {
total += 1;
current = code;
}
function reportFailure(expected, actual) {
failures.push({
source: current,
expected: expected.toString(),
actual: actual.toString()
});
}
context = getContext(esprima, reportCase, reportFailure);
tick = new Date();
require('./reflect').testReflect(context.Reflect, context.Pattern);
tick = (new Date()) - tick;
header = total + ' tests. ' + failures.length + ' failures. ' +
tick + ' ms';
if (failures.length) {
console.error(header);
failures.forEach(function (failure) {
console.error(failure.source + ': Expected\n ' +
failure.expected.split('\n').join('\n ') +
'\nto match\n ' + failure.actual);
});
} else {
console.log(header);
}
process.exit(failures.length === 0 ? 0 : 1);
}(this));
}
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@@ -1,422 +0,0 @@
// This is modified from Mozilla Reflect.parse test suite (the file is located
// at js/src/tests/js1_8_5/extensions/reflect-parse.js in the source tree).
//
// Some notable changes:
// * Removed unsupported features (destructuring, let, comprehensions...).
// * Removed tests for E4X (ECMAScript for XML).
// * Removed everything related to builder.
// * Enclosed every 'Pattern' construct with a scope.
// * Tweaked some expected tree to remove generator field.
// * Removed the test for bug 632030 and bug 632024.
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
*/
(function (exports) {
function testReflect(Reflect, Pattern) {
function program(elts) { return Pattern({ type: "Program", body: elts }); }
function exprStmt(expr) { return Pattern({ type: "ExpressionStatement", expression: expr }); }
function throwStmt(expr) { return Pattern({ type: "ThrowStatement", argument: expr }); }
function returnStmt(expr) { return Pattern({ type: "ReturnStatement", argument: expr }); }
function yieldExpr(expr) { return Pattern({ type: "YieldExpression", argument: expr }); }
function lit(val) { return Pattern({ type: "Literal", value: val }); }
var thisExpr = Pattern({ type: "ThisExpression" });
function funDecl(id, params, body) { return Pattern({ type: "FunctionDeclaration",
id: id,
params: params,
defaults: [],
body: body,
rest: null,
generator: false,
expression: false
}); }
function genFunDecl(id, params, body) { return Pattern({ type: "FunctionDeclaration",
id: id,
params: params,
defaults: [],
body: body,
rest: null,
generator: false,
expression: false
}); }
function declarator(id, init) { return Pattern({ type: "VariableDeclarator", id: id, init: init }); }
function varDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "var" }); }
function letDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "let" }); }
function constDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "const" }); }
function ident(name) { return Pattern({ type: "Identifier", name: name }); }
function dotExpr(obj, id) { return Pattern({ type: "MemberExpression", computed: false, object: obj, property: id }); }
function memExpr(obj, id) { return Pattern({ type: "MemberExpression", computed: true, object: obj, property: id }); }
function forStmt(init, test, update, body) { return Pattern({ type: "ForStatement", init: init, test: test, update: update, body: body }); }
function forInStmt(lhs, rhs, body) { return Pattern({ type: "ForInStatement", left: lhs, right: rhs, body: body, each: false }); }
function forEachInStmt(lhs, rhs, body) { return Pattern({ type: "ForInStatement", left: lhs, right: rhs, body: body, each: true }); }
function breakStmt(lab) { return Pattern({ type: "BreakStatement", label: lab }); }
function continueStmt(lab) { return Pattern({ type: "ContinueStatement", label: lab }); }
function blockStmt(body) { return Pattern({ type: "BlockStatement", body: body }); }
var emptyStmt = Pattern({ type: "EmptyStatement" });
function ifStmt(test, cons, alt) { return Pattern({ type: "IfStatement", test: test, alternate: alt, consequent: cons }); }
function labStmt(lab, stmt) { return Pattern({ type: "LabeledStatement", label: lab, body: stmt }); }
function withStmt(obj, stmt) { return Pattern({ type: "WithStatement", object: obj, body: stmt }); }
function whileStmt(test, stmt) { return Pattern({ type: "WhileStatement", test: test, body: stmt }); }
function doStmt(stmt, test) { return Pattern({ type: "DoWhileStatement", test: test, body: stmt }); }
function switchStmt(disc, cases) { return Pattern({ type: "SwitchStatement", discriminant: disc, cases: cases }); }
function caseClause(test, stmts) { return Pattern({ type: "SwitchCase", test: test, consequent: stmts }); }
function defaultClause(stmts) { return Pattern({ type: "SwitchCase", test: null, consequent: stmts }); }
function catchClause(id, guard, body) { if (guard) { return Pattern({ type: "GuardedCatchClause", param: id, guard: guard, body: body }) } else { return Pattern({ type: "CatchClause", param: id, body: body }); } }
function tryStmt(body, guarded, catches, fin) { return Pattern({ type: "TryStatement", block: body, guardedHandlers: guarded, handlers: catches, finalizer: fin }); }
function letStmt(head, body) { return Pattern({ type: "LetStatement", head: head, body: body }); }
function funExpr(id, args, body, gen) { return Pattern({ type: "FunctionExpression",
id: id,
params: args,
defaults: [],
body: body,
rest: null,
generator: false,
expression: false
}); }
function genFunExpr(id, args, body) { return Pattern({ type: "FunctionExpression",
id: id,
params: args,
defaults: [],
body: body,
rest: null,
generator: false,
expression: false
}); }
function unExpr(op, arg) { return Pattern({ type: "UnaryExpression", operator: op, argument: arg, prefix: true }); }
function binExpr(op, left, right) { return Pattern({ type: "BinaryExpression", operator: op, left: left, right: right }); }
function aExpr(op, left, right) { return Pattern({ type: "AssignmentExpression", operator: op, left: left, right: right }); }
function updExpr(op, arg, prefix) { return Pattern({ type: "UpdateExpression", operator: op, argument: arg, prefix: prefix }); }
function logExpr(op, left, right) { return Pattern({ type: "LogicalExpression", operator: op, left: left, right: right }); }
function condExpr(test, cons, alt) { return Pattern({ type: "ConditionalExpression", test: test, consequent: cons, alternate: alt }); }
function seqExpr(exprs) { return Pattern({ type: "SequenceExpression", expressions: exprs }); }
function newExpr(callee, args) { return Pattern({ type: "NewExpression", callee: callee, arguments: args }); }
function callExpr(callee, args) { return Pattern({ type: "CallExpression", callee: callee, arguments: args }); }
function arrExpr(elts) { return Pattern({ type: "ArrayExpression", elements: elts }); }
function objExpr(elts) { return Pattern({ type: "ObjectExpression", properties: elts }); }
function objProp(key, value, kind) { return Pattern({ type: "Property", key: key, value: value, kind: kind, method: false, shorthand: false }); }
function arrPatt(elts) { return Pattern({ type: "ArrayPattern", elements: elts }); }
function objPatt(elts) { return Pattern({ type: "ObjectPattern", properties: elts }); }
function localSrc(src) { return "(function(){ " + src + " })"; }
function localPatt(patt) { return program([exprStmt(funExpr(null, [], blockStmt([patt])))]); }
function blockSrc(src) { return "(function(){ { " + src + " } })"; }
function blockPatt(patt) { return program([exprStmt(funExpr(null, [], blockStmt([blockStmt([patt])])))]); }
function assertBlockStmt(src, patt) {
blockPatt(patt).assert(Reflect.parse(blockSrc(src)));
}
function assertBlockExpr(src, patt) {
assertBlockStmt(src, exprStmt(patt));
}
function assertBlockDecl(src, patt, builder) {
blockPatt(patt).assert(Reflect.parse(blockSrc(src), {builder: builder}));
}
function assertLocalStmt(src, patt) {
localPatt(patt).assert(Reflect.parse(localSrc(src)));
}
function assertLocalExpr(src, patt) {
assertLocalStmt(src, exprStmt(patt));
}
function assertLocalDecl(src, patt) {
localPatt(patt).assert(Reflect.parse(localSrc(src)));
}
function assertGlobalStmt(src, patt, builder) {
program([patt]).assert(Reflect.parse(src, {builder: builder}));
}
function assertGlobalExpr(src, patt, builder) {
program([exprStmt(patt)]).assert(Reflect.parse(src, {builder: builder}));
//assertStmt(src, exprStmt(patt));
}
function assertGlobalDecl(src, patt) {
program([patt]).assert(Reflect.parse(src));
}
function assertProg(src, patt) {
program(patt).assert(Reflect.parse(src));
}
function assertStmt(src, patt) {
assertLocalStmt(src, patt);
assertGlobalStmt(src, patt);
assertBlockStmt(src, patt);
}
function assertExpr(src, patt) {
assertLocalExpr(src, patt);
assertGlobalExpr(src, patt);
assertBlockExpr(src, patt);
}
function assertDecl(src, patt) {
assertLocalDecl(src, patt);
assertGlobalDecl(src, patt);
assertBlockDecl(src, patt);
}
function assertError(src, errorType) {
try {
Reflect.parse(src);
} catch (e) {
return;
}
throw new Error("expected " + errorType.name + " for " + uneval(src));
}
// general tests
// NB: These are useful but for now jit-test doesn't do I/O reliably.
//program(_).assert(Reflect.parse(snarf('data/flapjax.txt')));
//program(_).assert(Reflect.parse(snarf('data/jquery-1.4.2.txt')));
//program(_).assert(Reflect.parse(snarf('data/prototype.js')));
//program(_).assert(Reflect.parse(snarf('data/dojo.js.uncompressed.js')));
//program(_).assert(Reflect.parse(snarf('data/mootools-1.2.4-core-nc.js')));
// declarations
assertDecl("var x = 1, y = 2, z = 3",
varDecl([declarator(ident("x"), lit(1)),
declarator(ident("y"), lit(2)),
declarator(ident("z"), lit(3))]));
assertDecl("var x, y, z",
varDecl([declarator(ident("x"), null),
declarator(ident("y"), null),
declarator(ident("z"), null)]));
assertDecl("function foo() { }",
funDecl(ident("foo"), [], blockStmt([])));
assertDecl("function foo() { return 42 }",
funDecl(ident("foo"), [], blockStmt([returnStmt(lit(42))])));
// Bug 591437: rebound args have their defs turned into uses
assertDecl("function f(a) { function a() { } }",
funDecl(ident("f"), [ident("a")], blockStmt([funDecl(ident("a"), [], blockStmt([]))])));
assertDecl("function f(a,b,c) { function b() { } }",
funDecl(ident("f"), [ident("a"),ident("b"),ident("c")], blockStmt([funDecl(ident("b"), [], blockStmt([]))])));
// expressions
assertExpr("true", lit(true));
assertExpr("false", lit(false));
assertExpr("42", lit(42));
assertExpr("(/asdf/)", lit(/asdf/));
assertExpr("this", thisExpr);
assertExpr("foo", ident("foo"));
assertExpr("foo.bar", dotExpr(ident("foo"), ident("bar")));
assertExpr("foo[bar]", memExpr(ident("foo"), ident("bar")));
assertExpr("(function(){})", funExpr(null, [], blockStmt([])));
assertExpr("(function f() {})", funExpr(ident("f"), [], blockStmt([])));
assertExpr("(function f(x,y,z) {})", funExpr(ident("f"), [ident("x"),ident("y"),ident("z")], blockStmt([])));
assertExpr("(++x)", updExpr("++", ident("x"), true));
assertExpr("(x++)", updExpr("++", ident("x"), false));
assertExpr("(+x)", unExpr("+", ident("x")));
assertExpr("(-x)", unExpr("-", ident("x")));
assertExpr("(!x)", unExpr("!", ident("x")));
assertExpr("(~x)", unExpr("~", ident("x")));
assertExpr("(delete x)", unExpr("delete", ident("x")));
assertExpr("(typeof x)", unExpr("typeof", ident("x")));
assertExpr("(void x)", unExpr("void", ident("x")));
assertExpr("(x == y)", binExpr("==", ident("x"), ident("y")));
assertExpr("(x != y)", binExpr("!=", ident("x"), ident("y")));
assertExpr("(x === y)", binExpr("===", ident("x"), ident("y")));
assertExpr("(x !== y)", binExpr("!==", ident("x"), ident("y")));
assertExpr("(x < y)", binExpr("<", ident("x"), ident("y")));
assertExpr("(x <= y)", binExpr("<=", ident("x"), ident("y")));
assertExpr("(x > y)", binExpr(">", ident("x"), ident("y")));
assertExpr("(x >= y)", binExpr(">=", ident("x"), ident("y")));
assertExpr("(x << y)", binExpr("<<", ident("x"), ident("y")));
assertExpr("(x >> y)", binExpr(">>", ident("x"), ident("y")));
assertExpr("(x >>> y)", binExpr(">>>", ident("x"), ident("y")));
assertExpr("(x + y)", binExpr("+", ident("x"), ident("y")));
assertExpr("(w + x + y + z)", binExpr("+", binExpr("+", binExpr("+", ident("w"), ident("x")), ident("y")), ident("z")));
assertExpr("(x - y)", binExpr("-", ident("x"), ident("y")));
assertExpr("(w - x - y - z)", binExpr("-", binExpr("-", binExpr("-", ident("w"), ident("x")), ident("y")), ident("z")));
assertExpr("(x * y)", binExpr("*", ident("x"), ident("y")));
assertExpr("(x / y)", binExpr("/", ident("x"), ident("y")));
assertExpr("(x % y)", binExpr("%", ident("x"), ident("y")));
assertExpr("(x | y)", binExpr("|", ident("x"), ident("y")));
assertExpr("(x ^ y)", binExpr("^", ident("x"), ident("y")));
assertExpr("(x & y)", binExpr("&", ident("x"), ident("y")));
assertExpr("(x in y)", binExpr("in", ident("x"), ident("y")));
assertExpr("(x instanceof y)", binExpr("instanceof", ident("x"), ident("y")));
assertExpr("(x = y)", aExpr("=", ident("x"), ident("y")));
assertExpr("(x += y)", aExpr("+=", ident("x"), ident("y")));
assertExpr("(x -= y)", aExpr("-=", ident("x"), ident("y")));
assertExpr("(x *= y)", aExpr("*=", ident("x"), ident("y")));
assertExpr("(x /= y)", aExpr("/=", ident("x"), ident("y")));
assertExpr("(x %= y)", aExpr("%=", ident("x"), ident("y")));
assertExpr("(x <<= y)", aExpr("<<=", ident("x"), ident("y")));
assertExpr("(x >>= y)", aExpr(">>=", ident("x"), ident("y")));
assertExpr("(x >>>= y)", aExpr(">>>=", ident("x"), ident("y")));
assertExpr("(x |= y)", aExpr("|=", ident("x"), ident("y")));
assertExpr("(x ^= y)", aExpr("^=", ident("x"), ident("y")));
assertExpr("(x &= y)", aExpr("&=", ident("x"), ident("y")));
assertExpr("(x || y)", logExpr("||", ident("x"), ident("y")));
assertExpr("(x && y)", logExpr("&&", ident("x"), ident("y")));
assertExpr("(w || x || y || z)", logExpr("||", logExpr("||", logExpr("||", ident("w"), ident("x")), ident("y")), ident("z")));
assertExpr("(x ? y : z)", condExpr(ident("x"), ident("y"), ident("z")));
assertExpr("(x,y)", seqExpr([ident("x"),ident("y")]));
assertExpr("(x,y,z)", seqExpr([ident("x"),ident("y"),ident("z")]));
assertExpr("(a,b,c,d,e,f,g)", seqExpr([ident("a"),ident("b"),ident("c"),ident("d"),ident("e"),ident("f"),ident("g")]));
assertExpr("(new Object)", newExpr(ident("Object"), []));
assertExpr("(new Object())", newExpr(ident("Object"), []));
assertExpr("(new Object(42))", newExpr(ident("Object"), [lit(42)]));
assertExpr("(new Object(1,2,3))", newExpr(ident("Object"), [lit(1),lit(2),lit(3)]));
assertExpr("(String())", callExpr(ident("String"), []));
assertExpr("(String(42))", callExpr(ident("String"), [lit(42)]));
assertExpr("(String(1,2,3))", callExpr(ident("String"), [lit(1),lit(2),lit(3)]));
assertExpr("[]", arrExpr([]));
assertExpr("[1]", arrExpr([lit(1)]));
assertExpr("[1,2]", arrExpr([lit(1),lit(2)]));
assertExpr("[1,2,3]", arrExpr([lit(1),lit(2),lit(3)]));
assertExpr("[1,,2,3]", arrExpr([lit(1),,lit(2),lit(3)]));
assertExpr("[1,,,2,3]", arrExpr([lit(1),,,lit(2),lit(3)]));
assertExpr("[1,,,2,,3]", arrExpr([lit(1),,,lit(2),,lit(3)]));
assertExpr("[1,,,2,,,3]", arrExpr([lit(1),,,lit(2),,,lit(3)]));
assertExpr("[,1,2,3]", arrExpr([,lit(1),lit(2),lit(3)]));
assertExpr("[,,1,2,3]", arrExpr([,,lit(1),lit(2),lit(3)]));
assertExpr("[,,,1,2,3]", arrExpr([,,,lit(1),lit(2),lit(3)]));
assertExpr("[,,,1,2,3,]", arrExpr([,,,lit(1),lit(2),lit(3)]));
assertExpr("[,,,1,2,3,,]", arrExpr([,,,lit(1),lit(2),lit(3),undefined]));
assertExpr("[,,,1,2,3,,,]", arrExpr([,,,lit(1),lit(2),lit(3),undefined,undefined]));
assertExpr("[,,,,,]", arrExpr([undefined,undefined,undefined,undefined,undefined]));
assertExpr("({})", objExpr([]));
assertExpr("({x:1})", objExpr([objProp(ident("x"), lit(1), "init")]));
assertExpr("({x:1, y:2})", objExpr([objProp(ident("x"), lit(1), "init"),
objProp(ident("y"), lit(2), "init")]));
assertExpr("({x:1, y:2, z:3})", objExpr([objProp(ident("x"), lit(1), "init"),
objProp(ident("y"), lit(2), "init"),
objProp(ident("z"), lit(3), "init") ]));
assertExpr("({x:1, 'y':2, z:3})", objExpr([objProp(ident("x"), lit(1), "init"),
objProp(lit("y"), lit(2), "init"),
objProp(ident("z"), lit(3), "init") ]));
assertExpr("({'x':1, 'y':2, z:3})", objExpr([objProp(lit("x"), lit(1), "init"),
objProp(lit("y"), lit(2), "init"),
objProp(ident("z"), lit(3), "init") ]));
assertExpr("({'x':1, 'y':2, 3:3})", objExpr([objProp(lit("x"), lit(1), "init"),
objProp(lit("y"), lit(2), "init"),
objProp(lit(3), lit(3), "init") ]));
// Bug 571617: eliminate constant-folding
assertExpr("2 + 3", binExpr("+", lit(2), lit(3)));
// Bug 632026: constant-folding
assertExpr("typeof(0?0:a)", unExpr("typeof", condExpr(lit(0), lit(0), ident("a"))));
// Bug 632056: constant-folding
program([exprStmt(ident("f")),
ifStmt(lit(1),
funDecl(ident("f"), [], blockStmt([])),
null)]).assert(Reflect.parse("f; if (1) function f(){}"));
// statements
assertStmt("throw 42", throwStmt(lit(42)));
assertStmt("for (;;) break", forStmt(null, null, null, breakStmt(null)));
assertStmt("for (x; y; z) break", forStmt(ident("x"), ident("y"), ident("z"), breakStmt(null)));
assertStmt("for (var x; y; z) break", forStmt(varDecl([declarator(ident("x"), null)]), ident("y"), ident("z"), breakStmt(null)));
assertStmt("for (var x = 42; y; z) break", forStmt(varDecl([declarator(ident("x"), lit(42))]), ident("y"), ident("z"), breakStmt(null)));
assertStmt("for (x; ; z) break", forStmt(ident("x"), null, ident("z"), breakStmt(null)));
assertStmt("for (var x; ; z) break", forStmt(varDecl([declarator(ident("x"), null)]), null, ident("z"), breakStmt(null)));
assertStmt("for (var x = 42; ; z) break", forStmt(varDecl([declarator(ident("x"), lit(42))]), null, ident("z"), breakStmt(null)));
assertStmt("for (x; y; ) break", forStmt(ident("x"), ident("y"), null, breakStmt(null)));
assertStmt("for (var x; y; ) break", forStmt(varDecl([declarator(ident("x"), null)]), ident("y"), null, breakStmt(null)));
assertStmt("for (var x = 42; y; ) break", forStmt(varDecl([declarator(ident("x"),lit(42))]), ident("y"), null, breakStmt(null)));
assertStmt("for (var x in y) break", forInStmt(varDecl([declarator(ident("x"),null)]), ident("y"), breakStmt(null)));
assertStmt("for (x in y) break", forInStmt(ident("x"), ident("y"), breakStmt(null)));
assertStmt("{ }", blockStmt([]));
assertStmt("{ throw 1; throw 2; throw 3; }", blockStmt([ throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))]));
assertStmt(";", emptyStmt);
assertStmt("if (foo) throw 42;", ifStmt(ident("foo"), throwStmt(lit(42)), null));
assertStmt("if (foo) throw 42; else true;", ifStmt(ident("foo"), throwStmt(lit(42)), exprStmt(lit(true))));
assertStmt("if (foo) { throw 1; throw 2; throw 3; }",
ifStmt(ident("foo"),
blockStmt([throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))]),
null));
assertStmt("if (foo) { throw 1; throw 2; throw 3; } else true;",
ifStmt(ident("foo"),
blockStmt([throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))]),
exprStmt(lit(true))));
assertStmt("foo: for(;;) break foo;", labStmt(ident("foo"), forStmt(null, null, null, breakStmt(ident("foo")))));
assertStmt("foo: for(;;) continue foo;", labStmt(ident("foo"), forStmt(null, null, null, continueStmt(ident("foo")))));
assertStmt("with (obj) { }", withStmt(ident("obj"), blockStmt([])));
assertStmt("with (obj) { obj; }", withStmt(ident("obj"), blockStmt([exprStmt(ident("obj"))])));
assertStmt("while (foo) { }", whileStmt(ident("foo"), blockStmt([])));
assertStmt("while (foo) { foo; }", whileStmt(ident("foo"), blockStmt([exprStmt(ident("foo"))])));
assertStmt("do { } while (foo);", doStmt(blockStmt([]), ident("foo")));
assertStmt("do { foo; } while (foo)", doStmt(blockStmt([exprStmt(ident("foo"))]), ident("foo")));
assertStmt("switch (foo) { case 1: 1; break; case 2: 2; break; default: 3; }",
switchStmt(ident("foo"),
[ caseClause(lit(1), [ exprStmt(lit(1)), breakStmt(null) ]),
caseClause(lit(2), [ exprStmt(lit(2)), breakStmt(null) ]),
defaultClause([ exprStmt(lit(3)) ]) ]));
assertStmt("switch (foo) { case 1: 1; break; case 2: 2; break; default: 3; case 42: 42; }",
switchStmt(ident("foo"),
[ caseClause(lit(1), [ exprStmt(lit(1)), breakStmt(null) ]),
caseClause(lit(2), [ exprStmt(lit(2)), breakStmt(null) ]),
defaultClause([ exprStmt(lit(3)) ]),
caseClause(lit(42), [ exprStmt(lit(42)) ]) ]));
assertStmt("try { } catch (e) { }",
tryStmt(blockStmt([]),
[],
[ catchClause(ident("e"), null, blockStmt([])) ],
null));
assertStmt("try { } catch (e) { } finally { }",
tryStmt(blockStmt([]),
[],
[ catchClause(ident("e"), null, blockStmt([])) ],
blockStmt([])));
assertStmt("try { } finally { }",
tryStmt(blockStmt([]),
[],
[],
blockStmt([])));
// redeclarations (TOK_NAME nodes with lexdef)
assertStmt("function f() { function g() { } function g() { } }",
funDecl(ident("f"), [], blockStmt([funDecl(ident("g"), [], blockStmt([])),
funDecl(ident("g"), [], blockStmt([]))])));
assertStmt("function f() { function g() { } function g() { return 42 } }",
funDecl(ident("f"), [], blockStmt([funDecl(ident("g"), [], blockStmt([])),
funDecl(ident("g"), [], blockStmt([returnStmt(lit(42))]))])));
assertStmt("function f() { var x = 42; var x = 43; }",
funDecl(ident("f"), [], blockStmt([varDecl([declarator(ident("x"),lit(42))]),
varDecl([declarator(ident("x"),lit(43))])])));
// getters and setters
assertExpr("({ get x() { return 42 } })",
objExpr([ objProp(ident("x"),
funExpr(null, [], blockStmt([returnStmt(lit(42))])),
"get" ) ]));
assertExpr("({ set x(v) { return 42 } })",
objExpr([ objProp(ident("x"),
funExpr(null, [ident("v")], blockStmt([returnStmt(lit(42))])),
"set" ) ]));
}
exports.testReflect = testReflect;
}(typeof exports === 'undefined' ? this : exports));

View File

@@ -1,67 +0,0 @@
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint node:true */
(function () {
'use strict';
var child = require('child_process'),
nodejs = '"' + process.execPath + '"',
ret = 0,
suites,
index;
suites = [
'runner',
'compat',
'parselibs'
];
function nextTest() {
var suite = suites[index];
if (index < suites.length) {
child.exec(nodejs + ' ./test/' + suite + '.js', function (err, stdout, stderr) {
if (stdout) {
process.stdout.write(suite + ': ' + stdout);
}
if (stderr) {
process.stderr.write(suite + ': ' + stderr);
}
if (err) {
ret = err.code;
}
index += 1;
nextTest();
});
} else {
process.exit(ret);
}
}
index = 0;
nextTest();
}());

View File

@@ -1,494 +0,0 @@
/*
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2011 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2011 Arpad Borsos <arpad.borsos@googlemail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint browser:true node:true */
/*global esprima:true, testFixture:true */
var runTests;
// Special handling for regular expression literals: remove their `value`
// property since it may be `null` if it represents a regular expression
// that is not supported in the current environment. The `regex` property
// will be compared instead.
function adjustRegexLiteral(key, value) {
'use strict';
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
}
return value;
}
function NotMatchingError(expected, actual) {
'use strict';
Error.call(this, 'Expected ');
this.expected = expected;
this.actual = actual;
}
NotMatchingError.prototype = new Error();
function errorToObject(e) {
'use strict';
var msg = e.toString();
// Opera 9.64 produces an non-standard string in toString().
if (msg.substr(0, 6) !== 'Error:') {
if (typeof e.message === 'string') {
msg = 'Error: ' + e.message;
}
}
return {
index: e.index,
lineNumber: e.lineNumber,
column: e.column,
message: msg
};
}
function sortedObject(o) {
if (o === null) {
return o;
}
if (o instanceof Array) {
return o.map(sortedObject);
}
if (typeof o !== 'object') {
return o;
}
if (o instanceof RegExp) {
return o;
}
var keys = Object.keys(o);
var result = {
range: undefined,
loc: undefined
};
keys.forEach(function (key) {
if (o.hasOwnProperty(key)){
result[key] = sortedObject(o[key]);
}
});
return result;
}
function hasAttachedComment(syntax) {
var key;
for (key in syntax) {
if (key === 'leadingComments' || key === 'trailingComments') {
return true;
}
if (typeof syntax[key] === 'object' && syntax[key] !== null) {
if (hasAttachedComment(syntax[key])) {
return true;
}
}
}
return false;
}
function testParse(esprima, code, syntax) {
'use strict';
var expected, tree, actual, options, StringObject, i, len;
// alias, so that JSLint does not complain.
StringObject = String;
options = {
comment: (typeof syntax.comments !== 'undefined'),
range: true,
loc: true,
tokens: (typeof syntax.tokens !== 'undefined'),
raw: true,
tolerant: (typeof syntax.errors !== 'undefined'),
source: null
};
if (options.comment) {
options.attachComment = hasAttachedComment(syntax);
}
if (typeof syntax.tokens !== 'undefined') {
if (syntax.tokens.length > 0) {
options.range = (typeof syntax.tokens[0].range !== 'undefined');
options.loc = (typeof syntax.tokens[0].loc !== 'undefined');
}
}
if (typeof syntax.comments !== 'undefined') {
if (syntax.comments.length > 0) {
options.range = (typeof syntax.comments[0].range !== 'undefined');
options.loc = (typeof syntax.comments[0].loc !== 'undefined');
}
}
if (options.loc) {
options.source = syntax.loc.source;
}
syntax = sortedObject(syntax);
expected = JSON.stringify(syntax, adjustRegexLiteral, 4);
try {
// Some variations of the options.
tree = esprima.parse(code, { tolerant: options.tolerant });
tree = esprima.parse(code, { tolerant: options.tolerant, range: true });
tree = esprima.parse(code, { tolerant: options.tolerant, loc: true });
tree = esprima.parse(code, options);
tree = (options.comment || options.tokens || options.tolerant) ? tree : tree.body[0];
if (options.tolerant) {
for (i = 0, len = tree.errors.length; i < len; i += 1) {
tree.errors[i] = errorToObject(tree.errors[i]);
}
}
tree = sortedObject(tree);
actual = JSON.stringify(tree, adjustRegexLiteral, 4);
// Only to ensure that there is no error when using string object.
esprima.parse(new StringObject(code), options);
} catch (e) {
throw new NotMatchingError(expected, e.toString());
}
if (expected !== actual) {
throw new NotMatchingError(expected, actual);
}
function filter(key, value) {
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
}
return (key === 'loc' || key === 'range') ? undefined : value;
}
if (options.tolerant) {
return;
}
// Check again without any location info.
options.range = false;
options.loc = false;
syntax = sortedObject(syntax);
expected = JSON.stringify(syntax, filter, 4);
try {
tree = esprima.parse(code, options);
tree = (options.comment || options.tokens) ? tree : tree.body[0];
if (options.tolerant) {
for (i = 0, len = tree.errors.length; i < len; i += 1) {
tree.errors[i] = errorToObject(tree.errors[i]);
}
}
tree = sortedObject(tree);
actual = JSON.stringify(tree, filter, 4);
} catch (e) {
throw new NotMatchingError(expected, e.toString());
}
if (expected !== actual) {
throw new NotMatchingError(expected, actual);
}
}
function testTokenize(esprima, code, tokens) {
'use strict';
var options, expected, actual, tree;
options = {
comment: true,
tolerant: true,
loc: true,
range: true
};
expected = JSON.stringify(tokens, null, 4);
try {
tree = esprima.tokenize(code, options);
actual = JSON.stringify(tree, null, 4);
} catch (e) {
throw new NotMatchingError(expected, e.toString());
}
if (expected !== actual) {
throw new NotMatchingError(expected, actual);
}
}
function testError(esprima, code, exception) {
'use strict';
var i, options, expected, actual, err, handleInvalidRegexFlag, tokenize;
// Different parsing options should give the same error.
options = [
{},
{ comment: true },
{ raw: true },
{ raw: true, comment: true }
];
// If handleInvalidRegexFlag is true, an invalid flag in a regular expression
// will throw an exception. In some old version of V8, this is not the case
// and hence handleInvalidRegexFlag is false.
handleInvalidRegexFlag = false;
try {
'test'.match(new RegExp('[a-z]', 'x'));
} catch (e) {
handleInvalidRegexFlag = true;
}
exception.description = exception.message.replace(/Error: Line [0-9]+: /, '');
if (exception.tokenize) {
tokenize = true;
exception.tokenize = undefined;
}
expected = JSON.stringify(exception);
for (i = 0; i < options.length; i += 1) {
try {
if (tokenize) {
esprima.tokenize(code, options[i]);
} else {
esprima.parse(code, options[i]);
}
} catch (e) {
err = errorToObject(e);
err.description = e.description;
actual = JSON.stringify(err);
}
if (expected !== actual) {
// Compensate for old V8 which does not handle invalid flag.
if (exception.message.indexOf('Invalid regular expression') > 0) {
if (typeof actual === 'undefined' && !handleInvalidRegexFlag) {
return;
}
}
throw new NotMatchingError(expected, actual);
}
}
}
function testAPI(esprima, code, result) {
'use strict';
var expected, res, actual;
expected = JSON.stringify(result.result, null, 4);
try {
if (typeof result.property !== 'undefined') {
res = esprima[result.property];
} else {
res = esprima[result.call].apply(esprima, result.args);
}
actual = JSON.stringify(res, adjustRegexLiteral, 4);
} catch (e) {
throw new NotMatchingError(expected, e.toString());
}
if (expected !== actual) {
throw new NotMatchingError(expected, actual);
}
}
function runTest(esprima, code, result) {
'use strict';
if (result.hasOwnProperty('lineNumber')) {
testError(esprima, code, result);
} else if (result.hasOwnProperty('result')) {
testAPI(esprima, code, result);
} else if (result instanceof Array) {
testTokenize(esprima, code, result);
} else {
testParse(esprima, code, result);
}
}
if (typeof window !== 'undefined') {
// Run all tests in a browser environment.
runTests = function () {
'use strict';
var total = 0,
failures = 0,
category,
fixture,
source,
tick,
expected;
function setText(el, str) {
if (typeof el.innerText === 'string') {
el.innerText = str;
} else {
el.textContent = str;
}
}
function startCategory(category) {
var report, e;
report = document.getElementById('report');
e = document.createElement('h4');
setText(e, category);
report.appendChild(e);
}
function reportSuccess(code) {
var report, e;
report = document.getElementById('report');
e = document.createElement('pre');
e.setAttribute('class', 'code');
setText(e, code);
report.appendChild(e);
}
function reportFailure(code, expected, actual) {
var report, e;
report = document.getElementById('report');
e = document.createElement('p');
setText(e, 'Code:');
report.appendChild(e);
e = document.createElement('pre');
e.setAttribute('class', 'code');
setText(e, code);
report.appendChild(e);
e = document.createElement('p');
setText(e, 'Expected');
report.appendChild(e);
e = document.createElement('pre');
e.setAttribute('class', 'expected');
setText(e, expected);
report.appendChild(e);
e = document.createElement('p');
setText(e, 'Actual');
report.appendChild(e);
e = document.createElement('pre');
e.setAttribute('class', 'actual');
setText(e, actual);
report.appendChild(e);
}
setText(document.getElementById('version'), esprima.version);
tick = new Date();
for (category in testFixture) {
if (testFixture.hasOwnProperty(category)) {
startCategory(category);
fixture = testFixture[category];
for (source in fixture) {
if (fixture.hasOwnProperty(source)) {
expected = fixture[source];
total += 1;
try {
runTest(esprima, source, expected);
reportSuccess(source, JSON.stringify(expected, null, 4));
} catch (e) {
failures += 1;
reportFailure(source, e.expected, e.actual);
}
}
}
}
}
tick = (new Date()) - tick;
if (failures > 0) {
document.getElementById('status').className = 'alert-box alert';
setText(document.getElementById('status'), total + ' tests. ' +
'Failures: ' + failures + '. ' + tick + ' ms.');
} else {
document.getElementById('status').className = 'alert-box success';
setText(document.getElementById('status'), total + ' tests. ' +
'No failure. ' + tick + ' ms.');
}
};
} else {
(function () {
'use strict';
var esprima = require('../esprima'),
vm = require('vm'),
fs = require('fs'),
diff = require('json-diff').diffString,
total = 0,
failures = [],
tick = new Date(),
expected,
header;
vm.runInThisContext(fs.readFileSync(__dirname + '/test.js', 'utf-8'));
Object.keys(testFixture).forEach(function (category) {
Object.keys(testFixture[category]).forEach(function (source) {
total += 1;
expected = testFixture[category][source];
try {
runTest(esprima, source, expected);
} catch (e) {
e.source = source;
failures.push(e);
}
});
});
tick = (new Date()) - tick;
header = total + ' tests. ' + failures.length + ' failures. ' +
tick + ' ms';
if (failures.length) {
console.error(header);
failures.forEach(function (failure) {
try {
var expectedObject = JSON.parse(failure.expected);
var actualObject = JSON.parse(failure.actual);
console.error(failure.source + ': Expected\n ' +
failure.expected.split('\n').join('\n ') +
'\nto match\n ' + failure.actual + '\nDiff:\n' +
diff(expectedObject, actualObject));
} catch (ex) {
console.error(failure.source + ': Expected\n ' +
failure.expected.split('\n').join('\n ') +
'\nto match\n ' + failure.actual);
}
});
} else {
console.log(header);
}
process.exit(failures.length === 0 ? 0 : 1);
}());
}

29995
node/node_modules/esprima/test/test.js generated vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,62 +1,270 @@
3.2.7 / 2015-02-19 # Changelog
------------------
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [3.14.0] - 2020-05-22
### Changed
- Support `safe/loadAll(input, options)` variant of call.
- CI: drop outdated nodejs versions.
- Dev deps bump.
### Fixed
- Quote `=` in plain scalars #519.
- Check the node type for `!<?>` tag in case user manually specifies it.
- Verify that there are no null-bytes in input.
- Fix wrong quote position when writing condensed flow, #526.
## [3.13.1] - 2019-04-05
### Security
- Fix possible code execution in (already unsafe) `.load()`, #480.
## [3.13.0] - 2019-03-20
### Security
- Security fix: `safeLoad()` can hang when arrays with nested refs
used as key. Now throws exception for nested arrays. #475.
## [3.12.2] - 2019-02-26
### Fixed
- Fix `noArrayIndent` option for root level, #468.
## [3.12.1] - 2019-01-05
### Added
- Added `noArrayIndent` option, #432.
## [3.12.0] - 2018-06-02
### Changed
- Support arrow functions without a block statement, #421.
## [3.11.0] - 2018-03-05
### Added
- Add arrow functions suport for `!!js/function`.
### Fixed
- Fix dump in bin/octal/hex formats for negative integers, #399.
## [3.10.0] - 2017-09-10
### Fixed
- 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
### Fixed
- Ensure stack is present for custom errors in node 7.+, #351.
## [3.9.0] - 2017-07-08
### Added
- Add `condenseFlow` option (to create pretty URL query params), #346.
### Fixed
- Support array return from safeLoadAll/loadAll, #350.
## [3.8.4] - 2017-05-08
### Fixed
- Dumper: prevent space after dash for arrays that wrap, #343.
## [3.8.3] - 2017-04-05
### Fixed
- Should not allow numbers to begin and end with underscore, #335.
## [3.8.2] - 2017-03-02
### Fixed
- 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
### Changed
- Maintenance: update browserified build.
## [3.8.0] - 2017-02-07
### Fixed
- 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
### Added
- Support polymorphism for tags (#300, thanks to @monken).
### Fixed
- Fix parsing of quotes followed by newlines (#304, thanks to @dplepage).
## [3.6.1] - 2016-05-11
### Fixed
- Fix output cut on a pipe, #286.
## [3.6.0] - 2016-04-16
### Fixed
- 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
### Fixed
- Date parse fix: don't allow dates with on digit in month and day, #268.
## [3.5.4] - 2016-03-09
### Added
- `noCompatMode` for dumper, to disable quoting YAML 1.1 values.
## [3.5.3] - 2016-02-11
### Changed
- Maintenance release.
## [3.5.2] - 2016-01-11
### Changed
- Maintenance: missed comma in bower config.
## [3.5.1] - 2016-01-11
### Changed
- Removed `inherit` dependency, #239.
- Better browserify workaround for esprima load.
- Demo rewrite.
## [3.5.0] - 2016-01-10
### Fixed
- 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
### Changed
- Use standalone `inherit` to keep browserified files clear.
## [3.4.5] - 2015-11-23
### Added
- Added `lineWidth` option to dumper.
## [3.4.4] - 2015-11-21
### Fixed
- Fixed floats dump (missed dot for scientific format), #220.
- Allow non-printable characters inside quoted scalars, #192.
## [3.4.3] - 2015-10-10
### Changed
- Maintenance release - deps bump (esprima, argparse).
## [3.4.2] - 2015-09-09
### Fixed
- Fixed serialization of duplicated entries in sequences, #205.
Thanks to @vogelsgesang.
## [3.4.1] - 2015-09-05
### Fixed
- Fixed stacktrace handling in generated errors, for browsers (FF/IE).
## [3.4.0] - 2015-08-23
### Changed
- Don't throw on warnings anymore. Use `onWarning` option to catch.
- Throw error on unknown tags (was warning before).
- Reworked internals of error class.
### Fixed
- Fixed multiline keys dump, #197. Thanks to @tcr.
- Fixed heading line breaks in some scalars (regression).
## [3.3.1] - 2015-05-13
### Added
- Added `.sortKeys` dumper option, thanks to @rjmunro.
### Fixed
- Fixed astral characters support, #191.
## [3.3.0] - 2015-04-26
### Changed
- Significantly improved long strings formatting in dumper, thanks to @isaacs.
- Strip BOM if exists.
## [3.2.7] - 2015-02-19
### Changed
- Maintenance release. - Maintenance release.
- Updated dependencies. - Updated dependencies.
- HISTORY.md -> CHANGELOG.md - HISTORY.md -> CHANGELOG.md
3.2.6 / 2015-02-07 ## [3.2.6] - 2015-02-07
------------------ ### Fixed
- Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE). - Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE).
- Fixed demo dates dump (#113, thanks to @Hypercubed). - Fixed demo dates dump (#113, thanks to @Hypercubed).
3.2.5 / 2014-12-28 ## [3.2.5] - 2014-12-28
------------------ ### Fixed
- Fixed resolving of all built-in types on empty nodes. - Fixed resolving of all built-in types on empty nodes.
- Fixed invalid warning on empty lines within quoted scalars and flow collections. - 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. - Fixed bug: Tag on an empty node didn't resolve in some cases.
3.2.4 / 2014-12-19 ## [3.2.4] - 2014-12-19
------------------ ### Fixed
- Fixed resolving of !!null tag on an empty node. - Fixed resolving of !!null tag on an empty node.
3.2.3 / 2014-11-08 ## [3.2.3] - 2014-11-08
------------------ ### Fixed
- Implemented dumping of objects with circular and cross references. - Implemented dumping of objects with circular and cross references.
- Partially fixed aliasing of constructed objects. (see issue #141 for details) - Partially fixed aliasing of constructed objects. (see issue #141 for details)
3.2.2 / 2014-09-07 ## [3.2.2] - 2014-09-07
------------------ ### Fixed
- Fixed infinite loop on unindented block scalars. - Fixed infinite loop on unindented block scalars.
- Rewritten base64 encode/decode in binary type, to keep code licence clear. - Rewritten base64 encode/decode in binary type, to keep code licence clear.
3.2.1 / 2014-08-24 ## [3.2.1] - 2014-08-24
------------------ ### Fixed
- Nothig new. Just fix npm publish error. - Nothig new. Just fix npm publish error.
3.2.0 / 2014-08-24 ## [3.2.0] - 2014-08-24
------------------ ### Added
- Added input piping support to CLI. - Added input piping support to CLI.
### Fixed
- Fixed typo, that could cause hand on initial indent (#139). - Fixed typo, that could cause hand on initial indent (#139).
3.1.0 / 2014-07-07 ## [3.1.0] - 2014-07-07
------------------ ### Changed
- 1.5x-2x speed boost. - 1.5x-2x speed boost.
- Removed deprecated `require('xxx.yml')` support. - Removed deprecated `require('xxx.yml')` support.
- Significant code cleanup and refactoring. - Significant code cleanup and refactoring.
@@ -69,127 +277,112 @@
- Bugfixes. - Bugfixes.
3.0.2 / 2014-02-27 ## [3.0.2] - 2014-02-27
------------------ ### Fixed
- Fixed bug: "constructor" string parsed as `null`. - Fixed bug: "constructor" string parsed as `null`.
3.0.1 / 2013-12-22 ## [3.0.1] - 2013-12-22
------------------ ### Fixed
- Fixed parsing of literal scalars. (issue #108) - Fixed parsing of literal scalars. (issue #108)
- Prevented adding unnecessary spaces in object dumps. (issue #68) - Prevented adding unnecessary spaces in object dumps. (issue #68)
- Fixed dumping of objects with very long (> 1024 in length) keys. - Fixed dumping of objects with very long (> 1024 in length) keys.
3.0.0 / 2013-12-16 ## [3.0.0] - 2013-12-16
------------------ ### Changed
- Refactored code. Changed API for custom types. - Refactored code. Changed API for custom types.
- Removed output colors in CLI, dump json by default. - Removed output colors in CLI, dump json by default.
- Removed big dependencies from browser version (esprima, buffer) - Removed big dependencies from browser version (esprima, buffer). Load `esprima` manually, if `!!js/function` needed. `!!bin` now returns Array in browser
- load `esprima` manually, if !!js/function needed
- !!bin now returns Array in browser
- AMD support. - AMD support.
- Don't quote dumped strings because of `-` & `?` (if not first char). - Don't quote dumped strings because of `-` & `?` (if not first char).
- __Deprecated__ loading yaml files via `require()`, as not recommended - __Deprecated__ loading yaml files via `require()`, as not recommended
behaviour for node. behaviour for node.
2.1.3 / 2013-10-16 ## [2.1.3] - 2013-10-16
------------------ ### Fixed
- Fix wrong loading of empty block scalars. - Fix wrong loading of empty block scalars.
2.1.2 / 2013-10-07 ## [2.1.2] - 2013-10-07
------------------ ### Fixed
- Fix unwanted line breaks in folded scalars. - Fix unwanted line breaks in folded scalars.
2.1.1 / 2013-10-02 ## [2.1.1] - 2013-10-02
------------------ ### Fixed
- Dumper now respects deprecated booleans syntax from YAML 1.0/1.1 - Dumper now respects deprecated booleans syntax from YAML 1.0/1.1
- Fixed reader bug in JSON-like sequences/mappings. - Fixed reader bug in JSON-like sequences/mappings.
2.1.0 / 2013-06-05 ## [2.1.0] - 2013-06-05
------------------ ### Added
- Add standard YAML schemas: Failsafe (`FAILSAFE_SCHEMA`), - Add standard YAML schemas: Failsafe (`FAILSAFE_SCHEMA`),
JSON (`JSON_SCHEMA`) and Core (`CORE_SCHEMA`). JSON (`JSON_SCHEMA`) and Core (`CORE_SCHEMA`).
- Add `skipInvalid` dumper option.
### Changed
- Rename `DEFAULT_SCHEMA` to `DEFAULT_FULL_SCHEMA` - Rename `DEFAULT_SCHEMA` to `DEFAULT_FULL_SCHEMA`
and `SAFE_SCHEMA` to `DEFAULT_SAFE_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. - Use `safeLoad` for `require` extension.
### Fixed
- Bug fix: export `NIL` constant from the public interface.
2.0.5 / 2013-04-26
------------------
## [2.0.5] - 2013-04-26
### Security
- Close security issue in !!js/function constructor. - Close security issue in !!js/function constructor.
Big thanks to @nealpoole for security audit. Big thanks to @nealpoole for security audit.
2.0.4 / 2013-04-08 ## [2.0.4] - 2013-04-08
------------------ ### Changed
- Updated .npmignore to reduce package size - Updated .npmignore to reduce package size
2.0.3 / 2013-02-26 ## [2.0.3] - 2013-02-26
------------------ ### Fixed
- Fixed dumping of empty arrays ans objects. ([] and {} instead of null) - Fixed dumping of empty arrays ans objects. ([] and {} instead of null)
2.0.2 / 2013-02-15 ## [2.0.2] - 2013-02-15
------------------ ### Fixed
- Fixed input validation: tabs are printable characters. - Fixed input validation: tabs are printable characters.
2.0.1 / 2013-02-09 ## [2.0.1] - 2013-02-09
------------------ ### Fixed
- Fixed error, when options not passed to function cass - Fixed error, when options not passed to function cass
2.0.0 / 2013-02-09 ## [2.0.0] - 2013-02-09
------------------ ### Changed
- Full rewrite. New architecture. Fast one-stage parsing. - Full rewrite. New architecture. Fast one-stage parsing.
- Changed custom types API. - Changed custom types API.
- Added YAML dumper. - Added YAML dumper.
1.0.3 / 2012-11-05 ## [1.0.3] - 2012-11-05
------------------ ### Fixed
- Fixed utf-8 files loading. - Fixed utf-8 files loading.
1.0.2 / 2012-08-02 ## [1.0.2] - 2012-08-02
------------------ ### Fixed
- Pull out hand-written shims. Use ES5-Shims for old browsers support. See #44. - 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. - Fix timstamps incorectly parsed in local time when no time part specified.
1.0.1 / 2012-07-07 ## [1.0.1] - 2012-07-07
------------------ ### Fixed
- Fixes `TypeError: 'undefined' is not an object` under Safari. Thanks Phuong. - Fixes `TypeError: 'undefined' is not an object` under Safari. Thanks Phuong.
- Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46. - Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46.
1.0.0 / 2012-07-01 ## [1.0.0] - 2012-07-01
------------------ ### Changed
- `y`, `yes`, `n`, `no`, `on`, `off` are not converted to Booleans anymore. - `y`, `yes`, `n`, `no`, `on`, `off` are not converted to Booleans anymore.
Fixes #42. Fixes #42.
- `require(filename)` now returns a single document and throws an Error if - `require(filename)` now returns a single document and throws an Error if
@@ -197,89 +390,162 @@
- CLI was merged back from js-yaml.bin - CLI was merged back from js-yaml.bin
0.3.7 / 2012-02-28 ## [0.3.7] - 2012-02-28
------------------ ### Fixed
- Fix export of `addConstructor()`. Closes #39. - Fix export of `addConstructor()`. Closes #39.
0.3.6 / 2012-02-22 ## [0.3.6] - 2012-02-22
------------------ ### Changed
- Removed AMD parts - too buggy to use. Need help to rewrite from scratch - Removed AMD parts - too buggy to use. Need help to rewrite from scratch
### Fixed
- Removed YUI compressor warning (renamed `double` variable). Closes #40. - Removed YUI compressor warning (renamed `double` variable). Closes #40.
0.3.5 / 2012-01-10 ## [0.3.5] - 2012-01-10
------------------ ### Fixed
- Workagound for .npmignore fuckup under windows. Thanks to airportyh. - Workagound for .npmignore fuckup under windows. Thanks to airportyh.
0.3.4 / 2011-12-24 ## [0.3.4] - 2011-12-24
------------------ ### Fixed
- Fixes str[] for oldIEs support. - Fixes str[] for oldIEs support.
- Adds better has change support for browserified demo. - Adds better has change support for browserified demo.
- improves compact output of Error. Closes #33. - improves compact output of Error. Closes #33.
0.3.3 / 2011-12-20 ## [0.3.3] - 2011-12-20
------------------ ### Added
- jsyaml executable moved to separate module.
- adds `compact` stringification of Errors. - adds `compact` stringification of Errors.
### Changed
- jsyaml executable moved to separate module.
0.3.2 / 2011-12-16
------------------
## [0.3.2] - 2011-12-16
### Added
- Added jsyaml executable.
- Added !!js/function support. Closes #12.
### Fixed
- Fixes ug with block style scalars. Closes #26. - Fixes ug with block style scalars. Closes #26.
- All sources are passing JSLint now. - All sources are passing JSLint now.
- Fixes bug in Safari. Closes #28. - Fixes bug in Safari. Closes #28.
- Fixes bug in Opers. Closes #29. - Fixes bug in Opers. Closes #29.
- Improves browser support. Closes #20. - Improves browser support. Closes #20.
- Added jsyaml executable.
- Added !!js/function support. Closes #12.
0.3.1 / 2011-11-18 ## [0.3.1] - 2011-11-18
------------------ ### Added
- Added AMD support for browserified version. - 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 permalinks for online demo YAML snippets. Now we have YPaste service, lol.
- Added !!js/regexp and !!js/undefined types. Partially solves #12. - Added !!js/regexp and !!js/undefined types. Partially solves #12.
### Changed
- Wrapped browserified js-yaml into closure.
### Fixed
- Fixed the resolvement of non-specific tags. Closes #17.
- Fixed !!set mapping. - Fixed !!set mapping.
- Fixed month parse in dates. Closes #19. - Fixed month parse in dates. Closes #19.
0.3.0 / 2011-11-09 ## [0.3.0] - 2011-11-09
------------------ ### Added
- Removed JS.Class dependency. Closes #3.
- Added browserified version. Closes #13. - Added browserified version. Closes #13.
- Added live demo of browserified version. - Added live demo of browserified version.
- Ported some of the PyYAML tests. See #14. - Ported some of the PyYAML tests. See #14.
### Fixed
- Removed JS.Class dependency. Closes #3.
- Fixed timestamp bug when fraction was given. - Fixed timestamp bug when fraction was given.
0.2.2 / 2011-11-06 ## [0.2.2] - 2011-11-06
------------------ ### Fixed
- Fixed crash on docs without ---. Closes #8. - Fixed crash on docs without ---. Closes #8.
- Fixed miltiline string parse - Fixed multiline string parse
- Fixed tests/comments for using array as key - Fixed tests/comments for using array as key
0.2.1 / 2011-11-02 ## [0.2.1] - 2011-11-02
------------------ ### Fixed
- Fixed short file read (<4k). Closes #9. - Fixed short file read (<4k). Closes #9.
0.2.0 / 2011-11-02 ## [0.2.0] - 2011-11-02
------------------ ### Changed
- First public release - First public release
[3.14.0]: https://github.com/nodeca/js-yaml/compare/3.13.1...3.14.0
[3.13.1]: https://github.com/nodeca/js-yaml/compare/3.13.0...3.13.1
[3.13.0]: https://github.com/nodeca/js-yaml/compare/3.12.2...3.13.0
[3.12.2]: https://github.com/nodeca/js-yaml/compare/3.12.1...3.12.2
[3.12.1]: https://github.com/nodeca/js-yaml/compare/3.12.0...3.12.1
[3.12.0]: https://github.com/nodeca/js-yaml/compare/3.11.0...3.12.0
[3.11.0]: https://github.com/nodeca/js-yaml/compare/3.10.0...3.11.0
[3.10.0]: https://github.com/nodeca/js-yaml/compare/3.9.1...3.10.0
[3.9.1]: https://github.com/nodeca/js-yaml/compare/3.9.0...3.9.1
[3.9.0]: https://github.com/nodeca/js-yaml/compare/3.8.4...3.9.0
[3.8.4]: https://github.com/nodeca/js-yaml/compare/3.8.3...3.8.4
[3.8.3]: https://github.com/nodeca/js-yaml/compare/3.8.2...3.8.3
[3.8.2]: https://github.com/nodeca/js-yaml/compare/3.8.1...3.8.2
[3.8.1]: https://github.com/nodeca/js-yaml/compare/3.8.0...3.8.1
[3.8.0]: https://github.com/nodeca/js-yaml/compare/3.7.0...3.8.0
[3.7.0]: https://github.com/nodeca/js-yaml/compare/3.6.1...3.7.0
[3.6.1]: https://github.com/nodeca/js-yaml/compare/3.6.0...3.6.1
[3.6.0]: https://github.com/nodeca/js-yaml/compare/3.5.5...3.6.0
[3.5.5]: https://github.com/nodeca/js-yaml/compare/3.5.4...3.5.5
[3.5.4]: https://github.com/nodeca/js-yaml/compare/3.5.3...3.5.4
[3.5.3]: https://github.com/nodeca/js-yaml/compare/3.5.2...3.5.3
[3.5.2]: https://github.com/nodeca/js-yaml/compare/3.5.1...3.5.2
[3.5.1]: https://github.com/nodeca/js-yaml/compare/3.5.0...3.5.1
[3.5.0]: https://github.com/nodeca/js-yaml/compare/3.4.6...3.5.0
[3.4.6]: https://github.com/nodeca/js-yaml/compare/3.4.5...3.4.6
[3.4.5]: https://github.com/nodeca/js-yaml/compare/3.4.4...3.4.5
[3.4.4]: https://github.com/nodeca/js-yaml/compare/3.4.3...3.4.4
[3.4.3]: https://github.com/nodeca/js-yaml/compare/3.4.2...3.4.3
[3.4.2]: https://github.com/nodeca/js-yaml/compare/3.4.1...3.4.2
[3.4.1]: https://github.com/nodeca/js-yaml/compare/3.4.0...3.4.1
[3.4.0]: https://github.com/nodeca/js-yaml/compare/3.3.1...3.4.0
[3.3.1]: https://github.com/nodeca/js-yaml/compare/3.3.0...3.3.1
[3.3.0]: https://github.com/nodeca/js-yaml/compare/3.2.7...3.3.0
[3.2.7]: https://github.com/nodeca/js-yaml/compare/3.2.6...3.2.7
[3.2.6]: https://github.com/nodeca/js-yaml/compare/3.2.5...3.2.6
[3.2.5]: https://github.com/nodeca/js-yaml/compare/3.2.4...3.2.5
[3.2.4]: https://github.com/nodeca/js-yaml/compare/3.2.3...3.2.4
[3.2.3]: https://github.com/nodeca/js-yaml/compare/3.2.2...3.2.3
[3.2.2]: https://github.com/nodeca/js-yaml/compare/3.2.1...3.2.2
[3.2.1]: https://github.com/nodeca/js-yaml/compare/3.2.0...3.2.1
[3.2.0]: https://github.com/nodeca/js-yaml/compare/3.1.0...3.2.0
[3.1.0]: https://github.com/nodeca/js-yaml/compare/3.0.2...3.1.0
[3.0.2]: https://github.com/nodeca/js-yaml/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/nodeca/js-yaml/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/nodeca/js-yaml/compare/2.1.3...3.0.0
[2.1.3]: https://github.com/nodeca/js-yaml/compare/2.1.2...2.1.3
[2.1.2]: https://github.com/nodeca/js-yaml/compare/2.1.1...2.1.2
[2.1.1]: https://github.com/nodeca/js-yaml/compare/2.1.0...2.1.1
[2.1.0]: https://github.com/nodeca/js-yaml/compare/2.0.5...2.1.0
[2.0.5]: https://github.com/nodeca/js-yaml/compare/2.0.4...2.0.5
[2.0.4]: https://github.com/nodeca/js-yaml/compare/2.0.3...2.0.4
[2.0.3]: https://github.com/nodeca/js-yaml/compare/2.0.2...2.0.3
[2.0.2]: https://github.com/nodeca/js-yaml/compare/2.0.1...2.0.2
[2.0.1]: https://github.com/nodeca/js-yaml/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/nodeca/js-yaml/compare/1.0.3...2.0.0
[1.0.3]: https://github.com/nodeca/js-yaml/compare/1.0.2...1.0.3
[1.0.2]: https://github.com/nodeca/js-yaml/compare/1.0.1...1.0.2
[1.0.1]: https://github.com/nodeca/js-yaml/compare/1.0.0...1.0.1
[1.0.0]: https://github.com/nodeca/js-yaml/compare/0.3.7...1.0.0
[0.3.7]: https://github.com/nodeca/js-yaml/compare/0.3.6...0.3.7
[0.3.6]: https://github.com/nodeca/js-yaml/compare/0.3.5...0.3.6
[0.3.5]: https://github.com/nodeca/js-yaml/compare/0.3.4...0.3.5
[0.3.4]: https://github.com/nodeca/js-yaml/compare/0.3.3...0.3.4
[0.3.3]: https://github.com/nodeca/js-yaml/compare/0.3.2...0.3.3
[0.3.2]: https://github.com/nodeca/js-yaml/compare/0.3.1...0.3.2
[0.3.1]: https://github.com/nodeca/js-yaml/compare/0.3.0...0.3.1
[0.3.0]: https://github.com/nodeca/js-yaml/compare/0.2.2...0.3.0
[0.2.2]: https://github.com/nodeca/js-yaml/compare/0.2.1...0.2.2
[0.2.1]: https://github.com/nodeca/js-yaml/compare/0.2.0...0.2.1
[0.2.0]: https://github.com/nodeca/js-yaml/releases/tag/0.2.0

129
node/node_modules/js-yaml/README.md generated vendored
View File

@@ -1,13 +1,13 @@
JS-YAML - YAML 1.2 parser and serializer for JavaScript 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) [![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) [![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/) __[Online Demo](http://nodeca.github.com/js-yaml/)__
This is an implementation of [YAML](http://yaml.org/), a human friendly data This is an implementation of [YAML](http://yaml.org/), a human-friendly data
serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was 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. completely rewritten from scratch. Now it's very fast, and supports 1.2 spec.
@@ -57,13 +57,13 @@ var doc = jsyaml.load('greeting: hello\nname: world');
</script> </script>
``` ```
Browser support was done mostly for online demo. If you find any errors - feel 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 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. needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate.
Notes: Notes:
1. We have no resourses to support browserified version. Don't expect it to be 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. 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 2. `!!js/function` in browser bundle will not work by default. If you really need
it - load `esprima` parser first (via amd or directly). it - load `esprima` parser first (via amd or directly).
@@ -80,12 +80,12 @@ your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and
info. info.
``` javascript ``` javascript
yaml = require('js-yaml'); const yaml = require('js-yaml');
fs = require('fs'); const fs = require('fs');
// Get document, or throw exception on error // Get document, or throw exception on error
try { try {
var doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
console.log(doc); console.log(doc);
} catch (e) { } catch (e) {
console.log(e); console.log(e);
@@ -95,16 +95,16 @@ try {
### safeLoad (string [ , options ]) ### safeLoad (string [ , options ])
**Recommended loading way.** Parses `string` as single YAML document. Returns a JavaScript **Recommended loading way.** Parses `string` as single YAML document. Returns either a
object or throws `YAMLException` on error. By default, does not support regexps, plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does
functions and undefined. This method is safe for untrusted data. not support regexps, functions and undefined. This method is safe for untrusted data.
options: options:
- `filename` _(default: null)_ - string to be used as a file path in - `filename` _(default: null)_ - string to be used as a file path in
error/warning messages. error/warning messages.
- `onWarning` _(default: null)_ - function to call on warning messages. - `onWarning` _(default: null)_ - function to call on warning messages.
Loader will throw on warnings if this function is not provided. Loader will call this function with an instance of `YAMLException` for each warning.
- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use.
- `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects:
http://www.yaml.org/spec/1.2/spec.html#id2802346 http://www.yaml.org/spec/1.2/spec.html#id2802346
@@ -116,38 +116,39 @@ options:
(`!!js/undefined`, `!!js/regexp` and `!!js/function`): (`!!js/undefined`, `!!js/regexp` and `!!js/function`):
http://yaml.org/type/ http://yaml.org/type/
- `DEFAULT_FULL_SCHEMA` - all supported YAML types. - `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 NOTE: This function **does not** understand multi-document sources, it throws
exception on those. exception on those.
NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions.
So, JSON schema is not as strict as defined in the YAML specification. So, the JSON schema is not as strictly defined in the YAML specification.
It allows numbers in any notaion, use `Null` and `NULL` as `null`, etc. It allows numbers in any notation, use `Null` and `NULL` as `null`, etc.
Core schema also has no such restrictions. It allows binary notation for integers. The core schema also has no such restrictions. It allows binary notation for integers.
### load (string [ , options ]) ### load (string [ , options ])
**Use with care with untrusted sources**. The same as `safeLoad()` but uses **Use with care with untrusted sources**. The same as `safeLoad()` but uses
`DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: `DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types:
`!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources you `!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you
must additionally validate object structure, to avoid injections: must additionally validate object structure to avoid injections:
``` javascript ``` javascript
var untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"'; const untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"';
// I'm just converting that string, what could possibly go wrong? // I'm just converting that string, what could possibly go wrong?
require('js-yaml').load(untrusted_code) + '' require('js-yaml').load(untrusted_code) + ''
``` ```
### safeLoadAll (string, iterator [ , options ]) ### safeLoadAll (string [, iterator] [, options ])
Same as `safeLoad()`, but understands multi-document sources and apply Same as `safeLoad()`, but understands multi-document sources. Applies
`iterator` to each document. `iterator` to each document if specified, or returns array of documents.
``` javascript ``` javascript
var yaml = require('js-yaml'); const yaml = require('js-yaml');
yaml.safeLoadAll(data, function (doc) { yaml.safeLoadAll(data, function (doc) {
console.log(doc); console.log(doc);
@@ -155,48 +156,73 @@ yaml.safeLoadAll(data, function (doc) {
``` ```
### loadAll (string, iterator [ , options ]) ### loadAll (string [, iterator] [ , options ])
Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default.
### safeDump (object [ , options ]) ### safeDump (object [ , options ])
Serializes `object` as YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will
throw exception if you try to dump regexps or functions. However, you can throw an exception if you try to dump regexps or functions. However, you can
disable exceptions by `skipInvalid` option. disable exceptions by setting the `skipInvalid` option to `true`.
options: options:
- `indent` _(default: 2)_ - indentation width to use (in spaces). - `indent` _(default: 2)_ - indentation width to use (in spaces).
- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements
- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function
in the safe schema) and skip pairs and single values with such types. in the safe schema) and skip pairs and single values with such types.
- `flowLevel` (default: -1) - specifies level of nesting, when to switch from - `flowLevel` (default: -1) - specifies level of nesting, when to switch from
block to flow style for collections. -1 means block style everwhere block to flow style for collections. -1 means block style everwhere
- `styles` - "tag" => "style" map. Each tag may have own set of styles. - `styles` - "tag" => "style" map. Each tag may have own set of styles.
- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. - `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.
styles: The following table show availlable styles (e.g. "canonical",
"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml
output is shown on the right side after `=>` (default setting) or `->`:
``` none ``` none
!!null !!null
"canonical" => "~" "canonical" -> "~"
"lowercase" => "null"
"uppercase" -> "NULL"
"camelcase" -> "Null"
!!int !!int
"binary" => "0b1", "0b101010", "0b1110001111010" "binary" -> "0b1", "0b101010", "0b1110001111010"
"octal" => "01", "052", "016172" "octal" -> "01", "052", "016172"
"decimal" => "1", "42", "7290" "decimal" => "1", "42", "7290"
"hexadecimal" => "0x1", "0x2A", "0x1C7A" "hexadecimal" -> "0x1", "0x2A", "0x1C7A"
!!null, !!bool, !!float !!bool
"lowercase" => "null", "true", "false", ".nan", '.inf' "lowercase" => "true", "false"
"uppercase" => "NULL", "TRUE", "FALSE", ".NAN", '.INF' "uppercase" -> "TRUE", "FALSE"
"camelcase" => "Null", "True", "False", ".NaN", '.Inf' "camelcase" -> "True", "False"
!!float
"lowercase" => ".nan", '.inf'
"uppercase" -> ".NAN", '.INF'
"camelcase" -> ".NaN", '.Inf'
``` ```
By default, !!int uses `decimal`, and !!null, !!bool, !!float use `lowercase`. Example:
``` javascript
safeDump (object, {
'styles': {
'!!null': 'canonical' // dump null as ~
},
'sortKeys': true // sort object keys
});
```
### dump (object [ , options ]) ### dump (object [ , options ])
@@ -236,8 +262,8 @@ The list of standard YAML tags and corresponding JavaScipt types. See also
Caveats Caveats
------- -------
Note, that you use arrays or objects as key in JS-YAML. JS do not allows objects Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects
or array as keys, and stringifies (by calling .toString method) them at the or arrays as keys, and stringifies (by calling `toString()` method) them at the
moment of adding them. moment of adding them.
``` yaml ``` yaml
@@ -265,24 +291,9 @@ So, the following YAML document cannot be loaded.
``` ```
Breaking changes in 2.x.x -> 3.x.x js-yaml for enterprise
---------------------------------- ----------------------
If your have not used __custom__ tags or loader classes and not loaded yaml Available as part of the Tidelift Subscription
files via `require()` - no changes needed. Just upgrade library.
In other case, you should: The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
1. Replace all occurences of `require('xxxx.yml')` by `fs.readFileSync()` +
`yaml.safeLoad()`.
2. rewrite your custom tags constructors and custom loader
classes, to conform 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

@@ -3,6 +3,8 @@
'use strict'; 'use strict';
/*eslint-disable no-console*/
// stdlib // stdlib
var fs = require('fs'); var fs = require('fs');
@@ -26,7 +28,7 @@ var cli = new argparse.ArgumentParser({
}); });
cli.addArgument(['-c', '--compact'], { cli.addArgument([ '-c', '--compact' ], {
help: 'Display errors in compact mode', help: 'Display errors in compact mode',
action: 'storeTrue' action: 'storeTrue'
}); });
@@ -34,19 +36,19 @@ cli.addArgument(['-c', '--compact'], {
// deprecated (not needed after we removed output colors) // deprecated (not needed after we removed output colors)
// option suppressed, but not completely removed for compatibility // option suppressed, but not completely removed for compatibility
cli.addArgument(['-j', '--to-json'], { cli.addArgument([ '-j', '--to-json' ], {
help: argparse.Const.SUPPRESS, help: argparse.Const.SUPPRESS,
dest: 'json', dest: 'json',
action: 'storeTrue' action: 'storeTrue'
}); });
cli.addArgument(['-t', '--trace'], { cli.addArgument([ '-t', '--trace' ], {
help: 'Show stack trace on error', help: 'Show stack trace on error',
action: 'storeTrue' action: 'storeTrue'
}); });
cli.addArgument(['file'], { cli.addArgument([ 'file' ], {
help: 'File to read, utf-8 encoded without BOM', help: 'File to read, utf-8 encoded without BOM',
nargs: '?', nargs: '?',
defaultValue: '-' defaultValue: '-'
@@ -67,11 +69,11 @@ function readFile(filename, encoding, callback) {
var chunks = []; var chunks = [];
process.stdin.on('data', function(chunk) { process.stdin.on('data', function (chunk) {
chunks.push(chunk); chunks.push(chunk);
}); });
process.stdin.on('end', function() { process.stdin.on('end', function () {
return callback(null, Buffer.concat(chunks).toString(encoding)); return callback(null, Buffer.concat(chunks).toString(encoding));
}); });
} else { } else {
@@ -83,7 +85,7 @@ readFile(options.file, 'utf8', function (error, input) {
var output, isYaml; var output, isYaml;
if (error) { if (error) {
if ('ENOENT' === error.code) { if (error.code === 'ENOENT') {
console.error('File not found: ' + options.file); console.error('File not found: ' + options.file);
process.exit(2); process.exit(2);
} }
@@ -99,42 +101,32 @@ readFile(options.file, 'utf8', function (error, input) {
try { try {
output = JSON.parse(input); output = JSON.parse(input);
isYaml = false; isYaml = false;
} catch (error) { } catch (err) {
if (error instanceof SyntaxError) { if (err instanceof SyntaxError) {
try { try {
output = []; output = [];
yaml.loadAll(input, function (doc) { output.push(doc); }, {}); yaml.loadAll(input, function (doc) { output.push(doc); }, {});
isYaml = true; isYaml = true;
if (0 === output.length) { if (output.length === 0) output = null;
output = null; else if (output.length === 1) output = output[0];
} else if (1 === output.length) {
output = output[0]; } catch (e) {
} if (options.trace && err.stack) console.error(e.stack);
} catch (error) { else console.error(e.toString(options.compact));
if (options.trace && error.stack) {
console.error(error.stack);
} else {
console.error(error.toString(options.compact));
}
process.exit(1); process.exit(1);
} }
} else { } else {
console.error( console.error(
options.trace && error.stack || options.trace && err.stack ||
error.message || err.message ||
String(error)); String(err));
process.exit(1); process.exit(1);
} }
} }
if (isYaml) { if (isYaml) console.log(JSON.stringify(output, null, ' '));
console.log(JSON.stringify(output, null, ' ')); else console.log(yaml.dump(output));
} else {
console.log(yaml.dump(output));
}
process.exit(0);
}); });

23
node/node_modules/js-yaml/bower.json generated vendored
View File

@@ -1,23 +0,0 @@
{
"name": "js-yaml",
"main": "dist/js-yaml.js",
"homepage": "https://github.com/nodeca/js-yaml",
"authors": [ "Dervus Grim <dervus.grim@gmail.com>",
"Vitaly Puzrin <vitaly@rcdesign.ru>",
"Aleksey V Zapparov <ixti@member.fsf.org>",
"Martin Grenfell <martin.grenfell@gmail.com>" ],
"description": "YAML 1.2 parser and serializer",
"keywords": ["yaml", "parser", "serializer", "pyyaml"],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"benchmark",
"bower_components",
"test",
"Makefile",
"index*",
"package.json"
]
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -1,102 +0,0 @@
'use strict';
var fs = require('fs');
var path = require('path');
var util = require('util');
var yaml = require('../lib/js-yaml');
// Let's define a couple of classes.
function Point(x, y, z) {
this.klass = 'Point';
this.x = x;
this.y = y;
this.z = z;
}
function Space(height, width, points) {
if (points) {
if (!points.every(function (point) { return point instanceof Point; })) {
throw new Error('A non-Point inside a points array!');
}
}
this.klass = 'Space';
this.height = height;
this.width = width;
this.points = points;
}
// Then define YAML types to load and dump our Point/Space objects.
var PointYamlType = new yaml.Type('!point', {
// Loader must parse sequence nodes only for this type (i.e. arrays in JS terminology).
// Other available kinds are 'scalar' (string) and 'mapping' (object).
// http://www.yaml.org/spec/1.2/spec.html#kind//
kind: 'sequence',
// Loader must check if the input object is suitable for this type.
resolve: function (data) {
// `data` may be either:
// - Null in case of an "empty node" (http://www.yaml.org/spec/1.2/spec.html#id2786563)
// - Array since we specified `kind` to 'sequence'
return data !== null && data.length === 3;
},
// If a node is resolved, use it to create a Point instance.
construct: function (data) {
return new Point(data[0], data[1], data[2]);
},
// Dumper must process instances of Point by rules of this YAML type.
instanceOf: Point,
// Dumper must represent Point objects as three-element sequence in YAML.
represent: function (point) {
return [ point.x, point.y, point.z ];
}
});
var SpaceYamlType = new yaml.Type('!space', {
kind: 'mapping',
construct: function (data) {
data = data || {}; // in case of empty node
return new Space(data.height || 0, data.width || 0, data.points || []);
},
instanceOf: Space
// `represent` is omitted here. So, Space objects will be dumped as is.
// That is regular mapping with three key-value pairs but with !space tag.
});
// After our types are defined, it's time to join them into a schema.
var SPACE_SCHEMA = yaml.Schema.create([ SpaceYamlType, PointYamlType ]);
// And read a document using that schema.
fs.readFile(path.join(__dirname, 'custom_types.yml'), 'utf8', function (error, data) {
var loaded;
if (!error) {
loaded = yaml.load(data, { schema: SPACE_SCHEMA });
console.log(util.inspect(loaded, false, 20, true));
} else {
console.error(error.stack || error.message || String(error));
}
});
// There are some exports to play with this example interactively.
module.exports.Point = Point;
module.exports.Space = Space;
module.exports.PointYamlType = PointYamlType;
module.exports.SpaceYamlType = SpaceYamlType;
module.exports.SPACE_SCHEMA = SPACE_SCHEMA;

View File

@@ -1,18 +0,0 @@
subject: Custom types in JS-YAML
spaces:
- !space
height: 1000
width: 1000
points:
- !point [ 10, 43, 23 ]
- !point [ 165, 0, 50 ]
- !point [ 100, 100, 100 ]
- !space
height: 64
width: 128
points:
- !point [ 12, 43, 0 ]
- !point [ 1, 4, 90 ]
- !space # An empty space

View File

@@ -1,31 +0,0 @@
'use strict';
var yaml = require('../lib/js-yaml');
var object = require('./dumper.json');
console.log(yaml.dump(object, {
flowLevel: 3,
styles: {
'!!int' : 'hexadecimal',
'!!null' : 'camelcase'
}
}));
// Output:
//==============================================================================
// name: Wizzard
// level: 0x11
// sanity: Null
// inventory:
// - name: Hat
// features: [magic, pointed]
// traits: {}
// - name: Staff
// features: []
// traits: {damage: 0xA}
// - name: Cloak
// features: [old]
// traits: {defence: 0x0, comfort: 0x3}

View File

@@ -1,22 +0,0 @@
{
"name" : "Wizzard",
"level" : 17,
"sanity" : null,
"inventory" : [
{
"name" : "Hat",
"features" : [ "magic", "pointed" ],
"traits" : {}
},
{
"name" : "Staff",
"features" : [],
"traits" : { "damage" : 10 }
},
{
"name" : "Cloak",
"features" : [ "old" ],
"traits" : { "defence" : 0, "comfort" : 3 }
}
]
}

View File

@@ -1,18 +0,0 @@
'use strict';
var fs = require('fs');
var path = require('path');
var util = require('util');
var yaml = require('../lib/js-yaml');
try {
var filename = path.join(__dirname, 'sample_document.yml'),
contents = fs.readFileSync(filename, 'utf8'),
data = yaml.load(contents);
console.log(util.inspect(data, false, 10, true));
} catch (err) {
console.log(err.stack || String(err));
}

View File

@@ -1,197 +0,0 @@
---
# Collection Types #############################################################
################################################################################
# http://yaml.org/type/map.html -----------------------------------------------#
map:
# Unordered set of key: value pairs.
Block style: !!map
Clark : Evans
Ingy : döt Net
Oren : Ben-Kiki
Flow style: !!map { Clark: Evans, Ingy: döt Net, Oren: Ben-Kiki }
# http://yaml.org/type/omap.html ----------------------------------------------#
omap:
# Explicitly typed ordered map (dictionary).
Bestiary: !!omap
- aardvark: African pig-like ant eater. Ugly.
- anteater: South-American ant eater. Two species.
- anaconda: South-American constrictor snake. Scaly.
# Etc.
# Flow style
Numbers: !!omap [ one: 1, two: 2, three : 3 ]
# http://yaml.org/type/pairs.html ---------------------------------------------#
pairs:
# Explicitly typed pairs.
Block tasks: !!pairs
- meeting: with team.
- meeting: with boss.
- break: lunch.
- meeting: with client.
Flow tasks: !!pairs [ meeting: with team, meeting: with boss ]
# http://yaml.org/type/set.html -----------------------------------------------#
set:
# Explicitly typed set.
baseball players: !!set
? Mark McGwire
? Sammy Sosa
? Ken Griffey
# Flow style
baseball teams: !!set { Boston Red Sox, Detroit Tigers, New York Yankees }
# http://yaml.org/type/seq.html -----------------------------------------------#
seq:
# Ordered sequence of nodes
Block style: !!seq
- Mercury # Rotates - no light/dark sides.
- Venus # Deadliest. Aptly named.
- Earth # Mostly dirt.
- Mars # Seems empty.
- Jupiter # The king.
- Saturn # Pretty.
- Uranus # Where the sun hardly shines.
- Neptune # Boring. No rings.
- Pluto # You call this a planet?
Flow style: !!seq [ Mercury, Venus, Earth, Mars, # Rocks
Jupiter, Saturn, Uranus, Neptune, # Gas
Pluto ] # Overrated
# Scalar Types #################################################################
################################################################################
# http://yaml.org/type/binary.html --------------------------------------------#
binary:
canonical: !!binary "\
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5\
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+\
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC\
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs="
generic: !!binary |
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
description:
The binary value above is a tiny arrow encoded as a gif image.
# http://yaml.org/type/bool.html ----------------------------------------------#
bool:
- true
- True
- TRUE
- false
- False
- FALSE
# http://yaml.org/type/float.html ---------------------------------------------#
float:
canonical: 6.8523015e+5
exponentioal: 685.230_15e+03
fixed: 685_230.15
sexagesimal: 190:20:30.15
negative infinity: -.inf
not a number: .NaN
# http://yaml.org/type/int.html -----------------------------------------------#
int:
canonical: 685230
decimal: +685_230
octal: 02472256
hexadecimal: 0x_0A_74_AE
binary: 0b1010_0111_0100_1010_1110
sexagesimal: 190:20:30
# http://yaml.org/type/merge.html ---------------------------------------------#
merge:
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }
# All the following maps are equal:
- # Explicit keys
x: 1
y: 2
r: 10
label: nothing
- # Merge one map
<< : *CENTER
r: 10
label: center
- # Merge multiple maps
<< : [ *CENTER, *BIG ]
label: center/big
- # Override
<< : [ *BIG, *LEFT, *SMALL ]
x: 1
label: big/left/small
# http://yaml.org/type/null.html ----------------------------------------------#
null:
# This mapping has four keys,
# one has a value.
empty:
canonical: ~
english: null
~: null key
# This sequence has five
# entries, two have values.
sparse:
- ~
- 2nd entry
-
- 4th entry
- Null
# http://yaml.org/type/str.html -----------------------------------------------#
string: abcd
# http://yaml.org/type/timestamp.html -----------------------------------------#
timestamp:
canonical: 2001-12-15T02:59:43.1Z
valid iso8601: 2001-12-14t21:59:43.10-05:00
space separated: 2001-12-14 21:59:43.10 -5
no time zone (Z): 2001-12-15 2:59:43.10
date (00:00:00Z): 2002-12-14
# JavaScript Specific Types ####################################################
################################################################################
# https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
regexp:
simple: !!js/regexp foobar
modifiers: !!js/regexp /foobar/mi
# https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined
undefined: !!js/undefined ~
# https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function
function: !!js/function >
function foobar() {
return 'Wow! JS-YAML Rocks!';
}

View File

@@ -27,7 +27,7 @@ module.exports.dump = dumper.dump;
module.exports.safeDump = dumper.safeDump; module.exports.safeDump = dumper.safeDump;
module.exports.YAMLException = require('./js-yaml/exception'); module.exports.YAMLException = require('./js-yaml/exception');
// Deprecared schema names from JS-YAML 2.0.x // Deprecated schema names from JS-YAML 2.0.x
module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe'); module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe'); module.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full'); module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');

View File

@@ -2,23 +2,20 @@
function isNothing(subject) { function isNothing(subject) {
return (undefined === subject) || (null === subject); return (typeof subject === 'undefined') || (subject === null);
} }
function isObject(subject) { function isObject(subject) {
return ('object' === typeof subject) && (null !== subject); return (typeof subject === 'object') && (subject !== null);
} }
function toArray(sequence) { function toArray(sequence) {
if (Array.isArray(sequence)) { if (Array.isArray(sequence)) return sequence;
return sequence; else if (isNothing(sequence)) return [];
} else if (isNothing(sequence)) {
return [];
} else {
return [ sequence ]; return [ sequence ];
}
} }
@@ -50,7 +47,7 @@ function repeat(string, count) {
function isNegativeZero(number) { function isNegativeZero(number) {
return (0 === number) && (Number.NEGATIVE_INFINITY === 1 / number); return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
} }

View File

@@ -1,16 +1,15 @@
'use strict'; 'use strict';
/*eslint-disable no-use-before-define*/
var common = require('./common'); var common = require('./common');
var YAMLException = require('./exception'); var YAMLException = require('./exception');
var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
var _toString = Object.prototype.toString; var _toString = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty; var _hasOwnProperty = Object.prototype.hasOwnProperty;
var CHAR_TAB = 0x09; /* Tab */ var CHAR_TAB = 0x09; /* Tab */
var CHAR_LINE_FEED = 0x0A; /* LF */ var CHAR_LINE_FEED = 0x0A; /* LF */
var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
@@ -25,6 +24,7 @@ var CHAR_ASTERISK = 0x2A; /* * */
var CHAR_COMMA = 0x2C; /* , */ var CHAR_COMMA = 0x2C; /* , */
var CHAR_MINUS = 0x2D; /* - */ var CHAR_MINUS = 0x2D; /* - */
var CHAR_COLON = 0x3A; /* : */ var CHAR_COLON = 0x3A; /* : */
var CHAR_EQUALS = 0x3D; /* = */
var CHAR_GREATER_THAN = 0x3E; /* > */ var CHAR_GREATER_THAN = 0x3E; /* > */
var CHAR_QUESTION = 0x3F; /* ? */ var CHAR_QUESTION = 0x3F; /* ? */
var CHAR_COMMERCIAL_AT = 0x40; /* @ */ var CHAR_COMMERCIAL_AT = 0x40; /* @ */
@@ -35,7 +35,6 @@ var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
var CHAR_VERTICAL_LINE = 0x7C; /* | */ var CHAR_VERTICAL_LINE = 0x7C; /* | */
var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
var ESCAPE_SEQUENCES = {}; var ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0x00] = '\\0'; ESCAPE_SEQUENCES[0x00] = '\\0';
@@ -54,19 +53,15 @@ ESCAPE_SEQUENCES[0xA0] = '\\_';
ESCAPE_SEQUENCES[0x2028] = '\\L'; ESCAPE_SEQUENCES[0x2028] = '\\L';
ESCAPE_SEQUENCES[0x2029] = '\\P'; ESCAPE_SEQUENCES[0x2029] = '\\P';
var DEPRECATED_BOOLEANS_SYNTAX = [ var DEPRECATED_BOOLEANS_SYNTAX = [
'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
]; ];
function compileStyleMap(schema, map) { function compileStyleMap(schema, map) {
var result, keys, index, length, tag, style, type; var result, keys, index, length, tag, style, type;
if (null === map) { if (map === null) return {};
return {};
}
result = {}; result = {};
keys = Object.keys(map); keys = Object.keys(map);
@@ -75,11 +70,10 @@ function compileStyleMap(schema, map) {
tag = keys[index]; tag = keys[index];
style = String(map[tag]); style = String(map[tag]);
if ('!!' === tag.slice(0, 2)) { if (tag.slice(0, 2) === '!!') {
tag = 'tag:yaml.org,2002:' + tag.slice(2); tag = 'tag:yaml.org,2002:' + tag.slice(2);
} }
type = schema.compiledTypeMap['fallback'][tag];
type = schema.compiledTypeMap[tag];
if (type && _hasOwnProperty.call(type.styleAliases, style)) { if (type && _hasOwnProperty.call(type.styleAliases, style)) {
style = type.styleAliases[style]; style = type.styleAliases[style];
@@ -91,7 +85,6 @@ function compileStyleMap(schema, map) {
return result; return result;
} }
function encodeHex(character) { function encodeHex(character) {
var string, handle, length; var string, handle, length;
@@ -113,13 +106,18 @@ function encodeHex(character) {
return '\\' + handle + common.repeat('0', length - string.length) + string; return '\\' + handle + common.repeat('0', length - string.length) + string;
} }
function State(options) { function State(options) {
this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
this.indent = Math.max(1, (options['indent'] || 2)); this.indent = Math.max(1, (options['indent'] || 2));
this.noArrayIndent = options['noArrayIndent'] || false;
this.skipInvalid = options['skipInvalid'] || false; this.skipInvalid = options['skipInvalid'] || false;
this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
this.styleMap = compileStyleMap(this.schema, options['styles'] || null); 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.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit; this.explicitTypes = this.schema.compiledExplicit;
@@ -131,6 +129,32 @@ function State(options) {
this.usedDuplicates = null; 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) { function generateNextLine(state, level) {
return '\n' + common.repeat(' ', state.indent * level); return '\n' + common.repeat(' ', state.indent * level);
@@ -150,81 +174,343 @@ function testImplicitResolving(state, str) {
return false; return false;
} }
function writeScalar(state, object) { // [33] s-white ::= s-space | s-tab
var isQuoted, checkpoint, position, length, character, first; function isWhitespace(c) {
return c === CHAR_SPACE || c === CHAR_TAB;
}
state.dump = ''; // Returns true if the character can be printed without escaping.
isQuoted = false; // From YAML 1.2: "any allowed characters known to be non-printable
checkpoint = 0; // should also be escaped. [However,] This isnt mandatory"
first = object.charCodeAt(0) || 0; // 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);
}
if (-1 !== DEPRECATED_BOOLEANS_SYNTAX.indexOf(object)) { // [34] ns-char ::= nb-char - s-white
// Ensure compatibility with YAML 1.0/1.1 loaders. // [27] nb-char ::= c-printable - b-char - c-byte-order-mark
isQuoted = true; // [26] b-char ::= b-line-feed | b-carriage-return
} else if (0 === object.length) { // [24] b-line-feed ::= #xA /* LF */
// Quote empty string // [25] b-carriage-return ::= #xD /* CR */
isQuoted = true; // [3] c-byte-order-mark ::= #xFEFF
} else if (CHAR_SPACE === first || function isNsChar(c) {
CHAR_SPACE === object.charCodeAt(object.length - 1)) { return isPrintable(c) && !isWhitespace(c)
isQuoted = true; // byte-order-mark
} else if (CHAR_MINUS === first || && c !== 0xFEFF
CHAR_QUESTION === first) { // b-char
// Don't check second symbol for simplicity && c !== CHAR_CARRIAGE_RETURN
isQuoted = true; && c !== CHAR_LINE_FEED;
}
// Simplified test for values allowed after the first character in plain style.
function isPlainSafe(c, prev) {
// 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
// - ":" - "#"
// /* An ns-char preceding */ "#"
&& c !== CHAR_COLON
&& ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));
}
// 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_EQUALS
&& c !== CHAR_GREATER_THAN
&& c !== CHAR_SINGLE_QUOTE
&& c !== CHAR_DOUBLE_QUOTE
// | “%” | “@” | “`”)
&& c !== CHAR_PERCENT
&& c !== CHAR_COMMERCIAL_AT
&& c !== CHAR_GRAVE_ACCENT;
}
// Determines whether block indentation indicator is required.
function needIndentIndicator(string) {
var leadingSpaceRe = /^\n* /;
return leadingSpaceRe.test(string);
}
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, prev_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;
}
prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
plain = plain && isPlainSafe(char, prev_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;
}
prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
plain = plain && isPlainSafe(char, prev_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 (indentPerLevel > 9 && needIndentIndicator(string)) {
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 + "'";
} }
for (position = 0, length = object.length; position < length; position += 1) { var indent = state.indent * Math.max(1, level); // no 0-indent scalars
character = object.charCodeAt(position); // 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);
if (!isQuoted) { // Without knowing if keys are implicit/explicit, assume implicit for safety.
if (CHAR_TAB === character || var singleLineOnly = iskey
CHAR_LINE_FEED === character || // No block styles in flow mode.
CHAR_CARRIAGE_RETURN === character || || (state.flowLevel > -1 && level >= state.flowLevel);
CHAR_COMMA === character || function testAmbiguity(string) {
CHAR_LEFT_SQUARE_BRACKET === character || return testImplicitResolving(state, string);
CHAR_RIGHT_SQUARE_BRACKET === character ||
CHAR_LEFT_CURLY_BRACKET === character ||
CHAR_RIGHT_CURLY_BRACKET === character ||
CHAR_SHARP === character ||
CHAR_AMPERSAND === character ||
CHAR_ASTERISK === character ||
CHAR_EXCLAMATION === character ||
CHAR_VERTICAL_LINE === character ||
CHAR_GREATER_THAN === character ||
CHAR_SINGLE_QUOTE === character ||
CHAR_DOUBLE_QUOTE === character ||
CHAR_PERCENT === character ||
CHAR_COMMERCIAL_AT === character ||
CHAR_COLON === character ||
CHAR_GRAVE_ACCENT === character) {
isQuoted = true;
}
} }
if (ESCAPE_SEQUENCES[character] || switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
!((0x00020 <= character && character <= 0x00007E) || case STYLE_PLAIN:
(0x00085 === character) || return string;
(0x000A0 <= character && character <= 0x00D7FF) || case STYLE_SINGLE:
(0x0E000 <= character && character <= 0x00FFFD) || return "'" + string.replace(/'/g, "''") + "'";
(0x10000 <= character && character <= 0x10FFFF))) { case STYLE_LITERAL:
state.dump += object.slice(checkpoint, position); return '|' + blockHeader(string, state.indent)
state.dump += ESCAPE_SEQUENCES[character] || encodeHex(character); + dropEndingNewline(indentString(string, indent));
checkpoint = position + 1; case STYLE_FOLDED:
isQuoted = true; 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 = needIndentIndicator(string) ? 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;
} }
if (checkpoint < position) { return result;
state.dump += object.slice(checkpoint, position); }
// 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;
} }
if (!isQuoted && testImplicitResolving(state, state.dump)) { // By the invariants, start <= length-1, so there is something left over.
isQuoted = true; // 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);
} }
if (isQuoted) { return result.slice(1); // drop extra \n joiner
state.dump = '"' + state.dump + '"'; }
// 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) { function writeFlowSequence(state, level, object) {
@@ -236,9 +522,7 @@ function writeFlowSequence(state, level, object) {
for (index = 0, length = object.length; index < length; index += 1) { for (index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements. // Write only valid elements.
if (writeNode(state, level, object[index], false, false)) { if (writeNode(state, level, object[index], false, false)) {
if (0 !== index) { if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
_result += ', ';
}
_result += state.dump; _result += state.dump;
} }
} }
@@ -256,10 +540,17 @@ function writeBlockSequence(state, level, object, compact) {
for (index = 0, length = object.length; index < length; index += 1) { for (index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements. // Write only valid elements.
if (writeNode(state, level + 1, object[index], true, true)) { if (writeNode(state, level + 1, object[index], true, true)) {
if (!compact || 0 !== index) { if (!compact || index !== 0) {
_result += generateNextLine(state, level); _result += generateNextLine(state, level);
} }
_result += '- ' + state.dump;
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
_result += '-';
} else {
_result += '- ';
}
_result += state.dump;
} }
} }
@@ -278,11 +569,11 @@ function writeFlowMapping(state, level, object) {
pairBuffer; pairBuffer;
for (index = 0, length = objectKeyList.length; index < length; index += 1) { for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = '';
if (0 !== index) { pairBuffer = '';
pairBuffer += ', '; if (index !== 0) pairBuffer += ', ';
}
if (state.condenseFlow) pairBuffer += '"';
objectKey = objectKeyList[index]; objectKey = objectKeyList[index];
objectValue = object[objectKey]; objectValue = object[objectKey];
@@ -291,11 +582,9 @@ function writeFlowMapping(state, level, object) {
continue; // Skip this pair because of invalid key; continue; // Skip this pair because of invalid key;
} }
if (state.dump.length > 1024) { if (state.dump.length > 1024) pairBuffer += '? ';
pairBuffer += '? ';
}
pairBuffer += state.dump + ': '; pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
if (!writeNode(state, level, objectValue, false, false)) { if (!writeNode(state, level, objectValue, false, false)) {
continue; // Skip this pair because of invalid value. continue; // Skip this pair because of invalid value.
@@ -322,21 +611,33 @@ function writeBlockMapping(state, level, object, compact) {
explicitPair, explicitPair,
pairBuffer; 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) { for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = ''; pairBuffer = '';
if (!compact || 0 !== index) { if (!compact || index !== 0) {
pairBuffer += generateNextLine(state, level); pairBuffer += generateNextLine(state, level);
} }
objectKey = objectKeyList[index]; objectKey = objectKeyList[index];
objectValue = object[objectKey]; objectValue = object[objectKey];
if (!writeNode(state, level + 1, objectKey, true, true)) { if (!writeNode(state, level + 1, objectKey, true, true, true)) {
continue; // Skip this pair because of invalid key. continue; // Skip this pair because of invalid key.
} }
explicitPair = (null !== state.tag && '?' !== state.tag) || explicitPair = (state.tag !== null && state.tag !== '?') ||
(state.dump && state.dump.length > 1024); (state.dump && state.dump.length > 1024);
if (explicitPair) { if (explicitPair) {
@@ -382,7 +683,7 @@ function detectType(state, object, explicit) {
type = typeList[index]; type = typeList[index];
if ((type.instanceOf || type.predicate) && if ((type.instanceOf || type.predicate) &&
(!type.instanceOf || (('object' === typeof object) && (object instanceof type.instanceOf))) && (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
(!type.predicate || type.predicate(object))) { (!type.predicate || type.predicate(object))) {
state.tag = explicit ? type.tag : '?'; state.tag = explicit ? type.tag : '?';
@@ -390,7 +691,7 @@ function detectType(state, object, explicit) {
if (type.represent) { if (type.represent) {
style = state.styleMap[type.tag] || type.defaultStyle; style = state.styleMap[type.tag] || type.defaultStyle;
if ('[object Function]' === _toString.call(type.represent)) { if (_toString.call(type.represent) === '[object Function]') {
_result = type.represent(object, style); _result = type.represent(object, style);
} else if (_hasOwnProperty.call(type.represent, style)) { } else if (_hasOwnProperty.call(type.represent, style)) {
_result = type.represent[style](object, style); _result = type.represent[style](object, style);
@@ -411,7 +712,7 @@ function detectType(state, object, explicit) {
// Serializes `object` and writes it to global `result`. // Serializes `object` and writes it to global `result`.
// Returns true on success, or false on invalid object. // Returns true on success, or false on invalid object.
// //
function writeNode(state, level, object, block, compact) { function writeNode(state, level, object, block, compact, iskey) {
state.tag = null; state.tag = null;
state.dump = object; state.dump = object;
@@ -422,14 +723,10 @@ function writeNode(state, level, object, block, compact) {
var type = _toString.call(state.dump); var type = _toString.call(state.dump);
if (block) { if (block) {
block = (0 > state.flowLevel || state.flowLevel > level); block = (state.flowLevel < 0 || state.flowLevel > level);
} }
if ((null !== state.tag && '?' !== state.tag) || (2 !== state.indent && level > 0)) { var objectOrArray = type === '[object Object]' || type === '[object Array]',
compact = false;
}
var objectOrArray = '[object Object]' === type || '[object Array]' === type,
duplicateIndex, duplicateIndex,
duplicate; duplicate;
@@ -438,17 +735,21 @@ function writeNode(state, level, object, block, compact) {
duplicate = duplicateIndex !== -1; duplicate = duplicateIndex !== -1;
} }
if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
compact = false;
}
if (duplicate && state.usedDuplicates[duplicateIndex]) { if (duplicate && state.usedDuplicates[duplicateIndex]) {
state.dump = '*ref_' + duplicateIndex; state.dump = '*ref_' + duplicateIndex;
} else { } else {
if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
state.usedDuplicates[duplicateIndex] = true; state.usedDuplicates[duplicateIndex] = true;
} }
if ('[object Object]' === type) { if (type === '[object Object]') {
if (block && (0 !== Object.keys(state.dump).length)) { if (block && (Object.keys(state.dump).length !== 0)) {
writeBlockMapping(state, level, state.dump, compact); writeBlockMapping(state, level, state.dump, compact);
if (duplicate) { if (duplicate) {
state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump; state.dump = '&ref_' + duplicateIndex + state.dump;
} }
} else { } else {
writeFlowMapping(state, level, state.dump); writeFlowMapping(state, level, state.dump);
@@ -456,29 +757,29 @@ function writeNode(state, level, object, block, compact) {
state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
} }
} }
} else if ('[object Array]' === type) { } else if (type === '[object Array]') {
if (block && (0 !== state.dump.length)) { var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;
writeBlockSequence(state, level, state.dump, compact); if (block && (state.dump.length !== 0)) {
writeBlockSequence(state, arrayLevel, state.dump, compact);
if (duplicate) { if (duplicate) {
state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump; state.dump = '&ref_' + duplicateIndex + state.dump;
} }
} else { } else {
writeFlowSequence(state, level, state.dump); writeFlowSequence(state, arrayLevel, state.dump);
if (duplicate) { if (duplicate) {
state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
} }
} }
} else if ('[object String]' === type) { } else if (type === '[object String]') {
if ('?' !== state.tag) { if (state.tag !== '?') {
writeScalar(state, state.dump); writeScalar(state, state.dump, level, iskey);
} }
} else if (state.skipInvalid) {
return false;
} else { } else {
if (state.skipInvalid) return false;
throw new YAMLException('unacceptable kind of an object to dump ' + type); throw new YAMLException('unacceptable kind of an object to dump ' + type);
} }
if (null !== state.tag && '?' !== state.tag) { if (state.tag !== null && state.tag !== '?') {
state.dump = '!<' + state.tag + '> ' + state.dump; state.dump = '!<' + state.tag + '> ' + state.dump;
} }
} }
@@ -501,21 +802,20 @@ function getDuplicateReferences(object, state) {
} }
function inspectNode(object, objects, duplicatesIndexes) { function inspectNode(object, objects, duplicatesIndexes) {
var type = _toString.call(object), var objectKeyList,
objectKeyList,
index, index,
length; length;
if (null !== object && 'object' === typeof object) { if (object !== null && typeof object === 'object') {
index = objects.indexOf(object); index = objects.indexOf(object);
if (-1 !== index) { if (index !== -1) {
if (-1 === duplicatesIndexes.indexOf(index)) { if (duplicatesIndexes.indexOf(index) === -1) {
duplicatesIndexes.push(index); duplicatesIndexes.push(index);
} }
} else { } else {
objects.push(object); objects.push(object);
if(Array.isArray(object)) { if (Array.isArray(object)) {
for (index = 0, length = object.length; index < length; index += 1) { for (index = 0, length = object.length; index < length; index += 1) {
inspectNode(object[index], objects, duplicatesIndexes); inspectNode(object[index], objects, duplicatesIndexes);
} }
@@ -535,20 +835,16 @@ function dump(input, options) {
var state = new State(options); var state = new State(options);
getDuplicateReferences(input, state); if (!state.noRefs) getDuplicateReferences(input, state);
if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
if (writeNode(state, 0, input, true, true)) {
return state.dump + '\n';
} else {
return ''; return '';
}
} }
function safeDump(input, options) { function safeDump(input, options) {
return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
} }
module.exports.dump = dump; module.exports.dump = dump;
module.exports.safeDump = safeDump; module.exports.safeDump = safeDump;

View File

@@ -1,18 +1,36 @@
// YAML error class. http://stackoverflow.com/questions/8458984
//
'use strict'; 'use strict';
function YAMLException(reason, mark) { function YAMLException(reason, mark) {
// Super constructor
Error.call(this);
this.name = 'YAMLException'; this.name = 'YAMLException';
this.reason = reason; this.reason = reason;
this.mark = mark; this.mark = mark;
this.message = this.toString(false); 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 || '';
}
} }
YAMLException.prototype.toString = function toString(compact) { // Inherit from Error
var result; YAMLException.prototype = Object.create(Error.prototype);
YAMLException.prototype.constructor = YAMLException;
result = 'JS-YAML: ' + (this.reason || '(unknown reason)');
YAMLException.prototype.toString = function toString(compact) {
var result = this.name + ': ';
result += this.reason || '(unknown reason)';
if (!compact && this.mark) { if (!compact && this.mark) {
result += ' ' + this.mark.toString(); result += ' ' + this.mark.toString();

File diff suppressed because it is too large Load Diff

View File

@@ -16,9 +16,7 @@ function Mark(name, buffer, position, line, column) {
Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
var head, start, tail, end, snippet; var head, start, tail, end, snippet;
if (!this.buffer) { if (!this.buffer) return null;
return null;
}
indent = indent || 4; indent = indent || 4;
maxLength = maxLength || 75; maxLength = maxLength || 75;
@@ -26,7 +24,7 @@ Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
head = ''; head = '';
start = this.position; start = this.position;
while (start > 0 && -1 === '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1))) { while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
start -= 1; start -= 1;
if (this.position - start > (maxLength / 2 - 1)) { if (this.position - start > (maxLength / 2 - 1)) {
head = ' ... '; head = ' ... ';
@@ -38,7 +36,7 @@ Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
tail = ''; tail = '';
end = this.position; end = this.position;
while (end < this.buffer.length && -1 === '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end))) { while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
end += 1; end += 1;
if (end - this.position > (maxLength / 2 - 1)) { if (end - this.position > (maxLength / 2 - 1)) {
tail = ' ... '; tail = ' ... ';

View File

@@ -1,5 +1,6 @@
'use strict'; 'use strict';
/*eslint-disable max-len*/
var common = require('./common'); var common = require('./common');
var YAMLException = require('./exception'); var YAMLException = require('./exception');
@@ -15,7 +16,7 @@ function compileList(schema, name, result) {
schema[name].forEach(function (currentType) { schema[name].forEach(function (currentType) {
result.forEach(function (previousType, previousIndex) { result.forEach(function (previousType, previousIndex) {
if (previousType.tag === currentType.tag) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
exclude.push(previousIndex); exclude.push(previousIndex);
} }
}); });
@@ -24,22 +25,26 @@ function compileList(schema, name, result) {
}); });
return result.filter(function (type, index) { return result.filter(function (type, index) {
return -1 === exclude.indexOf(index); return exclude.indexOf(index) === -1;
}); });
} }
function compileMap(/* lists... */) { function compileMap(/* lists... */) {
var result = {}, index, length; var result = {
scalar: {},
sequence: {},
mapping: {},
fallback: {}
}, index, length;
function collectType(type) { function collectType(type) {
result[type.tag] = type; result[type.kind][type.tag] = result['fallback'][type.tag] = type;
} }
for (index = 0, length = arguments.length; index < length; index += 1) { for (index = 0, length = arguments.length; index < length; index += 1) {
arguments[index].forEach(collectType); arguments[index].forEach(collectType);
} }
return result; return result;
} }
@@ -50,7 +55,7 @@ function Schema(definition) {
this.explicit = definition.explicit || []; this.explicit = definition.explicit || [];
this.implicit.forEach(function (type) { this.implicit.forEach(function (type) {
if (type.loadKind && 'scalar' !== type.loadKind) { 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.'); throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
} }
}); });

View File

@@ -22,7 +22,7 @@ var YAML_NODE_KINDS = [
function compileStyleAliases(map) { function compileStyleAliases(map) {
var result = {}; var result = {};
if (null !== map) { if (map !== null) {
Object.keys(map).forEach(function (style) { Object.keys(map).forEach(function (style) {
map[style].forEach(function (alias) { map[style].forEach(function (alias) {
result[String(alias)] = style; result[String(alias)] = style;
@@ -37,7 +37,7 @@ function Type(tag, options) {
options = options || {}; options = options || {};
Object.keys(options).forEach(function (name) { Object.keys(options).forEach(function (name) {
if (-1 === TYPE_CONSTRUCTOR_OPTIONS.indexOf(name)) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
} }
}); });
@@ -53,7 +53,7 @@ function Type(tag, options) {
this.defaultStyle = options['defaultStyle'] || null; this.defaultStyle = options['defaultStyle'] || null;
this.styleAliases = compileStyleAliases(options['styleAliases'] || null); this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
if (-1 === YAML_NODE_KINDS.indexOf(this.kind)) { if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
} }
} }

View File

@@ -1,9 +1,15 @@
'use strict'; '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 (__) {}
// A trick for browserified version.
// Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined
var NodeBuffer = require('buffer').Buffer;
var Type = require('../type'); var Type = require('../type');
@@ -12,21 +18,19 @@ var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
function resolveYamlBinary(data) { function resolveYamlBinary(data) {
if (null === data) { if (data === null) return false;
return false;
}
var code, idx, bitlen = 0, len = 0, max = data.length, map = BASE64_MAP; var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
// Convert one by one. // Convert one by one.
for (idx = 0; idx < max; idx ++) { for (idx = 0; idx < max; idx++) {
code = map.indexOf(data.charAt(idx)); code = map.indexOf(data.charAt(idx));
// Skip CR/LF // Skip CR/LF
if (code > 64) { continue; } if (code > 64) continue;
// Fail on illegal characters // Fail on illegal characters
if (code < 0) { return false; } if (code < 0) return false;
bitlen += 6; bitlen += 6;
} }
@@ -36,7 +40,7 @@ function resolveYamlBinary(data) {
} }
function constructYamlBinary(data) { function constructYamlBinary(data) {
var code, idx, tailbits, var idx, tailbits,
input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
max = input.length, max = input.length,
map = BASE64_MAP, map = BASE64_MAP,
@@ -57,7 +61,7 @@ function constructYamlBinary(data) {
// Dump tail // Dump tail
tailbits = (max % 4)*6; tailbits = (max % 4) * 6;
if (tailbits === 0) { if (tailbits === 0) {
result.push((bits >> 16) & 0xFF); result.push((bits >> 16) & 0xFF);
@@ -72,7 +76,8 @@ function constructYamlBinary(data) {
// Wrap into Buffer for NodeJS and leave Array for browser // Wrap into Buffer for NodeJS and leave Array for browser
if (NodeBuffer) { if (NodeBuffer) {
return new NodeBuffer(result); // Support node 6.+ Buffer API when available
return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
} }
return result; return result;

View File

@@ -3,9 +3,7 @@
var Type = require('../type'); var Type = require('../type');
function resolveYamlBoolean(data) { function resolveYamlBoolean(data) {
if (null === data) { if (data === null) return false;
return false;
}
var max = data.length; var max = data.length;
@@ -20,7 +18,7 @@ function constructYamlBoolean(data) {
} }
function isBoolean(object) { function isBoolean(object) {
return '[object Boolean]' === Object.prototype.toString.call(object); return Object.prototype.toString.call(object) === '[object Boolean]';
} }
module.exports = new Type('tag:yaml.org,2002:bool', { module.exports = new Type('tag:yaml.org,2002:bool', {

View File

@@ -4,22 +4,28 @@ var common = require('../common');
var Type = require('../type'); var Type = require('../type');
var YAML_FLOAT_PATTERN = new RegExp( var YAML_FLOAT_PATTERN = new RegExp(
'^(?:[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+][0-9]+)?' + // 2.5e4, 2.5 and integers
'|\\.[0-9_]+(?:[eE][-+][0-9]+)?' + '^(?:[-+]?(?: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_]*' + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
// .inf
'|[-+]?\\.(?:inf|Inf|INF)' + '|[-+]?\\.(?:inf|Inf|INF)' +
// .nan
'|\\.(?:nan|NaN|NAN))$'); '|\\.(?:nan|NaN|NAN))$');
function resolveYamlFloat(data) { function resolveYamlFloat(data) {
if (null === 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 false;
} }
var value, sign, base, digits;
if (!YAML_FLOAT_PATTERN.test(data)) {
return false;
}
return true; return true;
} }
@@ -27,20 +33,20 @@ function constructYamlFloat(data) {
var value, sign, base, digits; var value, sign, base, digits;
value = data.replace(/_/g, '').toLowerCase(); value = data.replace(/_/g, '').toLowerCase();
sign = '-' === value[0] ? -1 : 1; sign = value[0] === '-' ? -1 : 1;
digits = []; digits = [];
if (0 <= '+-'.indexOf(value[0])) { if ('+-'.indexOf(value[0]) >= 0) {
value = value.slice(1); value = value.slice(1);
} }
if ('.inf' === value) { if (value === '.inf') {
return (1 === sign) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
} else if ('.nan' === value) { } else if (value === '.nan') {
return NaN; return NaN;
} else if (0 <= value.indexOf(':')) { } else if (value.indexOf(':') >= 0) {
value.split(':').forEach(function (v) { value.split(':').forEach(function (v) {
digits.unshift(parseFloat(v, 10)); digits.unshift(parseFloat(v, 10));
}); });
@@ -55,49 +61,49 @@ function constructYamlFloat(data) {
return sign * value; return sign * value;
} else {
return sign * parseFloat(value, 10);
} }
return sign * parseFloat(value, 10);
} }
var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
function representYamlFloat(object, style) { function representYamlFloat(object, style) {
var res;
if (isNaN(object)) { if (isNaN(object)) {
switch (style) { switch (style) {
case 'lowercase': case 'lowercase': return '.nan';
return '.nan'; case 'uppercase': return '.NAN';
case 'uppercase': case 'camelcase': return '.NaN';
return '.NAN';
case 'camelcase':
return '.NaN';
} }
} else if (Number.POSITIVE_INFINITY === object) { } else if (Number.POSITIVE_INFINITY === object) {
switch (style) { switch (style) {
case 'lowercase': case 'lowercase': return '.inf';
return '.inf'; case 'uppercase': return '.INF';
case 'uppercase': case 'camelcase': return '.Inf';
return '.INF';
case 'camelcase':
return '.Inf';
} }
} else if (Number.NEGATIVE_INFINITY === object) { } else if (Number.NEGATIVE_INFINITY === object) {
switch (style) { switch (style) {
case 'lowercase': case 'lowercase': return '-.inf';
return '-.inf'; case 'uppercase': return '-.INF';
case 'uppercase': case 'camelcase': return '-.Inf';
return '-.INF';
case 'camelcase':
return '-.Inf';
} }
} else if (common.isNegativeZero(object)) { } else if (common.isNegativeZero(object)) {
return '-0.0'; return '-0.0';
} else {
return object.toString(10);
} }
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) { function isFloat(object) {
return ('[object Number]' === Object.prototype.toString.call(object)) && return (Object.prototype.toString.call(object) === '[object Number]') &&
(0 !== object % 1 || common.isNegativeZero(object)); (object % 1 !== 0 || common.isNegativeZero(object));
} }
module.exports = new Type('tag:yaml.org,2002:float', { module.exports = new Type('tag:yaml.org,2002:float', {

View File

@@ -18,16 +18,14 @@ function isDecCode(c) {
} }
function resolveYamlInteger(data) { function resolveYamlInteger(data) {
if (null === data) { if (data === null) return false;
return false;
}
var max = data.length, var max = data.length,
index = 0, index = 0,
hasDigits = false, hasDigits = false,
ch; ch;
if (!max) { return false; } if (!max) return false;
ch = data[index]; ch = data[index];
@@ -38,7 +36,7 @@ function resolveYamlInteger(data) {
if (ch === '0') { if (ch === '0') {
// 0 // 0
if (index+1 === max) { return true; } if (index + 1 === max) return true;
ch = data[++index]; ch = data[++index];
// base 2, base 8, base 16 // base 2, base 8, base 16
@@ -49,13 +47,11 @@ function resolveYamlInteger(data) {
for (; index < max; index++) { for (; index < max; index++) {
ch = data[index]; ch = data[index];
if (ch === '_') { continue; } if (ch === '_') continue;
if (ch !== '0' && ch !== '1') { if (ch !== '0' && ch !== '1') return false;
return false;
}
hasDigits = true; hasDigits = true;
} }
return hasDigits; return hasDigits && ch !== '_';
} }
@@ -65,43 +61,43 @@ function resolveYamlInteger(data) {
for (; index < max; index++) { for (; index < max; index++) {
ch = data[index]; ch = data[index];
if (ch === '_') { continue; } if (ch === '_') continue;
if (!isHexCode(data.charCodeAt(index))) { if (!isHexCode(data.charCodeAt(index))) return false;
return false;
}
hasDigits = true; hasDigits = true;
} }
return hasDigits; return hasDigits && ch !== '_';
} }
// base 8 // base 8
for (; index < max; index++) { for (; index < max; index++) {
ch = data[index]; ch = data[index];
if (ch === '_') { continue; } if (ch === '_') continue;
if (!isOctCode(data.charCodeAt(index))) { if (!isOctCode(data.charCodeAt(index))) return false;
return false;
}
hasDigits = true; hasDigits = true;
} }
return hasDigits; return hasDigits && ch !== '_';
} }
// base 10 (except 0) or base 60 // base 10 (except 0) or base 60
// value should not start with `_`;
if (ch === '_') return false;
for (; index < max; index++) { for (; index < max; index++) {
ch = data[index]; ch = data[index];
if (ch === '_') { continue; } if (ch === '_') continue;
if (ch === ':') { break; } if (ch === ':') break;
if (!isDecCode(data.charCodeAt(index))) { if (!isDecCode(data.charCodeAt(index))) {
return false; return false;
} }
hasDigits = true; hasDigits = true;
} }
if (!hasDigits) { return false; } // Should have digits and should not end with `_`
if (!hasDigits || ch === '_') return false;
// if !base60 - done; // if !base60 - done;
if (ch !== ':') { return true; } if (ch !== ':') return true;
// base60 almost not used, no needs to optimize // base60 almost not used, no needs to optimize
return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
@@ -117,24 +113,17 @@ function constructYamlInteger(data) {
ch = value[0]; ch = value[0];
if (ch === '-' || ch === '+') { if (ch === '-' || ch === '+') {
if (ch === '-') { sign = -1; } if (ch === '-') sign = -1;
value = value.slice(1); value = value.slice(1);
ch = value[0]; ch = value[0];
} }
if ('0' === value) { if (value === '0') return 0;
return 0;
}
if (ch === '0') { if (ch === '0') {
if (value[1] === 'b') { if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
return sign * parseInt(value.slice(2), 2); if (value[1] === 'x') return sign * parseInt(value, 16);
}
if (value[1] === 'x') {
return sign * parseInt(value, 16);
}
return sign * parseInt(value, 8); return sign * parseInt(value, 8);
} }
if (value.indexOf(':') !== -1) { if (value.indexOf(':') !== -1) {
@@ -158,8 +147,8 @@ function constructYamlInteger(data) {
} }
function isInteger(object) { function isInteger(object) {
return ('[object Number]' === Object.prototype.toString.call(object)) && return (Object.prototype.toString.call(object)) === '[object Number]' &&
(0 === object % 1 && !common.isNegativeZero(object)); (object % 1 === 0 && !common.isNegativeZero(object));
} }
module.exports = new Type('tag:yaml.org,2002:int', { module.exports = new Type('tag:yaml.org,2002:int', {
@@ -168,10 +157,11 @@ module.exports = new Type('tag:yaml.org,2002:int', {
construct: constructYamlInteger, construct: constructYamlInteger,
predicate: isInteger, predicate: isInteger,
represent: { represent: {
binary: function (object) { return '0b' + object.toString(2); }, binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
octal: function (object) { return '0' + object.toString(8); }, octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },
decimal: function (object) { return object.toString(10); }, decimal: function (obj) { return obj.toString(10); },
hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); } /* eslint-disable max-len */
hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
}, },
defaultStyle: 'decimal', defaultStyle: 'decimal',
styleAliases: { styleAliases: {

View File

@@ -10,29 +10,29 @@ var esprima;
// found too - then fail to parse. // found too - then fail to parse.
// //
try { try {
esprima = require('esprima'); // workaround to exclude package from browserify list.
var _require = require;
esprima = _require('esprima');
} catch (_) { } catch (_) {
/*global window */ /* eslint-disable no-redeclare */
if (typeof window !== 'undefined') { esprima = window.esprima; } /* global window */
if (typeof window !== 'undefined') esprima = window.esprima;
} }
var Type = require('../../type'); var Type = require('../../type');
function resolveJavascriptFunction(data) { function resolveJavascriptFunction(data) {
if (null === data) { if (data === null) return false;
return false;
}
try { try {
var source = '(' + data + ')', var source = '(' + data + ')',
ast = esprima.parse(source, { range: true }), ast = esprima.parse(source, { range: true });
params = [],
body;
if ('Program' !== ast.type || if (ast.type !== 'Program' ||
1 !== ast.body.length || ast.body.length !== 1 ||
'ExpressionStatement' !== ast.body[0].type || ast.body[0].type !== 'ExpressionStatement' ||
'FunctionExpression' !== ast.body[0].expression.type) { (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
ast.body[0].expression.type !== 'FunctionExpression')) {
return false; return false;
} }
@@ -50,10 +50,11 @@ function constructJavascriptFunction(data) {
params = [], params = [],
body; body;
if ('Program' !== ast.type || if (ast.type !== 'Program' ||
1 !== ast.body.length || ast.body.length !== 1 ||
'ExpressionStatement' !== ast.body[0].type || ast.body[0].type !== 'ExpressionStatement' ||
'FunctionExpression' !== ast.body[0].expression.type) { (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
ast.body[0].expression.type !== 'FunctionExpression')) {
throw new Error('Failed to resolve function'); throw new Error('Failed to resolve function');
} }
@@ -65,7 +66,14 @@ function constructJavascriptFunction(data) {
// Esprima's ranges include the first '{' and the last '}' characters on // Esprima's ranges include the first '{' and the last '}' characters on
// function expressions. So cut them out. // function expressions. So cut them out.
return new Function(params, source.slice(body[0]+1, body[1]-1)); if (ast.body[0].expression.body.type === 'BlockStatement') {
/*eslint-disable no-new-func*/
return new Function(params, source.slice(body[0] + 1, body[1] - 1));
}
// ES6 arrow functions can omit the BlockStatement. In that case, just return
// the body.
/*eslint-disable no-new-func*/
return new Function(params, 'return ' + source.slice(body[0], body[1]));
} }
function representJavascriptFunction(object /*, style*/) { function representJavascriptFunction(object /*, style*/) {
@@ -73,7 +81,7 @@ function representJavascriptFunction(object /*, style*/) {
} }
function isFunction(object) { function isFunction(object) {
return '[object Function]' === Object.prototype.toString.call(object); return Object.prototype.toString.call(object) === '[object Function]';
} }
module.exports = new Type('tag:yaml.org,2002:js/function', { module.exports = new Type('tag:yaml.org,2002:js/function', {

View File

@@ -3,13 +3,8 @@
var Type = require('../../type'); var Type = require('../../type');
function resolveJavascriptRegExp(data) { function resolveJavascriptRegExp(data) {
if (null === data) { if (data === null) return false;
return false; if (data.length === 0) return false;
}
if (0 === data.length) {
return false;
}
var regexp = data, var regexp = data,
tail = /\/([gim]*)$/.exec(data), tail = /\/([gim]*)$/.exec(data),
@@ -17,24 +12,15 @@ function resolveJavascriptRegExp(data) {
// if regexp starts with '/' it can have modifiers and must be properly closed // if regexp starts with '/' it can have modifiers and must be properly closed
// `/foo/gim` - modifiers tail can be maximum 3 chars // `/foo/gim` - modifiers tail can be maximum 3 chars
if ('/' === regexp[0]) { if (regexp[0] === '/') {
if (tail) { if (tail) modifiers = tail[1];
modifiers = tail[1];
}
if (modifiers.length > 3) { return false; } if (modifiers.length > 3) return false;
// if expression starts with /, is should be properly terminated // if expression starts with /, is should be properly terminated
if (regexp[regexp.length - modifiers.length - 1] !== '/') { return false; } if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
} }
try {
var dummy = new RegExp(regexp, modifiers);
return true; return true;
} catch (error) {
return false;
}
} }
function constructJavascriptRegExp(data) { function constructJavascriptRegExp(data) {
@@ -43,10 +29,8 @@ function constructJavascriptRegExp(data) {
modifiers = ''; modifiers = '';
// `/foo/gim` - tail can be maximum 4 chars // `/foo/gim` - tail can be maximum 4 chars
if ('/' === regexp[0]) { if (regexp[0] === '/') {
if (tail) { if (tail) modifiers = tail[1];
modifiers = tail[1];
}
regexp = regexp.slice(1, regexp.length - modifiers.length - 1); regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
} }
@@ -56,23 +40,15 @@ function constructJavascriptRegExp(data) {
function representJavascriptRegExp(object /*, style*/) { function representJavascriptRegExp(object /*, style*/) {
var result = '/' + object.source + '/'; var result = '/' + object.source + '/';
if (object.global) { if (object.global) result += 'g';
result += 'g'; if (object.multiline) result += 'm';
} if (object.ignoreCase) result += 'i';
if (object.multiline) {
result += 'm';
}
if (object.ignoreCase) {
result += 'i';
}
return result; return result;
} }
function isRegExp(object) { function isRegExp(object) {
return '[object RegExp]' === Object.prototype.toString.call(object); return Object.prototype.toString.call(object) === '[object RegExp]';
} }
module.exports = new Type('tag:yaml.org,2002:js/regexp', { module.exports = new Type('tag:yaml.org,2002:js/regexp', {

View File

@@ -7,6 +7,7 @@ function resolveJavascriptUndefined() {
} }
function constructJavascriptUndefined() { function constructJavascriptUndefined() {
/*eslint-disable no-undefined*/
return undefined; return undefined;
} }
@@ -15,7 +16,7 @@ function representJavascriptUndefined() {
} }
function isUndefined(object) { function isUndefined(object) {
return 'undefined' === typeof object; return typeof object === 'undefined';
} }
module.exports = new Type('tag:yaml.org,2002:js/undefined', { module.exports = new Type('tag:yaml.org,2002:js/undefined', {

View File

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

View File

@@ -3,7 +3,7 @@
var Type = require('../type'); var Type = require('../type');
function resolveYamlMerge(data) { function resolveYamlMerge(data) {
return '<<' === data || null === data; return data === '<<' || data === null;
} }
module.exports = new Type('tag:yaml.org,2002:merge', { module.exports = new Type('tag:yaml.org,2002:merge', {

View File

@@ -3,9 +3,7 @@
var Type = require('../type'); var Type = require('../type');
function resolveYamlNull(data) { function resolveYamlNull(data) {
if (null === data) { if (data === null) return true;
return true;
}
var max = data.length; var max = data.length;
@@ -18,7 +16,7 @@ function constructYamlNull() {
} }
function isNull(object) { function isNull(object) {
return null === object; return object === null;
} }
module.exports = new Type('tag:yaml.org,2002:null', { module.exports = new Type('tag:yaml.org,2002:null', {

View File

@@ -6,9 +6,7 @@ var _hasOwnProperty = Object.prototype.hasOwnProperty;
var _toString = Object.prototype.toString; var _toString = Object.prototype.toString;
function resolveYamlOmap(data) { function resolveYamlOmap(data) {
if (null === data) { if (data === null) return true;
return true;
}
var objectKeys = [], index, length, pair, pairKey, pairHasKey, var objectKeys = [], index, length, pair, pairKey, pairHasKey,
object = data; object = data;
@@ -17,36 +15,26 @@ function resolveYamlOmap(data) {
pair = object[index]; pair = object[index];
pairHasKey = false; pairHasKey = false;
if ('[object Object]' !== _toString.call(pair)) { if (_toString.call(pair) !== '[object Object]') return false;
return false;
}
for (pairKey in pair) { for (pairKey in pair) {
if (_hasOwnProperty.call(pair, pairKey)) { if (_hasOwnProperty.call(pair, pairKey)) {
if (!pairHasKey) { if (!pairHasKey) pairHasKey = true;
pairHasKey = true; else return false;
} else {
return false;
}
} }
} }
if (!pairHasKey) { if (!pairHasKey) return false;
return false;
}
if (-1 === objectKeys.indexOf(pairKey)) { if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
objectKeys.push(pairKey); else return false;
} else {
return false;
}
} }
return true; return true;
} }
function constructYamlOmap(data) { function constructYamlOmap(data) {
return null !== data ? data : []; return data !== null ? data : [];
} }
module.exports = new Type('tag:yaml.org,2002:omap', { module.exports = new Type('tag:yaml.org,2002:omap', {

View File

@@ -5,9 +5,7 @@ var Type = require('../type');
var _toString = Object.prototype.toString; var _toString = Object.prototype.toString;
function resolveYamlPairs(data) { function resolveYamlPairs(data) {
if (null === data) { if (data === null) return true;
return true;
}
var index, length, pair, keys, result, var index, length, pair, keys, result,
object = data; object = data;
@@ -17,15 +15,11 @@ function resolveYamlPairs(data) {
for (index = 0, length = object.length; index < length; index += 1) { for (index = 0, length = object.length; index < length; index += 1) {
pair = object[index]; pair = object[index];
if ('[object Object]' !== _toString.call(pair)) { if (_toString.call(pair) !== '[object Object]') return false;
return false;
}
keys = Object.keys(pair); keys = Object.keys(pair);
if (1 !== keys.length) { if (keys.length !== 1) return false;
return false;
}
result[index] = [ keys[0], pair[keys[0]] ]; result[index] = [ keys[0], pair[keys[0]] ];
} }
@@ -34,9 +28,7 @@ function resolveYamlPairs(data) {
} }
function constructYamlPairs(data) { function constructYamlPairs(data) {
if (null === data) { if (data === null) return [];
return [];
}
var index, length, pair, keys, result, var index, length, pair, keys, result,
object = data; object = data;

View File

@@ -4,5 +4,5 @@ var Type = require('../type');
module.exports = new Type('tag:yaml.org,2002:seq', { module.exports = new Type('tag:yaml.org,2002:seq', {
kind: 'sequence', kind: 'sequence',
construct: function (data) { return null !== data ? data : []; } construct: function (data) { return data !== null ? data : []; }
}); });

View File

@@ -5,17 +5,13 @@ var Type = require('../type');
var _hasOwnProperty = Object.prototype.hasOwnProperty; var _hasOwnProperty = Object.prototype.hasOwnProperty;
function resolveYamlSet(data) { function resolveYamlSet(data) {
if (null === data) { if (data === null) return true;
return true;
}
var key, object = data; var key, object = data;
for (key in object) { for (key in object) {
if (_hasOwnProperty.call(object, key)) { if (_hasOwnProperty.call(object, key)) {
if (null !== object[key]) { if (object[key] !== null) return false;
return false;
}
} }
} }
@@ -23,7 +19,7 @@ function resolveYamlSet(data) {
} }
function constructYamlSet(data) { function constructYamlSet(data) {
return null !== data ? data : {}; return data !== null ? data : {};
} }
module.exports = new Type('tag:yaml.org,2002:set', { module.exports = new Type('tag:yaml.org,2002:set', {

View File

@@ -4,5 +4,5 @@ var Type = require('../type');
module.exports = new Type('tag:yaml.org,2002:str', { module.exports = new Type('tag:yaml.org,2002:str', {
kind: 'scalar', kind: 'scalar',
construct: function (data) { return null !== data ? data : ''; } construct: function (data) { return data !== null ? data : ''; }
}); });

View File

@@ -2,44 +2,38 @@
var Type = require('../type'); var Type = require('../type');
var YAML_DATE_REGEXP = new RegExp(
'^([0-9][0-9][0-9][0-9])' + // [1] year
'-([0-9][0-9])' + // [2] month
'-([0-9][0-9])$'); // [3] day
var YAML_TIMESTAMP_REGEXP = new RegExp( var YAML_TIMESTAMP_REGEXP = new RegExp(
'^([0-9][0-9][0-9][0-9])' + // [1] year '^([0-9][0-9][0-9][0-9])' + // [1] year
'-([0-9][0-9]?)' + // [2] month '-([0-9][0-9]?)' + // [2] month
'-([0-9][0-9]?)' + // [3] day '-([0-9][0-9]?)' + // [3] day
'(?:(?:[Tt]|[ \\t]+)' + // ... '(?:[Tt]|[ \\t]+)' + // ...
'([0-9][0-9]?)' + // [4] hour '([0-9][0-9]?)' + // [4] hour
':([0-9][0-9])' + // [5] minute ':([0-9][0-9])' + // [5] minute
':([0-9][0-9])' + // [6] second ':([0-9][0-9])' + // [6] second
'(?:\\.([0-9]*))?' + // [7] fraction '(?:\\.([0-9]*))?' + // [7] fraction
'(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
'(?::([0-9][0-9]))?))?)?$'); // [11] tz_minute '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
function resolveYamlTimestamp(data) { function resolveYamlTimestamp(data) {
if (null === data) { if (data === null) return false;
if (YAML_DATE_REGEXP.exec(data) !== null) return true;
if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
return false; return false;
}
var match, year, month, day, hour, minute, second, fraction = 0,
delta = null, tz_hour, tz_minute, date;
match = YAML_TIMESTAMP_REGEXP.exec(data);
if (null === match) {
return false;
}
return true;
} }
function constructYamlTimestamp(data) { function constructYamlTimestamp(data) {
var match, year, month, day, hour, minute, second, fraction = 0, var match, year, month, day, hour, minute, second, fraction = 0,
delta = null, tz_hour, tz_minute, date; delta = null, tz_hour, tz_minute, date;
match = YAML_TIMESTAMP_REGEXP.exec(data); match = YAML_DATE_REGEXP.exec(data);
if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
if (null === match) { if (match === null) throw new Error('Date resolve error');
throw new Error('Date resolve error');
}
// match: [1] year [2] month [3] day // match: [1] year [2] month [3] day
@@ -71,16 +65,12 @@ function constructYamlTimestamp(data) {
tz_hour = +(match[10]); tz_hour = +(match[10]);
tz_minute = +(match[11] || 0); tz_minute = +(match[11] || 0);
delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
if ('-' === match[9]) { if (match[9] === '-') delta = -delta;
delta = -delta;
}
} }
date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
if (delta) { if (delta) date.setTime(date.getTime() - delta);
date.setTime(date.getTime() - delta);
}
return date; return date;
} }

View File

@@ -1,37 +1,34 @@
{ {
"_from": "js-yaml@3.2.7", "_from": "js-yaml@>=3.13.1",
"_id": "js-yaml@3.2.7", "_id": "js-yaml@3.14.0",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha1-ECeQ8mXZhv6VpNDyp5Lnp72Ibuw=", "_integrity": "sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A==",
"_location": "/js-yaml", "_location": "/js-yaml",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "range",
"registry": true, "registry": true,
"raw": "js-yaml@3.2.7", "raw": "js-yaml@>=3.13.1",
"name": "js-yaml", "name": "js-yaml",
"escapedName": "js-yaml", "escapedName": "js-yaml",
"rawSpec": "3.2.7", "rawSpec": ">=3.13.1",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "3.2.7" "fetchSpec": ">=3.13.1"
}, },
"_requiredBy": [ "_requiredBy": [
"/nodestalker" "/"
], ],
"_resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.2.7.tgz", "_resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.0.tgz",
"_shasum": "102790f265d986fe95a4d0f2a792e7a7bd886eec", "_shasum": "a7a34170f26a21bb162424d8adacb4113a69e482",
"_spec": "js-yaml@3.2.7", "_spec": "js-yaml@>=3.13.1",
"_where": "/usr/home/web/cp/clonos/node/node_modules/nodestalker", "_where": "/usr/local/www/clonos/node",
"author": { "author": {
"name": "Dervus Grim", "name": "Vladimir Zapparov",
"email": "dervus.grim@gmail.com" "email": "dervus.grim@gmail.com"
}, },
"bin": { "bin": {
"js-yaml": "bin/js-yaml.js" "js-yaml": "bin/js-yaml.js"
}, },
"browser": {
"buffer": false
},
"bugs": { "bugs": {
"url": "https://github.com/nodeca/js-yaml/issues" "url": "https://github.com/nodeca/js-yaml/issues"
}, },
@@ -54,32 +51,45 @@
} }
], ],
"dependencies": { "dependencies": {
"argparse": "~ 1.0.0", "argparse": "^1.0.7",
"esprima": "~ 2.0.0" "esprima": "^4.0.0"
}, },
"deprecated": false, "deprecated": false,
"description": "YAML 1.2 parser and serializer", "description": "YAML 1.2 parser and serializer",
"devDependencies": { "devDependencies": {
"ansi": "*", "ansi": "^0.3.1",
"benchmark": "*", "benchmark": "^2.1.4",
"mocha": "*" "browserify": "^16.2.2",
"codemirror": "^5.13.4",
"eslint": "^7.0.0",
"fast-check": "^1.24.2",
"istanbul": "^0.4.5",
"mocha": "^7.1.2",
"uglify-js": "^3.0.1"
}, },
"files": [
"index.js",
"lib/",
"bin/",
"dist/"
],
"homepage": "https://github.com/nodeca/js-yaml", "homepage": "https://github.com/nodeca/js-yaml",
"jsdelivr": "dist/js-yaml.min.js",
"keywords": [ "keywords": [
"yaml", "yaml",
"parser", "parser",
"serializer", "serializer",
"pyyaml" "pyyaml"
], ],
"license": { "license": "MIT",
"type": "MIT",
"url": "https://github.com/nodeca/js-yaml/blob/master/LICENSE"
},
"main": "./index.js",
"name": "js-yaml", "name": "js-yaml",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git://github.com/nodeca/js-yaml.git" "url": "git+https://github.com/nodeca/js-yaml.git"
}, },
"version": "3.2.7" "scripts": {
"test": "make test"
},
"unpkg": "dist/js-yaml.min.js",
"version": "3.14.0"
} }

View File

@@ -1,2 +0,0 @@
node_modules
docs

View File

@@ -1,5 +1,3 @@
language: node_js language: node_js
node_js: node_js:
- "4.0" - "13.0"
- "0.12"
- "0.11"

View File

@@ -631,7 +631,7 @@ BeanstalkClient.prototype._createPutCommand = function(data, priority, delay, tt
var commandBegin = 'put ' + priority + ' ' + delay + ' ' + ttr + ' ' + data.length + '\r\n'; var commandBegin = 'put ' + priority + ' ' + delay + ' ' + ttr + ' ' + data.length + '\r\n';
var commandEnd = '\r\n'; var commandEnd = '\r\n';
command = new Buffer(commandBegin.length + data.length + commandEnd.length); command = Buffer.alloc(commandBegin.length + data.length + commandEnd.length);
command.write(commandBegin, 0, commandBegin.length, 'binary'); command.write(commandBegin, 0, commandBegin.length, 'binary');
data.copy(command, commandBegin.length, 0, data.length); data.copy(command, commandBegin.length, 0, data.length);
command.write(commandEnd, commandBegin.length + data.length, commandEnd.length, 'binary'); command.write(commandEnd, commandBegin.length + data.length, commandEnd.length, 'binary');

View File

@@ -1,27 +1,28 @@
{ {
"_from": "nodestalker@0.1.21", "_from": "nodestalker@0.1.22",
"_id": "nodestalker@0.1.21", "_id": "nodestalker@0.1.22",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha1-frUbWnbdq1Xau5uxNScCoigJUvk=", "_integrity": "sha512-yRFJgkO9BkGybKOLmjum4WAHeaSDbvWA7eC9RpHlxkGcsi7yZbsLo9BTHANbWlSbbQtWkkO0Lwyt4JKsjGAj1Q==",
"_location": "/nodestalker", "_location": "/nodestalker",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "nodestalker@0.1.21", "raw": "nodestalker@0.1.22",
"name": "nodestalker", "name": "nodestalker",
"escapedName": "nodestalker", "escapedName": "nodestalker",
"rawSpec": "0.1.21", "rawSpec": "0.1.22",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "0.1.21" "fetchSpec": "0.1.22"
}, },
"_requiredBy": [ "_requiredBy": [
"#USER",
"/" "/"
], ],
"_resolved": "https://registry.npmjs.org/nodestalker/-/nodestalker-0.1.21.tgz", "_resolved": "https://registry.npmjs.org/nodestalker/-/nodestalker-0.1.22.tgz",
"_shasum": "7eb51b5a76ddab55dabb9bb1352702a2280952f9", "_shasum": "a62dd8e67a6d5e9b8babb21c6dfcb055d0aaa5bd",
"_spec": "nodestalker@0.1.21", "_spec": "nodestalker@0.1.22",
"_where": "/usr/home/web/cp/clonos/node", "_where": "/usr/local/www/clonos/node",
"author": { "author": {
"name": "Pascal Opitz", "name": "Pascal Opitz",
"email": "contact@pascalopitz.com", "email": "contact@pascalopitz.com",
@@ -61,12 +62,12 @@
} }
], ],
"dependencies": { "dependencies": {
"js-yaml": "3.2.7" "js-yaml": "^3.13.1"
}, },
"deprecated": false, "deprecated": false,
"description": "A Beanstalk client for node.js.", "description": "A Beanstalk client for node.js.",
"devDependencies": { "devDependencies": {
"docco": "~0.7.0" "docco": "^0.8.0"
}, },
"engines": { "engines": {
"node": ">=0.11" "node": ">=0.11"
@@ -92,5 +93,5 @@
"docs": "docco ./lib/beanstalk_client.js", "docs": "docco ./lib/beanstalk_client.js",
"test": "find tests/test_*.js | xargs -n1 node" "test": "find tests/test_*.js | xargs -n1 node"
}, },
"version": "0.1.21" "version": "0.1.22"
} }

View File

@@ -4,8 +4,8 @@ var assert = require('assert');
var helper = require('./helper'); var helper = require('./helper');
var util = require('util'); var util = require('util');
var data1 = new Buffer([1,2,3,4]); var data1 = Buffer.alloc(4, [1,2,3,4]);
var data2 = new Buffer([1,2,3,4]); var data2 = Buffer.alloc(4, [1,2,3,4]);
helper.bind(function(conn, data) { helper.bind(function(conn, data) {
if(String(data).indexOf('put') > -1) { if(String(data).indexOf('put') > -1) {

View File

@@ -5,11 +5,11 @@ var helper = require('./helper');
var util = require('util'); var util = require('util');
var commandBegin = "RESERVED 1 4\r\n"; var commandBegin = "RESERVED 1 4\r\n";
var data1 = new Buffer([1,2,3,4]); var data1 = Buffer.alloc(4, [1,2,3,4]);
var data2 = new Buffer(data1); var data2 = Buffer.alloc(4, data1);
var commandEnd = "\r\n"; var commandEnd = "\r\n";
var command = new Buffer(commandBegin.length + data1.length + commandEnd.length); var command = Buffer.alloc(commandBegin.length + data1.length + commandEnd.length);
command.write(commandBegin, 0, commandBegin.length, 'binary'); command.write(commandBegin, 0, commandBegin.length, 'binary');
data1.copy(command, commandBegin.length, 0, data1.length); data1.copy(command, commandBegin.length, 0, data1.length);
command.write(commandEnd, commandBegin.length + data1.length, commandEnd.length, 'binary'); command.write(commandEnd, commandBegin.length + data1.length, commandEnd.length, 'binary');

24
node/package-lock.json generated
View File

@@ -18,25 +18,25 @@
"integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==" "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg=="
}, },
"esprima": { "esprima": {
"version": "2.0.0", "version": "4.0.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-2.0.0.tgz", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"integrity": "sha1-YJrFwmZ+rlQztB657OziMxtBSY8=" "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="
}, },
"js-yaml": { "js-yaml": {
"version": "3.2.7", "version": "3.14.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.2.7.tgz", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.0.tgz",
"integrity": "sha1-ECeQ8mXZhv6VpNDyp5Lnp72Ibuw=", "integrity": "sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A==",
"requires": { "requires": {
"argparse": "~ 1.0.0", "argparse": "^1.0.7",
"esprima": "~ 2.0.0" "esprima": "^4.0.0"
} }
}, },
"nodestalker": { "nodestalker": {
"version": "0.1.21", "version": "0.1.22",
"resolved": "https://registry.npmjs.org/nodestalker/-/nodestalker-0.1.21.tgz", "resolved": "https://registry.npmjs.org/nodestalker/-/nodestalker-0.1.22.tgz",
"integrity": "sha1-frUbWnbdq1Xau5uxNScCoigJUvk=", "integrity": "sha512-yRFJgkO9BkGybKOLmjum4WAHeaSDbvWA7eC9RpHlxkGcsi7yZbsLo9BTHANbWlSbbQtWkkO0Lwyt4JKsjGAj1Q==",
"requires": { "requires": {
"js-yaml": "3.2.7" "js-yaml": "^3.13.1"
} }
}, },
"sprintf-js": { "sprintf-js": {

View File

@@ -8,8 +8,9 @@
"url": "git@github.com:clonos/cp.git" "url": "git@github.com:clonos/cp.git"
}, },
"dependencies": { "dependencies": {
"ws": "6.1.0", "js-yaml": ">=3.13.1",
"nodestalker": "0.1.21" "nodestalker": "^0.1.22",
"ws": "6.1.0"
}, },
"devDependencies": {}, "devDependencies": {},
"scripts": {}, "scripts": {},