Added vscodium

This commit is contained in:
Kristofers Solo
2022-04-28 21:17:01 +03:00
parent 837a479d82
commit d7dddc39ef
29139 changed files with 250215 additions and 45125 deletions

View File

@@ -0,0 +1,16 @@
The ISC License
Copyright (c) Isaac Z. Schlueter
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,42 @@
Browser-friendly inheritance fully compatible with standard node.js
[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).
This package exports standard `inherits` from node.js `util` module in
node environment, but also provides alternative browser-friendly
implementation through [browser
field](https://gist.github.com/shtylman/4339901). Alternative
implementation is a literal copy of standard one located in standalone
module to avoid requiring of `util`. It also has a shim for old
browsers with no `Object.create` support.
While keeping you sure you are using standard `inherits`
implementation in node.js environment, it allows bundlers such as
[browserify](https://github.com/substack/node-browserify) to not
include full `util` package to your client code if all you need is
just `inherits` function. It worth, because browser shim for `util`
package is large and `inherits` is often the single function you need
from it.
It's recommended to use this package instead of
`require('util').inherits` for any code that has chances to be used
not only in node.js but in browser too.
## usage
```js
var inherits = require('inherits');
// then use exactly as the standard one
```
## note on version ~1.0
Version ~1.0 had completely different motivation and is not compatible
neither with 2.0 nor with standard node.js `inherits`.
If you are using version ~1.0 and planning to switch to ~2.0, be
careful:
* new version uses `super_` instead of `super` for referencing
superclass
* new version overwrites current prototype while old one preserves any
existing fields on it

View File

@@ -0,0 +1,9 @@
try {
var util = require('util');
/* istanbul ignore next */
if (typeof util.inherits !== 'function') throw '';
module.exports = util.inherits;
} catch (e) {
/* istanbul ignore next */
module.exports = require('./inherits_browser.js');
}

View File

@@ -0,0 +1,27 @@
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}

View File

@@ -0,0 +1,29 @@
{
"name": "inherits",
"description": "Browser-friendly inheritance fully compatible with standard node.js inherits()",
"version": "2.0.4",
"keywords": [
"inheritance",
"class",
"klass",
"oop",
"object-oriented",
"inherits",
"browser",
"browserify"
],
"main": "./inherits.js",
"browser": "./inherits_browser.js",
"repository": "git://github.com/isaacs/inherits",
"license": "ISC",
"scripts": {
"test": "tap"
},
"devDependencies": {
"tap": "^14.2.4"
},
"files": [
"inherits.js",
"inherits_browser.js"
]
}

View File

@@ -0,0 +1 @@
node_modules

View File

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

View File

@@ -0,0 +1,15 @@
# path
This is an exact copy of the NodeJS path module published to the NPM registry.
[Documentation](http://nodejs.org/docs/latest/api/path.html)
## Install
```sh
$ npm install --save path
```
## License
MIT

View File

@@ -0,0 +1,24 @@
{
"author": {
"name": "Joyent",
"url": "http://www.joyent.com"
},
"name": "path",
"description": "Node.JS path module",
"keywords": [
"ender",
"path"
],
"license": "MIT",
"version": "0.12.7",
"homepage": "http://nodejs.org/docs/latest/api/path.html",
"repository": {
"type": "git",
"url": "git://github.com/jinder/path.git"
},
"main": "./path.js",
"dependencies": {
"process": "^0.11.1",
"util": "^0.10.3"
}
}

View File

@@ -0,0 +1,628 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var isWindows = process.platform === 'win32';
var util = require('util');
// resolves . and .. elements in a path array with directory names there
// must be no slashes or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
var res = [];
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
// ignore empty parts
if (!p || p === '.')
continue;
if (p === '..') {
if (res.length && res[res.length - 1] !== '..') {
res.pop();
} else if (allowAboveRoot) {
res.push('..');
}
} else {
res.push(p);
}
}
return res;
}
// returns an array with empty elements removed from either end of the input
// array or the original array if no elements need to be removed
function trimArray(arr) {
var lastIndex = arr.length - 1;
var start = 0;
for (; start <= lastIndex; start++) {
if (arr[start])
break;
}
var end = lastIndex;
for (; end >= 0; end--) {
if (arr[end])
break;
}
if (start === 0 && end === lastIndex)
return arr;
if (start > end)
return [];
return arr.slice(start, end + 1);
}
// Regex to split a windows path into three parts: [*, device, slash,
// tail] windows-only
var splitDeviceRe =
/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
// Regex to split the tail part of the above into [*, dir, basename, ext]
var splitTailRe =
/^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
var win32 = {};
// Function to split a filename into [root, dir, basename, ext]
function win32SplitPath(filename) {
// Separate device+slash from tail
var result = splitDeviceRe.exec(filename),
device = (result[1] || '') + (result[2] || ''),
tail = result[3] || '';
// Split the tail into dir, basename and extension
var result2 = splitTailRe.exec(tail),
dir = result2[1],
basename = result2[2],
ext = result2[3];
return [device, dir, basename, ext];
}
function win32StatPath(path) {
var result = splitDeviceRe.exec(path),
device = result[1] || '',
isUnc = !!device && device[1] !== ':';
return {
device: device,
isUnc: isUnc,
isAbsolute: isUnc || !!result[2], // UNC paths are always absolute
tail: result[3]
};
}
function normalizeUNCRoot(device) {
return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\');
}
// path.resolve([from ...], to)
win32.resolve = function() {
var resolvedDevice = '',
resolvedTail = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1; i--) {
var path;
if (i >= 0) {
path = arguments[i];
} else if (!resolvedDevice) {
path = process.cwd();
} else {
// Windows has the concept of drive-specific current working
// directories. If we've resolved a drive letter but not yet an
// absolute path, get cwd for that drive. We're sure the device is not
// an unc path at this points, because unc paths are always absolute.
path = process.env['=' + resolvedDevice];
// Verify that a drive-local cwd was found and that it actually points
// to our drive. If not, default to the drive's root.
if (!path || path.substr(0, 3).toLowerCase() !==
resolvedDevice.toLowerCase() + '\\') {
path = resolvedDevice + '\\';
}
}
// Skip empty and invalid entries
if (!util.isString(path)) {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
var result = win32StatPath(path),
device = result.device,
isUnc = result.isUnc,
isAbsolute = result.isAbsolute,
tail = result.tail;
if (device &&
resolvedDevice &&
device.toLowerCase() !== resolvedDevice.toLowerCase()) {
// This path points to another device so it is not applicable
continue;
}
if (!resolvedDevice) {
resolvedDevice = device;
}
if (!resolvedAbsolute) {
resolvedTail = tail + '\\' + resolvedTail;
resolvedAbsolute = isAbsolute;
}
if (resolvedDevice && resolvedAbsolute) {
break;
}
}
// Convert slashes to backslashes when `resolvedDevice` points to an UNC
// root. Also squash multiple slashes into a single one where appropriate.
if (isUnc) {
resolvedDevice = normalizeUNCRoot(resolvedDevice);
}
// At this point the path should be resolved to a full absolute path,
// but handle relative paths to be safe (might happen when process.cwd()
// fails)
// Normalize the tail path
resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/),
!resolvedAbsolute).join('\\');
return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
'.';
};
win32.normalize = function(path) {
var result = win32StatPath(path),
device = result.device,
isUnc = result.isUnc,
isAbsolute = result.isAbsolute,
tail = result.tail,
trailingSlash = /[\\\/]$/.test(tail);
// Normalize the tail path
tail = normalizeArray(tail.split(/[\\\/]+/), !isAbsolute).join('\\');
if (!tail && !isAbsolute) {
tail = '.';
}
if (tail && trailingSlash) {
tail += '\\';
}
// Convert slashes to backslashes when `device` points to an UNC root.
// Also squash multiple slashes into a single one where appropriate.
if (isUnc) {
device = normalizeUNCRoot(device);
}
return device + (isAbsolute ? '\\' : '') + tail;
};
win32.isAbsolute = function(path) {
return win32StatPath(path).isAbsolute;
};
win32.join = function() {
var paths = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!util.isString(arg)) {
throw new TypeError('Arguments to path.join must be strings');
}
if (arg) {
paths.push(arg);
}
}
var joined = paths.join('\\');
// Make sure that the joined path doesn't start with two slashes, because
// normalize() will mistake it for an UNC path then.
//
// This step is skipped when it is very clear that the user actually
// intended to point at an UNC path. This is assumed when the first
// non-empty string arguments starts with exactly two slashes followed by
// at least one more non-slash character.
//
// Note that for normalize() to treat a path as an UNC path it needs to
// have at least 2 components, so we don't filter for that here.
// This means that the user can use join to construct UNC paths from
// a server name and a share name; for example:
// path.join('//server', 'share') -> '\\\\server\\share\')
if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) {
joined = joined.replace(/^[\\\/]{2,}/, '\\');
}
return win32.normalize(joined);
};
// path.relative(from, to)
// it will solve the relative path from 'from' to 'to', for instance:
// from = 'C:\\orandea\\test\\aaa'
// to = 'C:\\orandea\\impl\\bbb'
// The output of the function should be: '..\\..\\impl\\bbb'
win32.relative = function(from, to) {
from = win32.resolve(from);
to = win32.resolve(to);
// windows is not case sensitive
var lowerFrom = from.toLowerCase();
var lowerTo = to.toLowerCase();
var toParts = trimArray(to.split('\\'));
var lowerFromParts = trimArray(lowerFrom.split('\\'));
var lowerToParts = trimArray(lowerTo.split('\\'));
var length = Math.min(lowerFromParts.length, lowerToParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (lowerFromParts[i] !== lowerToParts[i]) {
samePartsLength = i;
break;
}
}
if (samePartsLength == 0) {
return to;
}
var outputParts = [];
for (var i = samePartsLength; i < lowerFromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('\\');
};
win32._makeLong = function(path) {
// Note: this will *probably* throw somewhere.
if (!util.isString(path))
return path;
if (!path) {
return '';
}
var resolvedPath = win32.resolve(path);
if (/^[a-zA-Z]\:\\/.test(resolvedPath)) {
// path is local filesystem path, which needs to be converted
// to long UNC path.
return '\\\\?\\' + resolvedPath;
} else if (/^\\\\[^?.]/.test(resolvedPath)) {
// path is network UNC path, which needs to be converted
// to long UNC path.
return '\\\\?\\UNC\\' + resolvedPath.substring(2);
}
return path;
};
win32.dirname = function(path) {
var result = win32SplitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
win32.basename = function(path, ext) {
var f = win32SplitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
win32.extname = function(path) {
return win32SplitPath(path)[3];
};
win32.format = function(pathObject) {
if (!util.isObject(pathObject)) {
throw new TypeError(
"Parameter 'pathObject' must be an object, not " + typeof pathObject
);
}
var root = pathObject.root || '';
if (!util.isString(root)) {
throw new TypeError(
"'pathObject.root' must be a string or undefined, not " +
typeof pathObject.root
);
}
var dir = pathObject.dir;
var base = pathObject.base || '';
if (!dir) {
return base;
}
if (dir[dir.length - 1] === win32.sep) {
return dir + base;
}
return dir + win32.sep + base;
};
win32.parse = function(pathString) {
if (!util.isString(pathString)) {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = win32SplitPath(pathString);
if (!allParts || allParts.length !== 4) {
throw new TypeError("Invalid path '" + pathString + "'");
}
return {
root: allParts[0],
dir: allParts[0] + allParts[1].slice(0, -1),
base: allParts[2],
ext: allParts[3],
name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
};
};
win32.sep = '\\';
win32.delimiter = ';';
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var posix = {};
function posixSplitPath(filename) {
return splitPathRe.exec(filename).slice(1);
}
// path.resolve([from ...], to)
// posix version
posix.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (!util.isString(path)) {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path[0] === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(resolvedPath.split('/'),
!resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
posix.normalize = function(path) {
var isAbsolute = posix.isAbsolute(path),
trailingSlash = path && path[path.length - 1] === '/';
// Normalize the path
path = normalizeArray(path.split('/'), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
posix.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
posix.join = function() {
var path = '';
for (var i = 0; i < arguments.length; i++) {
var segment = arguments[i];
if (!util.isString(segment)) {
throw new TypeError('Arguments to path.join must be strings');
}
if (segment) {
if (!path) {
path += segment;
} else {
path += '/' + segment;
}
}
}
return posix.normalize(path);
};
// path.relative(from, to)
// posix version
posix.relative = function(from, to) {
from = posix.resolve(from).substr(1);
to = posix.resolve(to).substr(1);
var fromParts = trimArray(from.split('/'));
var toParts = trimArray(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
posix._makeLong = function(path) {
return path;
};
posix.dirname = function(path) {
var result = posixSplitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
posix.basename = function(path, ext) {
var f = posixSplitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
posix.extname = function(path) {
return posixSplitPath(path)[3];
};
posix.format = function(pathObject) {
if (!util.isObject(pathObject)) {
throw new TypeError(
"Parameter 'pathObject' must be an object, not " + typeof pathObject
);
}
var root = pathObject.root || '';
if (!util.isString(root)) {
throw new TypeError(
"'pathObject.root' must be a string or undefined, not " +
typeof pathObject.root
);
}
var dir = pathObject.dir ? pathObject.dir + posix.sep : '';
var base = pathObject.base || '';
return dir + base;
};
posix.parse = function(pathString) {
if (!util.isString(pathString)) {
throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString
);
}
var allParts = posixSplitPath(pathString);
if (!allParts || allParts.length !== 4) {
throw new TypeError("Invalid path '" + pathString + "'");
}
allParts[1] = allParts[1] || '';
allParts[2] = allParts[2] || '';
allParts[3] = allParts[3] || '';
return {
root: allParts[0],
dir: allParts[0] + allParts[1].slice(0, -1),
base: allParts[2],
ext: allParts[3],
name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
};
};
posix.sep = '/';
posix.delimiter = ':';
if (isWindows)
module.exports = win32;
else /* posix */
module.exports = posix;
module.exports.posix = posix;
module.exports.win32 = win32;

View File

@@ -0,0 +1,21 @@
{
extends: "eslint:recommended",
"env": {
"node": true,
"browser": true,
"es6" : true,
"mocha": true
},
"rules": {
"indent": [2, 4],
"brace-style": [2, "1tbs"],
"quotes": [2, "single"],
"no-console": 0,
"no-shadow": 0,
"no-use-before-define": [2, "nofunc"],
"no-underscore-dangle": 0,
"no-constant-condition": 0,
"space-after-function-name": 0,
"consistent-return": 0
}
}

View File

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

View File

@@ -0,0 +1,26 @@
# process
```require('process');``` just like any other module.
Works in node.js and browsers via the browser.js shim provided with the module.
## browser implementation
The goal of this module is not to be a full-fledged alternative to the builtin process module. This module mostly exists to provide the nextTick functionality and little more. We keep this module lean because it will often be included by default by tools like browserify when it detects a module has used the `process` global.
It also exposes a "browser" member (i.e. `process.browser`) which is `true` in this implementation but `undefined` in node. This can be used in isomorphic code that adjusts it's behavior depending on which environment it's running in.
If you are looking to provide other process methods, I suggest you monkey patch them onto the process global in your app. A list of user created patches is below.
* [hrtime](https://github.com/kumavis/browser-process-hrtime)
* [stdout](https://github.com/kumavis/browser-stdout)
## package manager notes
If you are writing a bundler to package modules for client side use, make sure you use the ```browser``` field hint in package.json.
See https://gist.github.com/4339901 for details.
The [browserify](https://github.com/substack/node-browserify) module will properly handle this field when bundling your files.

View File

@@ -0,0 +1,184 @@
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

View File

@@ -0,0 +1,2 @@
// for now just expose the builtin process global from node.js
module.exports = global.process;

View File

@@ -0,0 +1,27 @@
{
"author": "Roman Shtylman <shtylman@gmail.com>",
"name": "process",
"description": "process information for node.js and browsers",
"keywords": [
"process"
],
"scripts": {
"test": "mocha test.js",
"browser": "zuul --no-coverage --ui mocha-bdd --local 8080 -- test.js"
},
"version": "0.11.10",
"repository": {
"type": "git",
"url": "git://github.com/shtylman/node-process.git"
},
"license": "MIT",
"browser": "./browser.js",
"main": "./index.js",
"engines": {
"node": ">= 0.6.0"
},
"devDependencies": {
"mocha": "2.2.1",
"zuul": "^3.10.3"
}
}

View File

@@ -0,0 +1,199 @@
var assert = require('assert');
var ourProcess = require('./browser');
describe('test against our process', function () {
test(ourProcess);
});
if (!process.browser) {
describe('test against node', function () {
test(process);
});
vmtest();
}
function test (ourProcess) {
describe('test arguments', function () {
it ('works', function (done) {
var order = 0;
ourProcess.nextTick(function (num) {
assert.equal(num, order++, 'first one works');
ourProcess.nextTick(function (num) {
assert.equal(num, order++, 'recursive one is 4th');
}, 3);
}, 0);
ourProcess.nextTick(function (num) {
assert.equal(num, order++, 'second one starts');
ourProcess.nextTick(function (num) {
assert.equal(num, order++, 'this is third');
ourProcess.nextTick(function (num) {
assert.equal(num, order++, 'this is last');
done();
}, 5);
}, 4);
}, 1);
ourProcess.nextTick(function (num) {
assert.equal(num, order++, '3rd schedualed happens after the error');
}, 2);
});
});
if (!process.browser) {
describe('test errors', function (t) {
it ('works', function (done) {
var order = 0;
process.removeAllListeners('uncaughtException');
process.once('uncaughtException', function(err) {
assert.equal(2, order++, 'error is third');
ourProcess.nextTick(function () {
assert.equal(5, order++, 'schedualed in error is last');
done();
});
});
ourProcess.nextTick(function () {
assert.equal(0, order++, 'first one works');
ourProcess.nextTick(function () {
assert.equal(4, order++, 'recursive one is 4th');
});
});
ourProcess.nextTick(function () {
assert.equal(1, order++, 'second one starts');
throw(new Error('an error is thrown'));
});
ourProcess.nextTick(function () {
assert.equal(3, order++, '3rd schedualed happens after the error');
});
});
});
}
describe('rename globals', function (t) {
var oldTimeout = setTimeout;
var oldClear = clearTimeout;
it('clearTimeout', function (done){
var ok = true;
clearTimeout = function () {
ok = false;
}
var ran = false;
function cleanup() {
clearTimeout = oldClear;
var err;
try {
assert.ok(ok, 'fake clearTimeout ran');
assert.ok(ran, 'should have run');
} catch (e) {
err = e;
}
done(err);
}
setTimeout(cleanup, 1000);
ourProcess.nextTick(function () {
ran = true;
});
});
it('just setTimeout', function (done){
setTimeout = function () {
setTimeout = oldTimeout;
try {
assert.ok(false, 'fake setTimeout called')
} catch (e) {
done(e);
}
}
ourProcess.nextTick(function () {
setTimeout = oldTimeout;
done();
});
});
});
}
function vmtest() {
var vm = require('vm');
var fs = require('fs');
var process = fs.readFileSync('./browser.js', {encoding: 'utf8'});
describe('should work in vm in strict mode with no globals', function () {
it('should parse', function (done) {
var str = '"use strict";var module = {exports:{}};';
str += process;
str += 'this.works = process.browser;';
var script = new vm.Script(str);
var context = {
works: false
};
script.runInNewContext(context);
assert.ok(context.works);
done();
});
it('setTimeout throws error', function (done) {
var str = '"use strict";var module = {exports:{}};';
str += process;
str += 'try {process.nextTick(function () {})} catch (e){this.works = e;}';
var script = new vm.Script(str);
var context = {
works: false
};
script.runInNewContext(context);
assert.ok(context.works);
done();
});
it('should generally work', function (done) {
var str = '"use strict";var module = {exports:{}};';
str += process;
str += 'process.nextTick(function () {assert.ok(true);done();})';
var script = new vm.Script(str);
var context = {
clearTimeout: clearTimeout,
setTimeout: setTimeout,
done: done,
assert: assert
};
script.runInNewContext(context);
});
it('late defs setTimeout', function (done) {
var str = '"use strict";var module = {exports:{}};';
str += process;
str += 'var setTimeout = hiddenSetTimeout;process.nextTick(function () {assert.ok(true);done();})';
var script = new vm.Script(str);
var context = {
clearTimeout: clearTimeout,
hiddenSetTimeout: setTimeout,
done: done,
assert: assert
};
script.runInNewContext(context);
});
it('late defs clearTimeout', function (done) {
var str = '"use strict";var module = {exports:{}};';
str += process;
str += 'var clearTimeout = hiddenClearTimeout;process.nextTick(function () {assert.ok(true);done();})';
var script = new vm.Script(str);
var context = {
hiddenClearTimeout: clearTimeout,
setTimeout: setTimeout,
done: done,
assert: assert
};
script.runInNewContext(context);
});
it('late defs setTimeout and then redefine', function (done) {
var str = '"use strict";var module = {exports:{}};';
str += process;
str += 'var setTimeout = hiddenSetTimeout;process.nextTick(function () {setTimeout = function (){throw new Error("foo")};hiddenSetTimeout(function(){process.nextTick(function (){assert.ok(true);done();});});});';
var script = new vm.Script(str);
var context = {
clearTimeout: clearTimeout,
hiddenSetTimeout: setTimeout,
done: done,
assert: assert
};
script.runInNewContext(context);
});
});
}

View File

@@ -0,0 +1,18 @@
{
"node": true,
"browser": true,
"browserify": true,
"curly": true,
"eqeqeq": true,
"eqnull": false,
"latedef": "nofunc",
"newcap": true,
"noarg": true,
"undef": true,
"strict": true,
"trailing": true,
"smarttabs": true,
"indent": 2,
"quotmark": true,
"laxbreak": true
}

View File

@@ -0,0 +1,7 @@
language: node_js
sudo: false
node_js:
- "4.1"
- "4.0"
- "0.12"
- "0.10"

View File

@@ -0,0 +1,116 @@
2.3.0 - July 13 2015
====================
* Correctly handle quoted keys ([#21](https://github.com/BinaryMuse/toml-node/issues/21))
2.2.3 - June 8 2015
===================
* Support empty inline tables ([#24](https://github.com/BinaryMuse/toml-node/issues/24))
* Do not allow implicit table definitions to replace value ([#23](https://github.com/BinaryMuse/toml-node/issues/23))
* Don't allow tables to replace inline tables ([#25](https://github.com/BinaryMuse/toml-node/issues/25))
2.2.2 - April 3 2015
====================
* Correctly handle newlines at beginning of string ([#22](https://github.com/BinaryMuse/toml-node/issues/22))
2.2.1 - March 17 2015
=====================
* Parse dates generated by Date#toISOString() ([#20](https://github.com/BinaryMuse/toml-node/issues/20))
2.2.0 - Feb 26 2015
===================
* Support TOML spec v0.4.0
2.1.0 - Jan 7 2015
==================
* Support TOML spec v0.3.1
2.0.6 - May 23 2014
===================
### Bug Fixes
* Fix support for empty arrays with newlines ([#13](https://github.com/BinaryMuse/toml-node/issues/13))
2.0.5 - May 5 2014
==================
### Bug Fixes
* Fix loop iteration leak, by [sebmck](https://github.com/sebmck) ([#12](https://github.com/BinaryMuse/toml-node/pull/12))
### Development
* Tests now run JSHint on `lib/compiler.js`
2.0.4 - Mar 9 2014
==================
### Bug Fixes
* Fix failure on duplicate table name inside table array ([#11](https://github.com/BinaryMuse/toml-node/issues/11))
2.0.2 - Feb 23 2014
===================
### Bug Fixes
* Fix absence of errors when table path starts or ends with period
2.0.1 - Feb 23 2014
===================
### Bug Fixes
* Fix incorrect messaging in array type errors
* Fix missing error when overwriting key with table array
2.0.0 - Feb 23 2014
===================
### Features
* Add support for [version 0.2 of the TOML spec](https://github.com/mojombo/toml/blob/master/versions/toml-v0.2.0.md) ([#9](https://github.com/BinaryMuse/toml-node/issues/9))
### Internals
* Upgrade to PEG.js v0.8 and rewrite compiler; parser is now considerably faster (from ~7000ms to ~1000ms to parse `example.toml` 1000 times on Node.js v0.10)
1.0.4 - Aug 17 2013
===================
### Bug Fixes
* Fix support for empty arrays
1.0.3 - Aug 17 2013
===================
### Bug Fixes
* Fix typo in array type error message
* Fix single-element arrays with no trailing commas
1.0.2 - Aug 17 2013
===================
### Bug Fixes
* Fix errors on lines that contain only whitespace ([#7](https://github.com/BinaryMuse/toml-node/issues/7))
1.0.1 - Aug 17 2013
===================
### Internals
* Remove old code remaining from the remove streaming API
1.0.0 - Aug 17 2013
===================
Initial stable release

View File

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

View File

@@ -0,0 +1,93 @@
TOML Parser for Node.js
=======================
[![Build Status](https://travis-ci.org/BinaryMuse/toml-node.png?branch=master)](https://travis-ci.org/BinaryMuse/toml-node)
[![NPM](https://nodei.co/npm/toml.png?downloads=true)](https://nodei.co/npm/toml/)
If you haven't heard of TOML, well you're just missing out. [Go check it out now.](https://github.com/mojombo/toml) Back? Good.
TOML Spec Support
-----------------
toml-node supports version 0.4.0 the TOML spec as specified by [mojombo/toml@v0.4.0](https://github.com/mojombo/toml/blob/master/versions/en/toml-v0.4.0.md)
Installation
------------
toml-node is available via npm.
npm install toml
toml-node also works with browser module bundlers like Browserify and webpack.
Usage
-----
### Standalone
Say you have some awesome TOML in a variable called `someTomlString`. Maybe it came from the web; maybe it came from a file; wherever it came from, it came asynchronously! Let's turn that sucker into a JavaScript object.
```javascript
var toml = require('toml');
var data = toml.parse(someTomlString);
console.dir(data);
```
`toml.parse` throws an exception in the case of a parsing error; such exceptions have a `line` and `column` property on them to help identify the offending text.
```javascript
try {
toml.parse(someCrazyKnuckleHeadedTrblToml);
} catch (e) {
console.error("Parsing error on line " + e.line + ", column " + e.column +
": " + e.message);
}
```
### Streaming
As of toml-node version 1.0, the streaming interface has been removed. Instead, use a module like [concat-stream](https://npmjs.org/package/concat-stream):
```javascript
var toml = require('toml');
var concat = require('concat-stream');
var fs = require('fs');
fs.createReadStream('tomlFile.toml', 'utf8').pipe(concat(function(data) {
var parsed = toml.parse(data);
}));
```
Thanks [@ForbesLindesay](https://github.com/ForbesLindesay) for the suggestion.
### Requiring with Node.js
You can use the [toml-require package](https://github.com/BinaryMuse/toml-require) to `require()` your `.toml` files with Node.js
Live Demo
---------
You can experiment with TOML online at http://binarymuse.github.io/toml-node/, which uses the latest version of this library.
Building & Testing
------------------
toml-node uses [the PEG.js parser generator](http://pegjs.majda.cz/).
npm install
npm run build
npm test
Any changes to `src/toml.peg` requires a regeneration of the parser with `npm run build`.
toml-node is tested on Travis CI and is tested against:
* Node 0.10
* Node 0.12
* Latest stable io.js
License
-------
toml-node is licensed under the MIT license agreement. See the LICENSE file for more information.

View File

@@ -0,0 +1,12 @@
var toml = require('./index');
var fs = require('fs');
var data = fs.readFileSync('./test/example.toml', 'utf8');
var iterations = 1000;
var start = new Date();
for(var i = 0; i < iterations; i++) {
toml.parse(data);
}
var end = new Date();
console.log("%s iterations in %sms", iterations, end - start);

View File

@@ -0,0 +1,9 @@
var parser = require('./lib/parser');
var compiler = require('./lib/compiler');
module.exports = {
parse: function(input) {
var nodes = parser.parse(input.toString());
return compiler.compile(nodes);
}
};

View File

@@ -0,0 +1,195 @@
"use strict";
function compile(nodes) {
var assignedPaths = [];
var valueAssignments = [];
var currentPath = "";
var data = Object.create(null);
var context = data;
var arrayMode = false;
return reduce(nodes);
function reduce(nodes) {
var node;
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
switch (node.type) {
case "Assign":
assign(node);
break;
case "ObjectPath":
setPath(node);
break;
case "ArrayPath":
addTableArray(node);
break;
}
}
return data;
}
function genError(err, line, col) {
var ex = new Error(err);
ex.line = line;
ex.column = col;
throw ex;
}
function assign(node) {
var key = node.key;
var value = node.value;
var line = node.line;
var column = node.column;
var fullPath;
if (currentPath) {
fullPath = currentPath + "." + key;
} else {
fullPath = key;
}
if (typeof context[key] !== "undefined") {
genError("Cannot redefine existing key '" + fullPath + "'.", line, column);
}
context[key] = reduceValueNode(value);
if (!pathAssigned(fullPath)) {
assignedPaths.push(fullPath);
valueAssignments.push(fullPath);
}
}
function pathAssigned(path) {
return assignedPaths.indexOf(path) !== -1;
}
function reduceValueNode(node) {
if (node.type === "Array") {
return reduceArrayWithTypeChecking(node.value);
} else if (node.type === "InlineTable") {
return reduceInlineTableNode(node.value);
} else {
return node.value;
}
}
function reduceInlineTableNode(values) {
var obj = Object.create(null);
for (var i = 0; i < values.length; i++) {
var val = values[i];
if (val.value.type === "InlineTable") {
obj[val.key] = reduceInlineTableNode(val.value.value);
} else if (val.type === "InlineTableValue") {
obj[val.key] = reduceValueNode(val.value);
}
}
return obj;
}
function setPath(node) {
var path = node.value;
var quotedPath = path.map(quoteDottedString).join(".");
var line = node.line;
var column = node.column;
if (pathAssigned(quotedPath)) {
genError("Cannot redefine existing key '" + path + "'.", line, column);
}
assignedPaths.push(quotedPath);
context = deepRef(data, path, Object.create(null), line, column);
currentPath = path;
}
function addTableArray(node) {
var path = node.value;
var quotedPath = path.map(quoteDottedString).join(".");
var line = node.line;
var column = node.column;
if (!pathAssigned(quotedPath)) {
assignedPaths.push(quotedPath);
}
assignedPaths = assignedPaths.filter(function(p) {
return p.indexOf(quotedPath) !== 0;
});
assignedPaths.push(quotedPath);
context = deepRef(data, path, [], line, column);
currentPath = quotedPath;
if (context instanceof Array) {
var newObj = Object.create(null);
context.push(newObj);
context = newObj;
} else {
genError("Cannot redefine existing key '" + path + "'.", line, column);
}
}
// Given a path 'a.b.c', create (as necessary) `start.a`,
// `start.a.b`, and `start.a.b.c`, assigning `value` to `start.a.b.c`.
// If `a` or `b` are arrays and have items in them, the last item in the
// array is used as the context for the next sub-path.
function deepRef(start, keys, value, line, column) {
var traversed = [];
var traversedPath = "";
var path = keys.join(".");
var ctx = start;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
traversed.push(key);
traversedPath = traversed.join(".");
if (typeof ctx[key] === "undefined") {
if (i === keys.length - 1) {
ctx[key] = value;
} else {
ctx[key] = Object.create(null);
}
} else if (i !== keys.length - 1 && valueAssignments.indexOf(traversedPath) > -1) {
// already a non-object value at key, can't be used as part of a new path
genError("Cannot redefine existing key '" + traversedPath + "'.", line, column);
}
ctx = ctx[key];
if (ctx instanceof Array && ctx.length && i < keys.length - 1) {
ctx = ctx[ctx.length - 1];
}
}
return ctx;
}
function reduceArrayWithTypeChecking(array) {
// Ensure that all items in the array are of the same type
var firstType = null;
for (var i = 0; i < array.length; i++) {
var node = array[i];
if (firstType === null) {
firstType = node.type;
} else {
if (node.type !== firstType) {
genError("Cannot add value of type " + node.type + " to array of type " +
firstType + ".", node.line, node.column);
}
}
}
// Recursively reduce array of nodes into array of the nodes' values
return array.map(reduceValueNode);
}
function quoteDottedString(str) {
if (str.indexOf(".") > -1) {
return "\"" + str + "\"";
} else {
return str;
}
}
}
module.exports = {
compile: compile
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,24 @@
{
"name": "toml",
"version": "3.0.0",
"description": "TOML parser for Node.js (parses TOML spec v0.4.0)",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"build": "pegjs --cache src/toml.pegjs lib/parser.js",
"test": "jshint lib/compiler.js && nodeunit test/test_*.js",
"prepublish": "npm run build"
},
"repository": "git://github.com/BinaryMuse/toml-node.git",
"keywords": [
"toml",
"parser"
],
"author": "Michelle Tilley <michelle@michelletilley.net>",
"license": "MIT",
"devDependencies": {
"jshint": "*",
"nodeunit": "~0.9.0",
"pegjs": "~0.8.0"
}
}

View File

@@ -0,0 +1,231 @@
{
var nodes = [];
function genError(err, line, col) {
var ex = new Error(err);
ex.line = line;
ex.column = col;
throw ex;
}
function addNode(node) {
nodes.push(node);
}
function node(type, value, line, column, key) {
var obj = { type: type, value: value, line: line(), column: column() };
if (key) obj.key = key;
return obj;
}
function convertCodePoint(str, line, col) {
var num = parseInt("0x" + str);
if (
!isFinite(num) ||
Math.floor(num) != num ||
num < 0 ||
num > 0x10FFFF ||
(num > 0xD7FF && num < 0xE000)
) {
genError("Invalid Unicode escape code: " + str, line, col);
} else {
return fromCodePoint(num);
}
}
function fromCodePoint() {
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
var result = '';
while (++index < length) {
var codePoint = Number(arguments[index]);
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
if (index + 1 == length || codeUnits.length > MAX_SIZE) {
result += String.fromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result;
}
}
start
= line* { return nodes }
line
= S* expr:expression S* comment* (NL+ / EOF)
/ S+ (NL+ / EOF)
/ NL
expression
= comment / path / tablearray / assignment
comment
= '#' (!(NL / EOF) .)*
path
= '[' S* name:table_key S* ']' { addNode(node('ObjectPath', name, line, column)) }
tablearray
= '[' '[' S* name:table_key S* ']' ']' { addNode(node('ArrayPath', name, line, column)) }
table_key
= parts:dot_ended_table_key_part+ name:table_key_part { return parts.concat(name) }
/ name:table_key_part { return [name] }
table_key_part
= S* name:key S* { return name }
/ S* name:quoted_key S* { return name }
dot_ended_table_key_part
= S* name:key S* '.' S* { return name }
/ S* name:quoted_key S* '.' S* { return name }
assignment
= key:key S* '=' S* value:value { addNode(node('Assign', value, line, column, key)) }
/ key:quoted_key S* '=' S* value:value { addNode(node('Assign', value, line, column, key)) }
key
= chars:ASCII_BASIC+ { return chars.join('') }
quoted_key
= node:double_quoted_single_line_string { return node.value }
/ node:single_quoted_single_line_string { return node.value }
value
= string / datetime / float / integer / boolean / array / inline_table
string
= double_quoted_multiline_string
/ double_quoted_single_line_string
/ single_quoted_multiline_string
/ single_quoted_single_line_string
double_quoted_multiline_string
= '"""' NL? chars:multiline_string_char* '"""' { return node('String', chars.join(''), line, column) }
double_quoted_single_line_string
= '"' chars:string_char* '"' { return node('String', chars.join(''), line, column) }
single_quoted_multiline_string
= "'''" NL? chars:multiline_literal_char* "'''" { return node('String', chars.join(''), line, column) }
single_quoted_single_line_string
= "'" chars:literal_char* "'" { return node('String', chars.join(''), line, column) }
string_char
= ESCAPED / (!'"' char:. { return char })
literal_char
= (!"'" char:. { return char })
multiline_string_char
= ESCAPED / multiline_string_delim / (!'"""' char:. { return char})
multiline_string_delim
= '\\' NL NLS* { return '' }
multiline_literal_char
= (!"'''" char:. { return char })
float
= left:(float_text / integer_text) ('e' / 'E') right:integer_text { return node('Float', parseFloat(left + 'e' + right), line, column) }
/ text:float_text { return node('Float', parseFloat(text), line, column) }
float_text
= '+'? digits:(DIGITS '.' DIGITS) { return digits.join('') }
/ '-' digits:(DIGITS '.' DIGITS) { return '-' + digits.join('') }
integer
= text:integer_text { return node('Integer', parseInt(text, 10), line, column) }
integer_text
= '+'? digits:DIGIT+ !'.' { return digits.join('') }
/ '-' digits:DIGIT+ !'.' { return '-' + digits.join('') }
boolean
= 'true' { return node('Boolean', true, line, column) }
/ 'false' { return node('Boolean', false, line, column) }
array
= '[' array_sep* ']' { return node('Array', [], line, column) }
/ '[' value:array_value? ']' { return node('Array', value ? [value] : [], line, column) }
/ '[' values:array_value_list+ ']' { return node('Array', values, line, column) }
/ '[' values:array_value_list+ value:array_value ']' { return node('Array', values.concat(value), line, column) }
array_value
= array_sep* value:value array_sep* { return value }
array_value_list
= array_sep* value:value array_sep* ',' array_sep* { return value }
array_sep
= S / NL / comment
inline_table
= '{' S* values:inline_table_assignment* S* '}' { return node('InlineTable', values, line, column) }
inline_table_assignment
= S* key:key S* '=' S* value:value S* ',' S* { return node('InlineTableValue', value, line, column, key) }
/ S* key:key S* '=' S* value:value { return node('InlineTableValue', value, line, column, key) }
secfragment
= '.' digits:DIGITS { return "." + digits }
date
= date:(
DIGIT DIGIT DIGIT DIGIT
'-'
DIGIT DIGIT
'-'
DIGIT DIGIT
) { return date.join('') }
time
= time:(DIGIT DIGIT ':' DIGIT DIGIT ':' DIGIT DIGIT secfragment?) { return time.join('') }
time_with_offset
= time:(
DIGIT DIGIT ':' DIGIT DIGIT ':' DIGIT DIGIT secfragment?
('-' / '+')
DIGIT DIGIT ':' DIGIT DIGIT
) { return time.join('') }
datetime
= date:date 'T' time:time 'Z' { return node('Date', new Date(date + "T" + time + "Z"), line, column) }
/ date:date 'T' time:time_with_offset { return node('Date', new Date(date + "T" + time), line, column) }
S = [ \t]
NL = "\n" / "\r" "\n"
NLS = NL / S
EOF = !.
HEX = [0-9a-f]i
DIGIT = DIGIT_OR_UNDER
DIGIT_OR_UNDER = [0-9]
/ '_' { return "" }
ASCII_BASIC = [A-Za-z0-9_\-]
DIGITS = d:DIGIT_OR_UNDER+ { return d.join('') }
ESCAPED = '\\"' { return '"' }
/ '\\\\' { return '\\' }
/ '\\b' { return '\b' }
/ '\\t' { return '\t' }
/ '\\n' { return '\n' }
/ '\\f' { return '\f' }
/ '\\r' { return '\r' }
/ ESCAPED_UNICODE
ESCAPED_UNICODE = "\\U" digits:(HEX HEX HEX HEX HEX HEX HEX HEX) { return convertCodePoint(digits.join('')) }
/ "\\u" digits:(HEX HEX HEX HEX) { return convertCodePoint(digits.join('')) }

View File

@@ -0,0 +1,5 @@
[something]
awesome = "this is"
[something.awesome]
this = "isn't"

View File

@@ -0,0 +1,32 @@
# This is a TOML document. Boom.
title = "TOML Example"
[owner]
name = "Tom Preston-Werner"
organization = "GitHub"
bio = "GitHub Cofounder & CEO\n\tLikes \"tater tots\" and beer and backslashes: \\"
dob = 1979-05-27T07:32:00Z # First class dates? Why not?
[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8003 ]
connection_max = 5000
connection_min = -2 # Don't ask me how
max_temp = 87.1 # It's a float
min_temp = -17.76
enabled = true
[servers]
# You can indent as you please. Tabs or spaces. TOML don't care.
[servers.alpha]
ip = "10.0.0.1"
dc = "eqdc10"
[servers.beta]
ip = "10.0.0.2"
dc = "eqdc10"
[clients]
data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it

View File

@@ -0,0 +1,33 @@
# Test file for TOML
# Only this one tries to emulate a TOML file written by a user of the kind of parser writers probably hate
# This part you'll really hate
[the]
test_string = "You'll hate me after this - #" # " Annoying, isn't it?
[the.hard]
test_array = [ "] ", " # "] # ] There you go, parse this!
test_array2 = [ "Test #11 ]proved that", "Experiment #9 was a success" ]
# You didn't think it'd as easy as chucking out the last #, did you?
another_test_string = " Same thing, but with a string #"
harder_test_string = " And when \"'s are in the string, along with # \"" # "and comments are there too"
# Things will get harder
[the.hard."bit#"]
"what?" = "You don't think some user won't do that?"
multi_line_array = [
"]",
# ] Oh yes I did
]
# Each of the following keygroups/key value pairs should produce an error. Uncomment to them to test
#[error] if you didn't catch this, your parser is broken
#string = "Anything other than tabs, spaces and newline after a keygroup or key value pair has ended should produce an error unless it is a comment" like this
#array = [
# "This might most likely happen in multiline arrays",
# Like here,
# "or here,
# and here"
# ] End of array comment, forgot the #
#number = 3.14 pi <--again forgot the #

View File

@@ -0,0 +1,10 @@
name = { first = "Tom", last = "Preston-Werner" }
point = { x = 1, y = 2 }
nested = { x = { a = { b = 3 } } }
points = [ { x = 1, y = 2, z = 3 },
{ x = 7, y = 8, z = 9 },
{ x = 2, y = 4, z = 8 } ]
arrays = [ { x = [1, 2, 3], y = [4, 5, 6] },
{ x = [7, 8, 9], y = [0, 1, 2] } ]

View File

@@ -0,0 +1,5 @@
# What you see is what you get.
winpath = 'C:\Users\nodejs\templates'
winpath2 = '\\ServerX\admin$\system32\'
quoted = 'Tom "Dubs" Preston-Werner'
regex = '<\i\c*\s*>'

View File

@@ -0,0 +1,15 @@
# The following strings are byte-for-byte equivalent:
key1 = "The quick brown fox jumps over the lazy dog."
key2 = """
The quick brown \
fox jumps over \
the lazy dog."""
key3 = """\
The quick brown \
fox jumps over \
the lazy dog.\
"""

View File

@@ -0,0 +1,7 @@
regex2 = '''I [dw]on't need \d{2} apples'''
lines = '''
The first newline is
trimmed in raw strings.
All other whitespace
is preserved.
'''

View File

@@ -0,0 +1,6 @@
# The following strings are byte-for-byte equivalent:
key1 = "One\nTwo"
key2 = """One\nTwo"""
key3 = """
One
Two"""

View File

@@ -0,0 +1,22 @@
var fs = require('fs');
var parser = require('../index');
var codes = [
"# test\n my.key=\"value\"\nother = 101\nthird = -37",
"first = 1.2\nsecond = -56.02\nth = true\nfth = false",
"time = 1979-05-27T07:32:00Z",
"test = [\"one\", ]",
"test = [[1, 2,], [true, false,],]",
"[my.sub.path]\nkey = true\nother = -15.3\n[my.sub]\nkey=false",
"arry = [\"one\", \"two\",\"thr\nee\", \"\\u03EA\"]",
fs.readFileSync(__dirname + '/example.toml', 'utf8'),
fs.readFileSync(__dirname + '/hard_example.toml', 'utf8')
]
console.log("=============================================");
for(i in codes) {
var code = codes[i];
console.log(code + "\n");
console.log(JSON.stringify(parser.parse(code)));
console.log("=============================================");
}

View File

@@ -0,0 +1,10 @@
[[products]]
name = "Hammer"
sku = 738594937
[[products]]
[[products]]
name = "Nail"
sku = 284758393
color = "gray"

View File

@@ -0,0 +1,31 @@
[[fruit]]
name = "durian"
variety = []
[[fruit]]
name = "apple"
[fruit.physical]
color = "red"
shape = "round"
[[fruit.variety]]
name = "red delicious"
[[fruit.variety]]
name = "granny smith"
[[fruit]]
[[fruit]]
name = "banana"
[[fruit.variety]]
name = "plantain"
[[fruit]]
name = "orange"
[fruit.physical]
color = "orange"
shape = "round"

View File

@@ -0,0 +1,596 @@
var toml = require('../');
var fs = require('fs');
var assert = require("nodeunit").assert;
assert.parsesToml = function(tomlStr, expected) {
try {
var actual = toml.parse(tomlStr);
} catch (e) {
var errInfo = "line: " + e.line + ", column: " + e.column;
return assert.fail("TOML parse error: " + e.message, errInfo, null, "at", assert.parsesToml);
}
return assert.deepEqual(actual, expected);
};
var exampleExpected = {
title: "TOML Example",
owner: {
name: "Tom Preston-Werner",
organization: "GitHub",
bio: "GitHub Cofounder & CEO\n\tLikes \"tater tots\" and beer and backslashes: \\",
dob: new Date("1979-05-27T07:32:00Z")
},
database: {
server: "192.168.1.1",
ports: [8001, 8001, 8003],
connection_max: 5000,
connection_min: -2,
max_temp: 87.1,
min_temp: -17.76,
enabled: true
},
servers: {
alpha: {
ip: "10.0.0.1",
dc: "eqdc10"
},
beta: {
ip: "10.0.0.2",
dc: "eqdc10"
}
},
clients: {
data: [ ["gamma", "delta"], [1, 2] ]
}
};
var hardExampleExpected = {
the: {
hard: {
another_test_string: ' Same thing, but with a string #',
'bit#': {
multi_line_array: [']'],
'what?': "You don't think some user won't do that?"
},
harder_test_string: " And when \"'s are in the string, along with # \"",
test_array: ['] ', ' # '],
test_array2: ['Test #11 ]proved that', 'Experiment #9 was a success']
},
test_string: "You'll hate me after this - #"
}
};
var easyTableArrayExpected = {
"products": [
{ "name": "Hammer", "sku": 738594937 },
{ },
{ "name": "Nail", "sku": 284758393, "color": "gray" }
]
};
var hardTableArrayExpected = {
"fruit": [
{
"name": "durian",
"variety": []
},
{
"name": "apple",
"physical": {
"color": "red",
"shape": "round"
},
"variety": [
{ "name": "red delicious" },
{ "name": "granny smith" }
]
},
{},
{
"name": "banana",
"variety": [
{ "name": "plantain" }
]
},
{
"name": "orange",
"physical": {
"color": "orange",
"shape": "round"
}
}
]
}
var badInputs = [
'[error] if you didn\'t catch this, your parser is broken',
'string = "Anything other than tabs, spaces and newline after a table or key value pair has ended should produce an error unless it is a comment" like this',
'array = [\n \"This might most likely happen in multiline arrays\",\n Like here,\n \"or here,\n and here\"\n ] End of array comment, forgot the #',
'number = 3.14 pi <--again forgot the #'
];
exports.testParsesExample = function(test) {
var str = fs.readFileSync(__dirname + "/example.toml", 'utf-8')
test.parsesToml(str, exampleExpected);
test.done();
};
exports.testParsesHardExample = function(test) {
var str = fs.readFileSync(__dirname + "/hard_example.toml", 'utf-8')
test.parsesToml(str, hardExampleExpected);
test.done();
};
exports.testEasyTableArrays = function(test) {
var str = fs.readFileSync(__dirname + "/table_arrays_easy.toml", 'utf8')
test.parsesToml(str, easyTableArrayExpected);
test.done();
};
exports.testHarderTableArrays = function(test) {
var str = fs.readFileSync(__dirname + "/table_arrays_hard.toml", 'utf8')
test.parsesToml(str, hardTableArrayExpected);
test.done();
};
exports.testSupportsTrailingCommasInArrays = function(test) {
var str = 'arr = [1, 2, 3,]';
var expected = { arr: [1, 2, 3] };
test.parsesToml(str, expected);
test.done();
};
exports.testSingleElementArrayWithNoTrailingComma = function(test) {
var str = "a = [1]";
test.parsesToml(str, {
a: [1]
});
test.done();
};
exports.testEmptyArray = function(test) {
var str = "a = []";
test.parsesToml(str, {
a: []
});
test.done();
};
exports.testArrayWithWhitespace = function(test) {
var str = "[versions]\nfiles = [\n 3, \n 5 \n\n ]";
test.parsesToml(str, {
versions: {
files: [3, 5]
}
});
test.done();
};
exports.testEmptyArrayWithWhitespace = function(test) {
var str = "[versions]\nfiles = [\n \n ]";
test.parsesToml(str, {
versions: {
files: []
}
});
test.done();
};
exports.testDefineOnSuperkey = function(test) {
var str = "[a.b]\nc = 1\n\n[a]\nd = 2";
var expected = {
a: {
b: {
c: 1
},
d: 2
}
};
test.parsesToml(str, expected);
test.done();
};
exports.testWhitespace = function(test) {
var str = "a = 1\n \n b = 2 ";
test.parsesToml(str, {
a: 1, b: 2
});
test.done();
};
exports.testUnicode = function(test) {
var str = "str = \"My name is Jos\\u00E9\"";
test.parsesToml(str, {
str: "My name is Jos\u00E9"
});
var str = "str = \"My name is Jos\\U000000E9\"";
test.parsesToml(str, {
str: "My name is Jos\u00E9"
});
test.done();
};
exports.testMultilineStrings = function(test) {
var str = fs.readFileSync(__dirname + "/multiline_strings.toml", 'utf8');
test.parsesToml(str, {
key1: "One\nTwo",
key2: "One\nTwo",
key3: "One\nTwo"
});
test.done();
};
exports.testMultilineEatWhitespace = function(test) {
var str = fs.readFileSync(__dirname + "/multiline_eat_whitespace.toml", 'utf8');
test.parsesToml(str, {
key1: "The quick brown fox jumps over the lazy dog.",
key2: "The quick brown fox jumps over the lazy dog.",
key3: "The quick brown fox jumps over the lazy dog."
});
test.done();
};
exports.testLiteralStrings = function(test) {
var str = fs.readFileSync(__dirname + "/literal_strings.toml", 'utf8');
test.parsesToml(str, {
winpath: "C:\\Users\\nodejs\\templates",
winpath2: "\\\\ServerX\\admin$\\system32\\",
quoted: "Tom \"Dubs\" Preston-Werner",
regex: "<\\i\\c*\\s*>"
});
test.done();
};
exports.testMultilineLiteralStrings = function(test) {
var str = fs.readFileSync(__dirname + "/multiline_literal_strings.toml", 'utf8');
test.parsesToml(str, {
regex2: "I [dw]on't need \\d{2} apples",
lines: "The first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n"
});
test.done();
};
exports.testIntegerFormats = function(test) {
var str = "a = +99\nb = 42\nc = 0\nd = -17\ne = 1_000_001\nf = 1_2_3_4_5 # why u do dis";
test.parsesToml(str, {
a: 99,
b: 42,
c: 0,
d: -17,
e: 1000001,
f: 12345
});
test.done();
};
exports.testFloatFormats = function(test) {
var str = "a = +1.0\nb = 3.1415\nc = -0.01\n" +
"d = 5e+22\ne = 1e6\nf = -2E-2\n" +
"g = 6.626e-34\n" +
"h = 9_224_617.445_991_228_313\n" +
"i = 1e1_000";
test.parsesToml(str, {
a: 1.0,
b: 3.1415,
c: -0.01,
d: 5e22,
e: 1e6,
f: -2e-2,
g: 6.626e-34,
h: 9224617.445991228313,
i: 1e1000
});
test.done();
};
exports.testDate = function(test) {
var date = new Date("1979-05-27T07:32:00Z");
test.parsesToml("a = 1979-05-27T07:32:00Z", {
a: date
});
test.done();
};
exports.testDateWithOffset = function(test) {
var date1 = new Date("1979-05-27T07:32:00-07:00"),
date2 = new Date("1979-05-27T07:32:00+02:00");
test.parsesToml("a = 1979-05-27T07:32:00-07:00\nb = 1979-05-27T07:32:00+02:00", {
a: date1,
b: date2
});
test.done();
};
exports.testDateWithSecondFraction = function(test) {
var date = new Date("1979-05-27T00:32:00.999999-07:00");
test.parsesToml("a = 1979-05-27T00:32:00.999999-07:00", {
a: date
});
test.done();
};
exports.testDateFromIsoString = function(test) {
// https://github.com/BinaryMuse/toml-node/issues/20
var date = new Date(),
dateStr = date.toISOString(),
tomlStr = "a = " + dateStr;
test.parsesToml(tomlStr, {
a: date
});
test.done();
};
exports.testLeadingNewlines = function(test) {
// https://github.com/BinaryMuse/toml-node/issues/22
var str = "\ntest = \"ing\"";
test.parsesToml(str, {
test: "ing"
});
test.done();
};
exports.testInlineTables = function(test) {
var str = fs.readFileSync(__dirname + "/inline_tables.toml", 'utf8');
test.parsesToml(str, {
name: {
first: "Tom",
last: "Preston-Werner"
},
point: {
x: 1,
y: 2
},
nested: {
x: {
a: {
b: 3
}
}
},
points: [
{ x: 1, y: 2, z: 3 },
{ x: 7, y: 8, z: 9 },
{ x: 2, y: 4, z: 8 }
],
arrays: [
{ x: [1, 2, 3], y: [4, 5, 6] },
{ x: [7, 8, 9], y: [0, 1, 2] }
]
});
test.done();
};
exports.testEmptyInlineTables = function(test) {
// https://github.com/BinaryMuse/toml-node/issues/24
var str = "a = { }";
test.parsesToml(str, {
a: {}
});
test.done();
};
exports.testKeyNamesWithWhitespaceAroundStartAndFinish = function(test) {
var str = "[ a ]\nb = 1";
test.parsesToml(str, {
a: {
b: 1
}
});
test.done();
};
exports.testKeyNamesWithWhitespaceAroundDots = function(test) {
var str = "[ a . b . c]\nd = 1";
test.parsesToml(str, {
a: {
b: {
c: {
d: 1
}
}
}
});
test.done();
};
exports.testSimpleQuotedKeyNames = function(test) {
var str = "[\"ʞ\"]\na = 1";
test.parsesToml(str, {
"ʞ": {
a: 1
}
});
test.done();
};
exports.testComplexQuotedKeyNames = function(test) {
var str = "[ a . \"ʞ\" . c ]\nd = 1";
test.parsesToml(str, {
a: {
"ʞ": {
c: {
d: 1
}
}
}
});
test.done();
};
exports.testEscapedQuotesInQuotedKeyNames = function(test) {
test.parsesToml("[\"the \\\"thing\\\"\"]\na = true", {
'the "thing"': {
a: true
}
});
test.done();
};
exports.testMoreComplexQuotedKeyNames = function(test) {
// https://github.com/BinaryMuse/toml-node/issues/21
test.parsesToml('["the\\ key"]\n\none = "one"\ntwo = 2\nthree = false', {
"the\\ key": {
one: "one",
two: 2,
three: false
}
});
test.parsesToml('[a."the\\ key"]\n\none = "one"\ntwo = 2\nthree = false', {
a: {
"the\\ key": {
one: "one",
two: 2,
three: false
}
}
});
test.parsesToml('[a."the-key"]\n\none = "one"\ntwo = 2\nthree = false', {
a: {
"the-key": {
one: "one",
two: 2,
three: false
}
}
});
test.parsesToml('[a."the.key"]\n\none = "one"\ntwo = 2\nthree = false', {
a: {
"the.key": {
one: "one",
two: 2,
three: false
}
}
});
// https://github.com/BinaryMuse/toml-node/issues/34
test.parsesToml('[table]\n\'a "quoted value"\' = "value"', {
table: {
'a "quoted value"': "value"
}
});
// https://github.com/BinaryMuse/toml-node/issues/33
test.parsesToml('[module]\n"foo=bar" = "zzz"', {
module: {
"foo=bar": "zzz"
}
});
test.done();
};
exports.testErrorOnBadUnicode = function(test) {
var str = "str = \"My name is Jos\\uD800\"";
test.throws(function() {
toml.parse(str);
});
test.done();
};
exports.testErrorOnDotAtStartOfKey = function(test) {
test.throws(function() {
var str = "[.a]\nb = 1";
toml.parse(str);
});
test.done()
};
exports.testErrorOnDotAtEndOfKey = function(test) {
test.throws(function() {
var str = "[.a]\nb = 1";
toml.parse(str);
});
test.done()
};
exports.testErrorOnTableOverride = function(test) {
test.throws(function() {
var str = "[a]\nb = 1\n\n[a]\nc = 2";
toml.parse(str);
});
test.done()
};
exports.testErrorOnKeyOverride = function(test) {
test.throws(function() {
var str = "[a]\nb = 1\n[a.b]\nc = 2";
toml.parse(str);
});
test.done()
};
exports.testErrorOnKeyOverrideWithNested = function(test) {
// https://github.com/BinaryMuse/toml-node/issues/23
test.throws(function() {
var str = "[a]\nb = \"a\"\n[a.b.c]";
toml.parse(str);
}, "existing key 'a.b'");
test.done();
};
exports.testErrorOnKeyOverrideWithArrayTable = function(test) {
test.throws(function() {
var str = "[a]\nb = 1\n[[a]]\nc = 2";
toml.parse(str);
});
test.done()
};
exports.testErrorOnKeyReplace = function(test) {
test.throws(function() {
var str = "[a]\nb = 1\nb = 2";
toml.parse(str);
});
test.done()
};
exports.testErrorOnInlineTableReplace = function(test) {
// https://github.com/BinaryMuse/toml-node/issues/25
test.throws(function() {
var str = "a = { b = 1 }\n[a]\nc = 2";
toml.parse(str);
}, "existing key 'a'");
test.done();
};
exports.testErrorOnArrayMismatch = function(test) {
test.throws(function() {
var str = 'data = [1, 2, "test"]'
toml.parse(str);
});
test.done();
};
exports.testErrorOnBadInputs = function(test) {
var count = 0;
for (i in badInputs) {
(function(num) {
test.throws(function() {
toml.parse(badInputs[num]);
});
})(i);
}
test.done();
};
exports.testErrorsHaveCorrectLineAndColumn = function(test) {
var str = "[a]\nb = 1\n [a.b]\nc = 2";
try { toml.parse(str); }
catch (e) {
test.equal(e.line, 3);
test.equal(e.column, 2);
test.done();
}
};
exports.testUsingConstructorAsKey = function(test) {
test.parsesToml("[empty]\n[emptier]\n[constructor]\nconstructor = 1\n[emptiest]", {
"empty": {},
"emptier": {},
"constructor": { "constructor": 1 },
"emptiest": {}
});
test.done();
};

View File

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

View File

@@ -0,0 +1,15 @@
# util
[![Build Status](https://travis-ci.org/defunctzombie/node-util.png?branch=master)](https://travis-ci.org/defunctzombie/node-util)
node.js [util](http://nodejs.org/api/util.html) module as a module
## install via [npm](npmjs.org)
```shell
npm install util
```
## browser support
This module also works in modern browsers. If you need legacy browser support you will need to polyfill ES5 features.

View File

@@ -0,0 +1,16 @@
The ISC License
Copyright (c) Isaac Z. Schlueter
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,42 @@
Browser-friendly inheritance fully compatible with standard node.js
[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).
This package exports standard `inherits` from node.js `util` module in
node environment, but also provides alternative browser-friendly
implementation through [browser
field](https://gist.github.com/shtylman/4339901). Alternative
implementation is a literal copy of standard one located in standalone
module to avoid requiring of `util`. It also has a shim for old
browsers with no `Object.create` support.
While keeping you sure you are using standard `inherits`
implementation in node.js environment, it allows bundlers such as
[browserify](https://github.com/substack/node-browserify) to not
include full `util` package to your client code if all you need is
just `inherits` function. It worth, because browser shim for `util`
package is large and `inherits` is often the single function you need
from it.
It's recommended to use this package instead of
`require('util').inherits` for any code that has chances to be used
not only in node.js but in browser too.
## usage
```js
var inherits = require('inherits');
// then use exactly as the standard one
```
## note on version ~1.0
Version ~1.0 had completely different motivation and is not compatible
neither with 2.0 nor with standard node.js `inherits`.
If you are using version ~1.0 and planning to switch to ~2.0, be
careful:
* new version uses `super_` instead of `super` for referencing
superclass
* new version overwrites current prototype while old one preserves any
existing fields on it

View File

@@ -0,0 +1,7 @@
try {
var util = require('util');
if (typeof util.inherits !== 'function') throw '';
module.exports = util.inherits;
} catch (e) {
module.exports = require('./inherits_browser.js');
}

View File

@@ -0,0 +1,23 @@
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}

View File

@@ -0,0 +1,29 @@
{
"name": "inherits",
"description": "Browser-friendly inheritance fully compatible with standard node.js inherits()",
"version": "2.0.3",
"keywords": [
"inheritance",
"class",
"klass",
"oop",
"object-oriented",
"inherits",
"browser",
"browserify"
],
"main": "./inherits.js",
"browser": "./inherits_browser.js",
"repository": "git://github.com/isaacs/inherits",
"license": "ISC",
"scripts": {
"test": "node test"
},
"devDependencies": {
"tap": "^7.1.0"
},
"files": [
"inherits.js",
"inherits_browser.js"
]
}

View File

@@ -0,0 +1,35 @@
{
"author": {
"name": "Joyent",
"url": "http://www.joyent.com"
},
"name": "util",
"description": "Node.JS util module",
"keywords": [
"util"
],
"version": "0.10.4",
"homepage": "https://github.com/defunctzombie/node-util",
"repository": {
"type": "git",
"url": "git://github.com/defunctzombie/node-util"
},
"main": "./util.js",
"files": [
"util.js",
"support"
],
"scripts": {
"test": "node test/node/*.js && zuul test/browser/*.js"
},
"dependencies": {
"inherits": "2.0.3"
},
"license": "MIT",
"devDependencies": {
"zuul": "~1.0.9"
},
"browser": {
"./support/isBuffer.js": "./support/isBufferBrowser.js"
}
}

View File

@@ -0,0 +1,3 @@
module.exports = function isBuffer(arg) {
return arg instanceof Buffer;
}

View File

@@ -0,0 +1,6 @@
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}

View File

@@ -0,0 +1,586 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}