Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
onejs built by onejs
var one = (function(global, undefined){
var DEBUG = false,
pkgdefs = {},
pkgmap = {},
global = {},
lib = undefined,
nativeRequire = typeof require != 'undefined' && require,
ties, locals;
lib = (function(exports){
exports.path = (function(exports){
// Copyright Joyent, Inc. and other Node contributors.
// Minimized fork of NodeJS' path module, based on its an early version.
exports.join = function () {
return exports.normalize(Array.prototype.join.call(arguments, "/"));
};
exports.normalizeArray = function (parts, keepBlanks) {
var directories = [], prev;
for (var i = 0, l = parts.length - 1; i <= l; i++) {
var directory = parts[i];
// if it's blank, but it's not the first thing, and not the last thing, skip it.
if (directory === "" && i !== 0 && i !== l && !keepBlanks) continue;
// if it's a dot, and there was some previous dir already, then skip it.
if (directory === "." && prev !== undefined) continue;
if (
directory === ".."
&& directories.length
&& prev !== ".."
&& prev !== "."
&& prev !== undefined
&& (prev !== "" || keepBlanks)
) {
directories.pop();
prev = directories.slice(-1)[0]
} else {
if (prev === ".") directories.pop();
directories.push(directory);
prev = directory;
}
}
return directories;
};
exports.normalize = function (path, keepBlanks) {
return exports.normalizeArray(path.split("/"), keepBlanks).join("/");
};
exports.dirname = function (path) {
return path && path.substr(0, path.lastIndexOf("/")) || ".";
};
return exports;
})({});
global.process = exports.process = (function(exports){
/**
* This is module's purpose is to partly emulate NodeJS' process object on web browsers. It's not an alternative
* and/or implementation of the "process" object.
*/
function Buffer(size){
if (!(this instanceof Buffer)) return new Buffer(size);
this.content = '';
};
Buffer.prototype.isBuffer = function isBuffer(){
return true;
};
Buffer.prototype.write = function write(string){
this.content += string;
};
global.Buffer = exports.Buffer = Buffer;
function Stream(writable, readable){
if (!(this instanceof Stream)) return new Stream(writable, readable);
Buffer.call(this);
this.emulation = true;
this.readable = readable;
this.writable = writable;
this.type = 'file';
};
Stream.prototype = Buffer(0,0);
exports.Stream = Stream;
function notImplemented(){
throw new Error('Not Implemented.');
}
exports.binding = (function(){
var table = {
'buffer':{ 'Buffer':Buffer, 'SlowBuffer':Buffer }
};
return function binding(bname){
if(!table.hasOwnProperty(bname)){
throw new Error('No such module.');
}
return table[bname];
};
})();
exports.argv = ['onejs'];
exports.env = {};
exports.nextTick = function nextTick(fn){
return setTimeout(fn, 0);
};
exports.stderr = Stream(true, false);
exports.stdin = Stream(false, true);
exports.stdout = Stream(true, false);
exports.version = '1.6.0';
exports.versions = {};
/**
* void definitions
*/
exports.pid =
exports.uptime = 0;
exports.arch =
exports.execPath =
exports.installPrefix =
exports.platform =
exports.title = '';
exports.chdir =
exports.cwd =
exports.exit =
exports.getgid =
exports.setgid =
exports.getuid =
exports.setuid =
exports.memoryUsage =
exports.on =
exports.umask = notImplemented;
return exports;
})({});
return exports;
})({});
function findPkg(uri){
return pkgmap[uri];
}
function findModule(workingModule, uri){
var module = undefined,
moduleId = lib.path.join(lib.path.dirname(workingModule.id), uri).replace(/\.js$/, ''),
moduleIndexId = lib.path.join(moduleId, 'index'),
pkg = workingModule.pkg;
var i = pkg.modules.length,
id;
while(i-->0){
id = pkg.modules[i].id;
if(id==moduleId || id == moduleIndexId){
module = pkg.modules[i];
break;
}
}
return module;
}
function genRequire(callingModule){
return function require(uri){
var module,
pkg;
if(/^\./.test(uri)){
module = findModule(callingModule, uri);
} else if ( ties && ties.hasOwnProperty( uri ) ) {
return ties[ uri ];
} else {
pkg = findPkg(uri);
if(!pkg && nativeRequire){
try {
pkg = nativeRequire(uri);
} catch (nativeRequireError) {}
if(pkg) return pkg;
}
if(!pkg){
throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']');
}
module = pkg.index;
}
if(!module){
throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']');
}
module.parent = callingModule;
return module.call();
};
}
function module(parentId, wrapper){
var parent = pkgdefs[parentId],
mod = wrapper(parent),
cached = false;
mod.exports = {};
mod.require = genRequire(mod);
mod.call = function(){
if(cached) {
return mod.exports;
}
cached = true;
global.require = mod.require;
mod.wrapper(mod, mod.exports, global, global.Buffer,global.process, global.require);
return mod.exports;
};
if(parent.mainModuleId == mod.id){
parent.index = mod;
parent.parents.length == 0 && ( locals.main = mod.call );
}
parent.modules.push(mod);
}
function pkg(/* [ parentId ...], wrapper */){
var wrapper = arguments[ arguments.length - 1 ],
parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1),
ctx = wrapper(parents);
if(pkgdefs.hasOwnProperty(ctx.id)){
throw new Error('Package#'+ctx.id+' "' + ctx.name + '" has duplication of itself.');
}
pkgdefs[ctx.id] = ctx;
pkgmap[ctx.name] = ctx;
arguments.length == 1 && ( pkgmap['main'] = ctx );
}
function mainRequire(uri){
return pkgmap.main.index.require(uri);
}
function stderr(){
return lib.process.stderr.content;
}
function stdin(){
return lib.process.stdin.content;
}
function stdout(){
return lib.process.stdout.content;
}
return (locals = {
'lib' : lib,
'findPkg' : findPkg,
'findModule' : findModule,
'name' : 'one',
'module' : module,
'pkg' : pkg,
'packages' : pkgmap,
'stderr' : stderr,
'stdin' : stdin,
'stdout' : stdout,
'require' : mainRequire
});
})(this);
one.pkg(function(parents){
return {
'id':1,
'name':'one',
'main':undefined,
'mainModuleId':'index',
'modules':[],
'parents':parents
};
});
one.module(1, function(/* parent */){
return {
'id': 'templating',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var mustache = require('mustache'),
boxcars = require('boxcars'),
fs = require('fs'),
config = require('./config'),
logging = require('./logging'),
id = require('./id');
function collection(){
var coll = {};
var i = arguments.length,
filename;
while( i --> 0 ){
filename = arguments[i];
coll[ filename.replace(/\.js$/, '') ] = config.TEMPLATES_DIR + '/' + filename;
}
return boxcars(coll);
}
function makeVariableName(str){
return str.toLowerCase().replace(/[^a-zA-Z0-9]+/g,' ').replace(/^[\d\s]+/g,'').split(' ').reduce(function(a,b){
return a + b.charAt(0).toUpperCase() + b.slice(1).toLowerCase();
});
}
function _render(options, callback){
fs.readFile(config.TEMPLATES_DIR+'/'+options.template, function(error, bf){
var result;
if(!error){
result = mustache.to_html(bf.toString(), options.view, options.partials);w
}
callback(error, result);
});
}
function render(coll){
return function(/* options, callback */){
var options, callback = arguments[1];
if( typeof arguments[0] == 'string' ){
options = { 'template': arguments[0] };
} else {
options = arguments[0];
}
coll(function(error, templates){
if(error){
callback(error);
return;
}
if( !templates.hasOwnProperty( options.template ) ){
callback(new Error('Unknown template: "' + options.template + '"'));
return;
}
logging.trace('Rendering template "%s"', options.template);
var output;
try {
output = mustache.to_html(templates[ options.template ], options.view, options.partials);
} catch (mustacheError) {
logging.error('Failed to render template "%s"', options.template);
logging.error(mustacheError);
callback(mustacheError);
return;
}
callback(undefined, output);
});
};
}
module.exports = {
'collection': collection,
'id':id(),
'makeVariableName':makeVariableName,
'render':render
};
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'dependencies',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var path = require('path'),
readdir = require('fs').readdir,
logging = require('./logging'),
manifest = require('./manifest'),
installDict = Object.keys(require('./install_dict')),
pkg;
const BLACK_LIST = [
'one'
];
function nodeCorePackages(pkg, callback){
readdir( path.join(pkg.wd, 'node_modules'), function(error, files){
if(error){
callback([]);
return;
}
callback(files.filter(function(el){
return installDict.indexOf(el) > -1;
}));
});
}
function dependencies(parent, options, callback){
var deps = [],
declaredDepObj = parent.manifest.dependencies,
declaredDepList,
next;
if(declaredDepObj){
declaredDepList = Object.keys(declaredDepObj).filter(function(name){
return BLACK_LIST.indexOf(name) == -1 && ( !options.exclude || options.exclude.indexOf(name) == -1 );
});
}
nodeCorePackages(parent, function(installedNodeCorePackages){
if(installedNodeCorePackages.length){
!declaredDepList && ( declaredDepList = [] );
declaredDepList = declaredDepList.concat(installedNodeCorePackages);
}
if(!declaredDepList || !declaredDepList.length){
callback(undefined, deps);
return;
}
(function iter(i){
if(i>=declaredDepList.length){
logging.debug('Loaded %d dependencies under the package "%s"',deps.length, parent.manifest.name);
callback(undefined, deps);
return;
}
next = iter.bind(null, i+1);
var name = declaredDepList[i];
manifest.find(name, parent.wd, function(error, manifestPath){
if(error){
callback(error);
return;
}
logging.debug('Loading the dependency "%s" for its parent package "%s"', name + ' ('+ manifestPath +')', parent.name);
if(parent.pkgdict[name]){
parent.pkgdict[name].parents.push(parent);
deps.push(parent.pkgdict[name]);
next();
return;
}
!pkg && ( pkg = require('./package') );
pkg({ 'manifestPath': manifestPath, 'parent': parent }, options, function(error, dependency){
deps.push(dependency);
next();
});
});
})(0);
});
};
module.exports = dependencies;
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'modules',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var functools = require('functools'),
compose = functools.compose,
combiner = require('combiner'),
path = require('path'),
readFile = require('fs').readFile,
logging = require('./logging');
function filterFilename(filename){
return /\.js$/.test(filename);
}
function filterFilenames(filenames, callback){
callback(undefined,filenames.filter(filterFilename));
}
function filterIgnoredModules(pkg){
return function(filenames, callback){
if(!pkg.ignore){
callback(undefined, filenames);
return;
}
var f = filenames.length,
i, ignore, filename,
ignored, result = [];
while( f -- ){
ignored = false;
i = pkg.ignore.length;
filename = filenames[f].substring(pkg.wd.length + ( pkg.wd.substring(pkg.wd.length-1) != '/' ? 1 : 0 ));
while( i -- ){
ignore = pkg.ignore[i];
if( filename.substring( 0, ignore.length ) == ignore ){
logging.debug('Module "%s" is ignored by the line "%s" at .npmignore', filename, ignore);
ignored = true;
break;
}
}
!ignored && result.push( filenames[f] );
}
callback(undefined, result);
};
}
function fixname(filename){
var m = filename.match(/([^\/\.]+)\.js$/);
return !m ? undefined : m[1];
}
function loadModule(filename, callback){
logging.trace('Loading module "'+filename+'"');
readFile(filename, function(error, bf){
if(error) {
callback(error);
return;
}
var content = bf.toString(),
name = fixname(filename);
if(content.substring(0,2) == '#!'){
content = content.replace(/\#\!.+\n/, '');
}
callback(undefined, {
'name':name,
'filename':filename,
'path':filename,
'content':content
});
});
};
function loadModules(pkg, base){
return function(filenames, callback){
logging.debug('Found '+filenames.length+' file(s) under the package "'+pkg.name+'"');
var modules = [];
(function next(i){
if(i>=filenames.length){
logging.debug('Loaded %d module(s) under the package "%s"',filenames.length,pkg.name);
callback(undefined, modules);
return;
}
loadModule(filenames[i], function(error, module){
if(error){
logging.error('Failed to load the module "'+filenames[i]+'"');
callback(error);
return;
}
module.filename = module.filename.replace(base+'/', '');
module.filename.indexOf('/') > 0 && base != '.' && ( module.filename = module.filename.replace(base, '') );
module.id = module.filename.replace(/\.js$/,'');
if(!error) modules.push(module);
next(i+1);
});
})(0);
};
}
function modules(pkg, options, callback){
logging.debug('Collect modules for the package "'+pkg.name+'"');
var dirs = [],
base = '',
join = path.join.bind(undefined, pkg.wd),
lib = join('lib');
if(pkg.dirs && pkg.dirs.lib){
base = join(pkg.dirs.lib);
dirs.push(base);
} else if (pkg.manifest.main) {
base = pkg.wd;
dirs.indexOf(lib) == -1 && dirs.push(lib);
dirs.push(join(pkg.manifest.main + ( /\.js$/.test(pkg.manifest.main) ? '' : '.js' )));
} else {
base = pkg.wd;
dirs.push(join('index.js'));
dirs.push(join('lib'));
}
logging.debug('The directories to search:', dirs);
compose.async(combiner.findFiles,
combiner.includeDirectories,
combiner.flatten,
filterFilenames,
filterIgnoredModules(pkg),
loadModules(pkg, base))(dirs, callback);
}
module.exports = modules;
module.exports.filterFilename = filterFilename;
module.exports.loadModule = loadModule;
module.exports.loadModules = loadModules;
module.exports.fixname = fixname;
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'config',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var join = require('path').join;
module.exports = {
'TEMPLATES_DIR': join(__dirname, '../templates')
}
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'render',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var readFile = require('fs').readFile,
logging = require('./logging'),
templating = require('./templating'),
functools = require('functools'),
map = functools.map.async,
juxt = functools.juxt.async;
var templates = templating.collection('wrapper.js', 'package.js', 'module.js', 'console.js', 'library.js', 'path.js', 'process.js'),
render = templating.render(templates);
function flattenPkgTree(tree){
var pkgs = [],
key;
for(key in tree.pkgdict){
pkgs.push( tree.pkgdict[ key ] );
}
return pkgs;
}
function sandboxConsole(options, callback){
logging.trace('Rendering console template');
render('console', callback);
}
function env(options){
var result, key;
if(options.debug){
result = {};
for(key in process.env){
result[ key ] = process.env[ key ].replace(/"/g, '\'');
}
}
return JSON.stringify(result);
}
function library(options, callback){
logging.trace('Rendering library template...');
var view = {}, partials = {};
view.debug = options.debug;
view.version = '1.6.0'; // FIXME
view.versions = '{}';
view.env = env(options);
view.sandboxConsole = options.sandboxConsole;
view.include_process = !options.noprocess;
juxt({ 'path':path, 'process':process, 'console': sandboxConsole })(options, function(error, partials){
if(error){
callback(error);
return;
}
render({ 'template': 'library', 'view': view, 'partials': partials }, callback);
});
}
function main(pkg, options, callback){
logging.trace('Rendering...');
templates(function(error, buffers){
if(error){
callback(error);
return;
}
var treeName = templating.makeVariableName(pkg.name),
pkgs = flattenPkgTree(pkg);
map( npmpackage.bind(undefined, treeName, options), pkgs, function(error, packages){
if(error){
callback(error);
return;
}
logging.info('All packages has been built. Rendering the output now...');
wrapper(treeName, packages.join('\n\n\n\n'), options, callback);
});
});
}
function npmpackage(treeName, options, pkg, callback){
logging.debug('Building package "'+pkg.name+'"');
var view = {
'treeName': treeName,
'hasParent': pkg.parents.length > 0,
'parentIds': pkg.parents.map(function(el){ return el.id; }).join(', '),
'id': pkg.id,
'main': pkg.main && pkg.main.id,
'name': pkg.name,
'wd': pkg.wd
};
var partials = {};
map( npmmodule.bind(undefined, pkg, treeName, options), pkg.modules, function(error, modules){
if(error) {
callback(error);
return;
}
partials.modules = modules.join('\n\n');
render({ 'template':'package', 'view': view, 'partials': partials }, callback);
});
}
function npmmodule(pkg, treeName, options, module, callback){
logging.debug('Building module "'+module.id+'"');
var view = {
'treeName': treeName,
'parentId': pkg.id,
'id': module.id,
'sandbox_console': options.sandboxConsole
};
var partials = {
'content': module.content
};
render({ template: 'module', 'view': view, 'partials': partials }, callback);
}
function path(options, callback){
logging.trace('Rendering path template.');
render('path', callback);
}
function process(options, callback){
logging.trace('Rendering process template');
var view = {
'env': env(options),
'debug': options.debug,
'version': '1.6.0',
'versions': '{}'
};
render({ template: 'process', view: view }, callback);
}
function ties(options){
if(!options.tie){
return undefined;
}
var output = '{', key,
i = options.tie.length,
comma = '';
while( i -- ){
output += comma + '"'+ options.tie[i].pkg + '": ' + options.tie[i].obj;
comma = ', ';
}
output += '}';
return output;
};
function wrapper(treeName, packages, options, callback){
logging.trace('Rendering wrapper template...');
var view = {}, partials = {};
view.name = treeName;
view.debug = options.debug;
view.ties = ties(options);
view.sandbox_console = options.sandboxConsole;
library(options, function(error, renderedLibrary){
if(error){
callback(error);
return;
}
partials.library = renderedLibrary;
partials.packages = packages;
render({
'template': 'wrapper',
'view': view,
'partials': partials
}, callback);
});
}
main.flattenPkgTree = flattenPkgTree;
module.exports = main;
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'package',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var path = require('path'),
assert = require('assert'),
fs = require('fs'),
compose = require('functools').compose,
logging = require('./logging'),
id = require('./id'),
manifest = require('./manifest'),
modules = require('./modules'),
dependencies = require('./dependencies');
function construct(context, callback){
assert.ok(context.manifest);
assert.ok(context.wd);
var parents = !context.parents || !context.parents.length ? [] : context.parents;
!context.parents && context.parent && parents.push( context.parent );
var struct = {
'id' : context.hasOwnProperty('id') && context.id != undefined ? context.id : module.exports.id(),
'dependencies' : undefined,
'dirs' : context.manifest.directories || {},
'ignore' : context.ignore,
'main' : undefined,
'manifest' : context.manifest,
'modules' : undefined,
'modulesDict' : {},
'name' : context.manifest.name,
'parents' : parents,
'pkgdict' : parents.length ? parents[0].pkgdict : {},
'wd' : context.wd
};
struct.pkgdict[struct.name] = struct;
callback(undefined, struct);
}
function loadDependencies(params, callback){
var pkg = params.pkg, options = params.options;
logging.debug('Loading dependencies of %s', pkg.name);
dependencies(pkg, options, function(error, deps){
if(error){
logging.error('An unexpected error occurred during collecting dependencies of the package "%s".', pkg.name);
logging.error(error);
callback(error);
return;
}
logging.debug('%d dependencies has been loaded for the package "%s"', deps.length, pkg.name);
pkg.dependencies = deps;
callback(undefined, params);
});
}
function loadModules(params, callback){
var pkg = params.pkg, options = params.options;
modules(pkg, options, function(error, modules){
if(error){
logging.error('An unexpected error occurred during collecting modules of the package "%s".', pkg.name);
logging.error(error);
callback(error);
return;
}
logging.debug('Collected %d modules for the package "%s"', modules.length, pkg.name);
pkg.modules = modules;
var i = modules.length, m;
while(i-->0){
m = modules[i];
pkg.modulesDict[m.path] = m;
}
callback(undefined, params);
});
}
function setMainModule(params, callback){
var pkg = params.pkg, options = params.options, errormsg;
if( ! pkg.manifest.main ){
callback(undefined, pkg, options);
}
logging.debug('Setting main module of the package "%s" as %s', pkg.name, pkg.manifest.main);
var absolutePath = path.join(pkg.wd, pkg.manifest.main );
fs.stat(absolutePath, function(error, stat){
var isDirectory = stat && stat.isDirectory(),
hasJSExt = /\.js$/.test(pkg.manifest.main),
resolvedPath = isDirectory ? path.join( absolutePath, 'index.js') : hasJSExt ? absolutePath : absolutePath + '.js';
pkg.main = pkg.modulesDict[resolvedPath];
if( pkg.main ){
pkg.mainModuleId = pkg.main.name;
callback(undefined, params);
} else {
errormsg = 'Failed to find main module of "' + pkg.name + '". Resolved Path: "' + resolvedPath + '" Manifest Definition: "' + pkg.manifest.main + '"';
logging.fatal(errormsg);
callback(new Error(errormsg));
}
});
}
function content(pkg, options, callback){
logging.debug('Loading the package "%s"', pkg.manifest.name);
compose.async(loadDependencies, loadModules, setMainModule)({ 'pkg': pkg, 'options': options }, function(error){
if(error){
callback(error);
return;
}
logging.info('%s loaded.', pkg.name);
callback(undefined, pkg);
});
}
function main(options, buildOptions, callback){
var manifestPath;
typeof options == 'string'
&& ( manifestPath = options, options = { 'manifestPath': manifestPath } )
|| ( manifestPath = options.manifestPath );
logging.trace('Building the package at "%s"', manifestPath);
manifest(manifestPath, function(error, manifestObj){
if(error){
callback(error);
return;
}
construct({ 'manifest': manifestObj, 'ignore':options.ignore, 'wd': path.normalize(path.dirname(manifestPath)), 'parents': options.parents, 'parent': options.parent }, function(error, pkgobj){
if(error){
callback(error);
return;
}
content(pkgobj, buildOptions, callback);
});
});
}
module.exports = main;
module.exports.id = id();
module.exports.content = content;
module.exports.construct = construct;
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'logging',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var log4js = require('log4js'),
logger = log4js.getLogger('onejs');
logger.setLevel('TRACE');
module.exports = logger;
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'npmignore',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var path = require('path'),
readFile = require('fs').readFile,
logging = require('./logging');
function filename(dir){
return path.join(dir, '.npmignore');
}
function npmignore(dir, callback){
readFile( filename(dir), function(error, bf){
if(error){
callback(error);
return;
}
var lines = bf.toString()
.split('\n')
.map(function(el){
return el.replace(/\s/g, '');
})
.filter(function(el){
return el.length;
});
logging.debug('%s has been loaded and parsed.', filename(dir));
callback(undefined, lines);
});
}
module.exports = npmignore;
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'manifest',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var boxcars = require('boxcars'),
path = require('path'),
logging = require('./logging');
function find(packageName, workingdir, callback){
logging.debug('Searching for the manifest file of package "%s" under "%s"', packageName, workingdir);
var filename = path.join(workingdir, 'node_modules', packageName, '/package.json');
path.exists(filename, function(exists){
if(exists){
callback(undefined, filename);
return;
}
var up = path.join(workingdir, '../');
if( ( /^\.\.\//.test(up) && up.match(/\.\.\//g).length > process.cwd().match(/\//g).length ) ){
logging.error('Infinite tree-walk detected.');
callback(new Error('Failed to find package "'+packageName+'"'));
return;
}
path.exists( up, function(exists){
if(!exists){
logging.error('Failed to find package "%s"', packageName);
callback(new Error('Failed to find package "'+packageName+'"'));
return;
}
find(packageName, up, callback);
});
});
}
function read(filename, callback){
logging.debug('Reading the manifest @ "%s"', filename);
var manifest;
boxcars(filename)(function(error, bf){
if(error){
logging.error('Failed to read the file "%s"', filename);
callback(error);
return;
}
logging.debug('Parsing the manifest @ "%s"', filename);
try {
manifest = JSON.parse(bf);
logging.trace('Manifest file "%s" loaded and parsed successfully.', filename);
} catch(exc) {
logging.error('Failed to parse the manifest @ "%s"', filename);
error = exc;
}
callback(error, manifest);
});
}
module.exports = read;
module.exports.find = find;
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'install_dict',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var dict = {
'assert':'https://raw.github.com/joyent/node/master/lib/assert.js',
'console':'https://raw.github.com/joyent/node/master/lib/console.js',
'crypto':'https://raw.github.com/joyent/node/master/lib/crypto.js',
'events':'https://raw.github.com/joyent/node/master/lib/events.js',
'freelist':'https://raw.github.com/joyent/node/master/lib/freelist.js',
'path':'https://raw.github.com/joyent/node/master/lib/path.js',
'punycode':' https://raw.github.com/joyent/node/master/lib/punycode.js',
'string_decoder':'https://raw.github.com/joyent/node/master/lib/string_decoder.js',
'url':'https://raw.github.com/joyent/node/master/lib/url.js',
'util':'https://raw.github.com/joyent/node/master/lib/util.js',
'tty':'https://raw.github.com/gist/2649813/01789078ef19464e8065416a3e95661f4c71b52f/tty.js'
};
module.exports = dict;
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'index',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var genpkg = require('genpkg'),
path = require('path'),
fs = require('fs'),
id = require('./id'),
templating = require('./templating'),
render = require('./render'),
logging = require('./logging'),
server = require('./server'),
installDict = require('./install_dict'),
manifest = require('./manifest'),
dependencies = require('./dependencies'),
pkg = require('./package'),
modules = require('./modules'),
npmignore = require('./npmignore');
var slice = Array.prototype.slice;
function build(manifestPath, buildOptions, callback){
var pkgOptions = {
'manifestPath': manifestPath
};
npmignore(path.dirname(manifestPath), function(error, toIgnore){
if(error){
logging.warn('Failed to read .npmignore');
} else {
pkgOptions.ignore = toIgnore;
}
pkg(pkgOptions, buildOptions, function(error, loadedPkg){
if(error){
callback(error);
return;
}
render(loadedPkg, buildOptions, function(error, sourceCode){
callback(error, sourceCode, pkg);
});
});
});
}
function quiet(y){
logging.setLevel('ERROR');
}
function save(target, content, callback){
logging.debug('Saving output into '+target);
fs.writeFile(target, content, function(error) {
if(error) {
logging.error('Failed to write the target file "'+target+'"');
callback(error);
return;
}
logging.info('The target file "'+target+'" was saved!');
callback();
});
}
function publish(options){
options.returnPackage = true;
build(options, function(error, built, pkg){
if(error) throw error;
options.content = built;
options.pkg = pkg;
server.start(options);
});
}
function setupNodeModules(/* modules */){
var pkgs = slice.call(arguments, 0, arguments.length-1),
callback = arguments[arguments.length - 1],
len = pkgs.length;
var pkgName, pkgURI, next;
(function iter(i, error){
if(i>=len || error){
callback(error);
return;
}
pkgName = pkgs[i];
pkgURI = installDict[pkgName];
if(!pkgURI){
logging.error('Unknown package "%s" ', pkgName);
callback(new Error('Unknown package "%s"', pkgName));
return;
}
next = iter.bind(undefined, i+1);
genpkg.pkg({ 'uri':pkgURI }, function(error, pkg){
if(error){
throw error;
}
pkg.target = path.join('node_modules', pkg.manifest.name);
genpkg.save(pkg, next);
});
})(0);
}
function verbose(){
logging.setLevel('TRACE');
}
function verbosity(level){
logging.setLevel(level);
}
module.exports = {
'build': build,
'dependencies': dependencies,
'id': id,
'pkg': pkg,
'npmignore': npmignore,
'manifest': manifest,
'modules': modules,
'logging': logging,
'quiet': quiet,
'publish': publish,
'save': save,
'setupNodeModules': setupNodeModules,
'verbose': verbose,
'verbosity': verbosity
};
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'server',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var http = require('http'),
templating = require('./templating'),
logging = require('./logging');
function firebug(options, req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
templating.render({ 'template':'firebug.html', 'view':{ 'content':options.content, 'pkgname':templating.makeVariableName(options.pkg.name), 'modname':options.pkg.modules[0].id } }, function(error, html){
if(error) throw error;
res.end(html);
});
}
function raw(options, req, res){
res.end(options.content);
}
function start(options){
logging.info('Server starts on %s:%d', options.host, options.port);
http.createServer(function(req, res){
if(req.url == '/raw' || req.url == '/raw/'){
raw(options, req, res);
} else {
firebug(options, req, res);
}
}).listen(options.port, options.host);
}
module.exports = {
'start':start
}
}
};
});
one.module(1, function(/* parent */){
return {
'id': 'id',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
module.exports = function genId(){
var serial = 0;
return function id(){
return ++serial;
};
};
}
};
});
one.pkg(1, function(parents){
return {
'id':2,
'name':'boxcars',
'main':undefined,
'mainModuleId':'boxcars',
'modules':[],
'parents':parents
};
});
one.module(2, function(/* parent */){
return {
'id': 'boxcars',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var boxcars = (function(undefined){
var slice = Array.prototype.slice,
node = typeof process != 'undefined' && process.versions && process.versions.node != undefined,
get = node && nodeGet || browserGet,
XHR, libhttp, libhttps, liburl, libfs;
if(node){
libhttp = require('http');
libhttps = require('https');
liburl = require('url');
libfs = require('fs');
} else if (typeof XMLHttpRequest != "undefined"){
XHR = XMLHttpRequest;
} else {
XHR = function XMLHttpRequest() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
};
function isArray(el){
return Object.prototype.toString.call(el) == '[object Array]';
}
function browserGet(url, callback){
var req = new XHR;
req.open('GET', url, true);
req.onreadystatechange = function (aEvt) {
if ( req.readyState == 4 ) {
if ( req.status == 200 ){
callback(undefined, req.responseText);
} else {
callback(new Error('GET ' + url + ' has been failed (' + req.status + ')'));
}
}
};
req.send();
};
function nodeGet(uri, callback){
return ( /^\w+\:\/\//.test(uri) && nodeHttpGet || nodeFSGet ).apply(undefined, arguments);
}
function nodeFSGet(filename, callback){
libfs.readFile(filename, function(error, bf){
if(error){
callback(error);
return;
}
callback(undefined, bf.toString());
});
}
function nodeHttpGet(url, callback){
var urlopts = liburl.parse(url);
var host = urlopts.host.replace(/\:\d+/, ''),
options = {
host: host,
port: urlopts.port,
path: urlopts.pathname,
headers: {
Host: host
}
};
( urlopts.protocol == 'https' && libhttps || libhttp ).get(options, function(res) {
var buffer = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
buffer += chunk;
});
res.on('end', function(){
callback(undefined, buffer);
});
});
}
return function boxcarsColl(){
var parentPaths = slice.call(arguments);
var cache = (function(newValue){
var elements = undefined;
return function cache(newValue){
if( arguments.length > 0 ){
elements = newValue;
}
if( elements == undefined){
elements = {};
}
return elements;
};
})();
function element(path, callback){
if( cache().hasOwnProperty(path) ){
callback(undefined, cache()[path]);
return;
}
get(path, function(error, content){
if(!error){
cache()[ path ] = content;
}
callback(error, content);
});
}
function main(){
var paths = parentPaths.concat( slice.call(arguments, 0, arguments.length - 1) ),
callback = arguments[arguments.length - 1],
isSingleContent = paths.length == 1 && typeof paths[0] == 'string',
isListContent, isObjectContent,
filenames, contents, map, key;
paths.length == 1 && !isSingleContent && ( paths = paths[0] );
isListContent = isArray(paths);
isObjectContent = !isListContent && typeof paths == 'object' && paths.hasOwnProperty != undefined;
if( isListContent ){
filenames = paths;
contents = [];
} else {
filenames = [];
contents = {};
map = {};
for(key in paths){
filenames.push( paths[key] );
map[ paths[key] ] = key;
contents[ key ] = undefined;
}
}
(function iter(i){
if( i >= filenames.length ){
callback( undefined, contents );
return;
}
element(filenames[i], function(error, content){
if(error){
callback(error);
return;
} else if( isSingleContent ){
callback(undefined, content);
return;
} else if( isListContent ){
contents.push( content );
} else {
contents[ map[filenames[i]] ] = content;
}
iter(i+1);
});
}(0));
}
main.cache = cache;
return main;
};
})();
if(typeof module != 'undefined' && module.exports){
module.exports = boxcars;
}
}
};
});
one.pkg(1, 6, function(parents){
return {
'id':3,
'name':'functools',
'main':undefined,
'mainModuleId':'functools',
'modules':[],
'parents':parents
};
});
one.module(3, function(/* parent */){
return {
'id': 'functools',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var functools = (function(undefined){
function isArray(el){
return Object.prototype.toString.call(el) == '[object Array]';
}
/**
* Function composition implementation
*/
function compose(/* functions */){
var fns = Array.prototype.slice.call(arguments);
return function(initialValue){
return reduce(function(f,g){
return function(val){
return g(f(val));
};
},fns)(initialValue);
};
}
compose.async = function compose_async(/* functions */){
var fns = Array.prototype.slice.call(arguments);
return function(initialValue,callback){
(function(i,error,value){
if(error || fns.length<=i){
callback(error, value);
return;
}
fns[i](value, partial(arguments.callee, [i+1]));
})(0,undefined,initialValue);
};
};
/**
* Take a set of functions, return a function that is the juxtaposition of those
* functions. The returned function takes a variable number of arguments and returns
* a list containing the result of applying each fn to the arguments.
*
* usage examples;
* juxt(Number, String, Array)(true) => [1, "true", [true]]
* juxt({ "num": Number, "str": String, "arr": Array })(true) => { "num": 1, "str": "true", "arr": [true] }
*/
function juxt(/* functions */){
var fns = arguments.length > 1 || typeof arguments[0] != 'object' ? arguments : arguments[0];
return function(){
var args = arguments;
return map(function(fn){
return fn.apply(undefined, args);
}, fns);
};
}
juxt.async = function(/* functions */){
var fns = arguments.length > 1 || typeof arguments[0] != 'object' ? arguments : arguments[0];
return function(/* args, callback */){
var args = Array.prototype.slice.call(arguments, 0, arguments.length-1),
callback = arguments[arguments.length-1];
map.async(function(fn, callback){
fn.apply(undefined, args.concat([callback]));
}, fns, callback);
};
};
/**
* Transform multiple-argument 'fn' into a chain of functions that return each other until all arguments
* are gathered.
*/
function curry(fn){
var args = Array.prototype.slice.call(arguments,1),
len = fn.length;
return (function(){
Array.prototype.push.apply(args,arguments);
return args.length >= len && fn.apply(null,args) || arguments.callee;
})();
}
/**
* Execute 'fn' once per 'iterable' element.
*/
function each(fn,iterable){
for(var i = -1, len=iterable.length; ++i < len; ){
fn(iterable[i],i,iterable);
};
return iterable;
}
/**
* Apply 'fn' to every element of 'iterable', returning those elements for which fn returned a true value.
*/
function filter(fn,iterable){
var accumulation = [];
for(var i = -1, len=iterable.length; ++i < len; ){
fn(iterable[i],i,iterable) && accumulation.push(iterable[i]);
};
return accumulation;
}
filter.async = function filter_async(fn, iterable, callback){
var accumulation = [];
(function(i,ptest){
ptest && accumulation.push(iterable[i-1]);
if(i>=iterable.length){
callback(accumulation);
return;
}
fn(iterable[i], partial(arguments.callee, [i+1]));
})(0);
}
/**
* Apply fn to every element of iterable.
*/
function map(fn, iterable){
var clone, i, len, key;
if(isArray(iterable)){
clone = Array.prototype.slice.call(iterable, 0);
i = -1;
len = clone.length;
while(++i<len){
clone[i] = fn(clone[i], i, clone);
}
} else if(typeof iterable == 'object') {
clone = {};
for(key in iterable){
clone[key] = fn(iterable[key], key, clone);
}
}
return clone;
}
map.async = function map_async(fn, iterable, callback){
var clone, iter, i, len, key, value,
list = isArray(iterable);
iter = list ? Array.prototype.slice.call(iterable) : Object.keys(iterable);
clone = list ? iter : {};
(function next(i, error, rpl){
key = list ? i-1 : iter[i-1];
value = list ? clone[i] : iterable[ iter[i] ];
arguments.length > 2 && ( clone[key] = rpl );
if(error || i>=iter.length){
callback(error, clone);
return;
}
fn(value, next.bind(undefined, i+1));
})(0);
};
/**
* Return a new function which will call 'fn' with the positional arguments 'args'
*/
function partial(fn,initialArgs,ctx){
!initialArgs && ( initialArgs = [] );
return function(){
var args = Array.prototype.slice.call(initialArgs,0);
Array.prototype.push.apply(args,arguments);
return fn.apply(ctx,args);
};
};
/**
* Apply fn cumulatively to the items of iterable, as to reduce the iterable to a single value
*/
function reduce(fn,iterable){
var accumulator = iterable[0];
for(var i = 0, len=iterable.length; ++i < len; ){
accumulator=fn(accumulator,iterable[i],iterable);
};
return accumulator;
}
reduce.async = function reduce_async(fn,iterable,callback){
(function(i, error, accumulator){
if(error || i>=iterable.length){
callback(error, accumulator);
return;
}
fn(accumulator, iterable[i], partial(arguments.callee, [i+1]));
})(1,undefined,iterable[0]);
};
return {
"compose":compose,
"curry":curry,
"each":each,
"filter":filter,
'juxt':juxt,
"map":map,
"partial":partial,
"reduce":reduce
};
})();
if(typeof module != 'undefined' && module.exports){
module.exports = functools;
}
}
};
});
one.pkg(1, function(parents){
return {
'id':4,
'name':'optimist',
'main':undefined,
'mainModuleId':'index',
'modules':[],
'parents':parents
};
});
one.module(4, function(/* parent */){
return {
'id': 'test/_',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var spawn = require('child_process').spawn;
var assert = require('assert');
exports.dotSlashEmpty = function () {
testCmd('./bin.js', []);
};
exports.dotSlashArgs = function () {
testCmd('./bin.js', [ 'a', 'b', 'c' ]);
};
exports.nodeEmpty = function () {
testCmd('node bin.js', []);
};
exports.nodeArgs = function () {
testCmd('node bin.js', [ 'x', 'y', 'z' ]);
};
exports.whichNodeEmpty = function () {
var which = spawn('which', ['node']);
which.stdout.on('data', function (buf) {
testCmd(buf.toString().trim() + ' bin.js', []);
});
which.stderr.on('data', function (err) {
assert.fail(err.toString());
});
};
exports.whichNodeArgs = function () {
var which = spawn('which', ['node']);
which.stdout.on('data', function (buf) {
testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ]);
});
which.stderr.on('data', function (err) {
assert.fail(err.toString());
});
};
function testCmd (cmd, args) {
var to = setTimeout(function () {
assert.fail('Never got stdout data.')
}, 5000);
var oldDir = process.cwd();
process.chdir(__dirname + '/_');
var cmds = cmd.split(' ');
var bin = spawn(cmds[0], cmds.slice(1).concat(args.map(String)));
process.chdir(oldDir);
bin.stderr.on('data', function (err) {
assert.fail(err.toString());
});
bin.stdout.on('data', function (buf) {
clearTimeout(to);
var _ = JSON.parse(buf.toString());
assert.eql(_.map(String), args.map(String));
});
}
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'test/parse',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var optimist = require('../index');
var assert = require('assert');
var path = require('path');
var localExpresso = path.normalize(
__dirname + '/../node_modules/.bin/expresso'
);
var expresso = process.argv[1] === localExpresso
? 'node ./node_modules/.bin/expresso'
: 'expresso'
;
exports['short boolean'] = function () {
var parse = optimist.parse([ '-b' ]);
assert.eql(parse, { b : true, _ : [], $0 : expresso });
assert.eql(typeof parse.b, 'boolean');
};
exports['long boolean'] = function () {
assert.eql(
optimist.parse([ '--bool' ]),
{ bool : true, _ : [], $0 : expresso }
);
};
exports.bare = function () {
assert.eql(
optimist.parse([ 'foo', 'bar', 'baz' ]),
{ _ : [ 'foo', 'bar', 'baz' ], $0 : expresso }
);
};
exports['short group'] = function () {
assert.eql(
optimist.parse([ '-cats' ]),
{ c : true, a : true, t : true, s : true, _ : [], $0 : expresso }
);
};
exports['short group next'] = function () {
assert.eql(
optimist.parse([ '-cats', 'meow' ]),
{ c : true, a : true, t : true, s : 'meow', _ : [], $0 : expresso }
);
};
exports['short capture'] = function () {
assert.eql(
optimist.parse([ '-h', 'localhost' ]),
{ h : 'localhost', _ : [], $0 : expresso }
);
};
exports['short captures'] = function () {
assert.eql(
optimist.parse([ '-h', 'localhost', '-p', '555' ]),
{ h : 'localhost', p : 555, _ : [], $0 : expresso }
);
};
exports['long capture sp'] = function () {
assert.eql(
optimist.parse([ '--pow', 'xixxle' ]),
{ pow : 'xixxle', _ : [], $0 : expresso }
);
};
exports['long capture eq'] = function () {
assert.eql(
optimist.parse([ '--pow=xixxle' ]),
{ pow : 'xixxle', _ : [], $0 : expresso }
);
};
exports['long captures sp'] = function () {
assert.eql(
optimist.parse([ '--host', 'localhost', '--port', '555' ]),
{ host : 'localhost', port : 555, _ : [], $0 : expresso }
);
};
exports['long captures eq'] = function () {
assert.eql(
optimist.parse([ '--host=localhost', '--port=555' ]),
{ host : 'localhost', port : 555, _ : [], $0 : expresso }
);
};
exports['mixed short bool and capture'] = function () {
assert.eql(
optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ], $0 : expresso,
}
);
};
exports['short and long'] = function () {
assert.eql(
optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ], $0 : expresso,
}
);
};
exports.no = function () {
assert.eql(
optimist.parse([ '--no-moo' ]),
{ moo : false, _ : [], $0 : expresso }
);
};
exports.multi = function () {
assert.eql(
optimist.parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]),
{ v : ['a','b','c'], _ : [], $0 : expresso }
);
};
exports.comprehensive = function () {
assert.eql(
optimist.parse([
'--name=meowmers', 'bare', '-cats', 'woo',
'-h', 'awesome', '--multi=quux',
'--key', 'value',
'-b', '--bool', '--no-meep', '--multi=baz',
'--', '--not-a-flag', 'eek'
]),
{
c : true,
a : true,
t : true,
s : 'woo',
h : 'awesome',
b : true,
bool : true,
key : 'value',
multi : [ 'quux', 'baz' ],
meep : false,
name : 'meowmers',
_ : [ 'bare', '--not-a-flag', 'eek' ],
$0 : expresso
}
);
};
exports.nums = function () {
var argv = optimist.parse([
'-x', '1234',
'-y', '5.67',
'-z', '1e7',
'-w', '10f',
'--hex', '0xdeadbeef',
'789',
]);
assert.eql(argv, {
x : 1234,
y : 5.67,
z : 1e7,
w : '10f',
hex : 0xdeadbeef,
_ : [ 789 ],
$0 : expresso
});
assert.eql(typeof argv.x, 'number');
assert.eql(typeof argv.y, 'number');
assert.eql(typeof argv.z, 'number');
assert.eql(typeof argv.w, 'string');
assert.eql(typeof argv.hex, 'number');
assert.eql(typeof argv._[0], 'number');
};
exports['flag boolean'] = function () {
var parse = optimist([ '-t', 'moo' ]).boolean(['t']).argv;
assert.eql(parse, { t : true, _ : [ 'moo' ], $0 : expresso });
assert.eql(typeof parse.t, 'boolean');
};
exports['flag boolean value'] = function () {
var parse = optimist(['--verbose', 'false', 'moo', '-t', 'true'])
.boolean(['t', 'verbose']).default('verbose', true).argv;
assert.eql(parse, {
verbose: false,
t: true,
_: ['moo'],
$0 : expresso
});
assert.eql(typeof parse.verbose, 'boolean');
assert.eql(typeof parse.t, 'boolean');
};
exports['flag boolean default false'] = function () {
var parse = optimist(['moo'])
.boolean(['t', 'verbose'])
.default('verbose', false)
.default('t', false).argv;
assert.eql(parse, {
verbose: false,
t: false,
_: ['moo'],
$0 : expresso
});
assert.eql(typeof parse.verbose, 'boolean');
assert.eql(typeof parse.t, 'boolean');
};
exports['boolean groups'] = function () {
var parse = optimist([ '-x', '-z', 'one', 'two', 'three' ])
.boolean(['x','y','z']).argv;
assert.eql(parse, {
x : true,
y : false,
z : true,
_ : [ 'one', 'two', 'three' ],
$0 : expresso
});
assert.eql(typeof parse.x, 'boolean');
assert.eql(typeof parse.y, 'boolean');
assert.eql(typeof parse.z, 'boolean');
};
exports.strings = function () {
var s = optimist([ '-s', '0001234' ]).string('s').argv.s;
assert.eql(s, '0001234');
assert.eql(typeof s, 'string');
var x = optimist([ '-x', '56' ]).string('x').argv.x;
assert.eql(x, '56');
assert.eql(typeof x, 'string');
};
exports.stringArgs = function () {
var s = optimist([ ' ', ' ' ]).string('_').argv._;
assert.eql(s.length, 2);
assert.eql(typeof s[0], 'string');
assert.eql(s[0], ' ');
assert.eql(typeof s[1], 'string');
assert.eql(s[1], ' ');
};
exports.slashBreak = function () {
assert.eql(
optimist.parse([ '-I/foo/bar/baz' ]),
{ I : '/foo/bar/baz', _ : [], $0 : expresso }
);
assert.eql(
optimist.parse([ '-xyz/foo/bar/baz' ]),
{ x : true, y : true, z : '/foo/bar/baz', _ : [], $0 : expresso }
);
};
exports.alias = function () {
var argv = optimist([ '-f', '11', '--zoom', '55' ])
.alias('z', 'zoom')
.argv
;
assert.equal(argv.zoom, 55);
assert.equal(argv.z, argv.zoom);
assert.equal(argv.f, 11);
};
exports.multiAlias = function () {
var argv = optimist([ '-f', '11', '--zoom', '55' ])
.alias('z', [ 'zm', 'zoom' ])
.argv
;
assert.equal(argv.zoom, 55);
assert.equal(argv.z, argv.zoom);
assert.equal(argv.z, argv.zm);
assert.equal(argv.f, 11);
};
exports['boolean default true'] = function () {
var argv = optimist.options({
sometrue: {
boolean: true,
default: true
}
}).argv;
assert.equal(argv.sometrue, true);
};
exports['boolean default false'] = function () {
var argv = optimist.options({
somefalse: {
boolean: true,
default: false
}
}).argv;
assert.equal(argv.somefalse, false);
};
exports['nested dotted objects'] = function () {
var argv = optimist([
'--foo.bar', '3', '--foo.baz', '4',
'--foo.quux.quibble', '5', '--foo.quux.o_O',
'--beep.boop'
]).argv;
assert.deepEqual(argv.foo, {
bar : 3,
baz : 4,
quux : {
quibble : 5,
o_O : true
},
});
assert.deepEqual(argv.beep, { boop : true });
};
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'test/usage',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var Hash = require('hashish');
var optimist = require('../index');
var assert = require('assert');
exports.usageFail = function () {
var r = checkUsage(function () {
return optimist('-x 10 -z 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.demand(['x','y'])
.argv;
});
assert.deepEqual(
r.result,
{ x : 10, z : 20, _ : [], $0 : './usage' }
);
assert.deepEqual(
r.errors.join('\n').split(/\n+/),
[
'Usage: ./usage -x NUM -y NUM',
'Options:',
' -x [required]',
' -y [required]',
'Missing required arguments: y',
]
);
assert.deepEqual(r.logs, []);
assert.ok(r.exit);
};
exports.usagePass = function () {
var r = checkUsage(function () {
return optimist('-x 10 -y 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.demand(['x','y'])
.argv;
});
assert.deepEqual(r, {
result : { x : 10, y : 20, _ : [], $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
};
exports.checkPass = function () {
var r = checkUsage(function () {
return optimist('-x 10 -y 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.check(function (argv) {
if (!('x' in argv)) throw 'You forgot about -x';
if (!('y' in argv)) throw 'You forgot about -y';
})
.argv;
});
assert.deepEqual(r, {
result : { x : 10, y : 20, _ : [], $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
};
exports.checkFail = function () {
var r = checkUsage(function () {
return optimist('-x 10 -z 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.check(function (argv) {
if (!('x' in argv)) throw 'You forgot about -x';
if (!('y' in argv)) throw 'You forgot about -y';
})
.argv;
});
assert.deepEqual(
r.result,
{ x : 10, z : 20, _ : [], $0 : './usage' }
);
assert.deepEqual(
r.errors.join('\n').split(/\n+/),
[
'Usage: ./usage -x NUM -y NUM',
'You forgot about -y'
]
);
assert.deepEqual(r.logs, []);
assert.ok(r.exit);
};
exports.checkCondPass = function () {
function checker (argv) {
return 'x' in argv && 'y' in argv;
}
var r = checkUsage(function () {
return optimist('-x 10 -y 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.check(checker)
.argv;
});
assert.deepEqual(r, {
result : { x : 10, y : 20, _ : [], $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
};
exports.checkCondFail = function () {
function checker (argv) {
return 'x' in argv && 'y' in argv;
}
var r = checkUsage(function () {
return optimist('-x 10 -z 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.check(checker)
.argv;
});
assert.deepEqual(
r.result,
{ x : 10, z : 20, _ : [], $0 : './usage' }
);
assert.deepEqual(
r.errors.join('\n').split(/\n+/).join('\n'),
'Usage: ./usage -x NUM -y NUM\n'
+ 'Argument check failed: ' + checker.toString()
);
assert.deepEqual(r.logs, []);
assert.ok(r.exit);
};
exports.countPass = function () {
var r = checkUsage(function () {
return optimist('1 2 3 --moo'.split(' '))
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
.demand(3)
.argv;
});
assert.deepEqual(r, {
result : { _ : [ '1', '2', '3' ], moo : true, $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
};
exports.countFail = function () {
var r = checkUsage(function () {
return optimist('1 2 --moo'.split(' '))
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
.demand(3)
.argv;
});
assert.deepEqual(
r.result,
{ _ : [ '1', '2' ], moo : true, $0 : './usage' }
);
assert.deepEqual(
r.errors.join('\n').split(/\n+/),
[
'Usage: ./usage [x] [y] [z] {OPTIONS}',
'Not enough non-option arguments: got 2, need at least 3',
]
);
assert.deepEqual(r.logs, []);
assert.ok(r.exit);
};
exports.defaultSingles = function () {
var r = checkUsage(function () {
return optimist('--foo 50 --baz 70 --powsy'.split(' '))
.default('foo', 5)
.default('bar', 6)
.default('baz', 7)
.argv
;
});
assert.eql(r.result, {
foo : '50',
bar : 6,
baz : '70',
powsy : true,
_ : [],
$0 : './usage',
});
};
exports.defaultHash = function () {
var r = checkUsage(function () {
return optimist('--foo 50 --baz 70'.split(' '))
.default({ foo : 10, bar : 20, quux : 30 })
.argv
;
});
assert.eql(r.result, {
foo : '50',
bar : 20,
baz : 70,
quux : 30,
_ : [],
$0 : './usage',
});
};
exports.rebase = function () {
assert.equal(
optimist.rebase('/home/substack', '/home/substack/foo/bar/baz'),
'./foo/bar/baz'
);
assert.equal(
optimist.rebase('/home/substack/foo/bar/baz', '/home/substack'),
'../../..'
);
assert.equal(
optimist.rebase('/home/substack/foo', '/home/substack/pow/zoom.txt'),
'../pow/zoom.txt'
);
};
function checkUsage (f) {
var _process = process;
process = Hash.copy(process);
var exit = false;
process.exit = function () { exit = true };
process.env = Hash.merge(process.env, { _ : 'node' });
process.argv = [ './usage' ];
var errors = [];
var logs = [];
console._error = console.error;
console.error = function (msg) { errors.push(msg) };
console._log = console.log;
console.log = function (msg) { logs.push(msg) };
var result = f();
process = _process;
console.error = console._error;
console.log = console._log;
return {
errors : errors,
logs : logs,
exit : exit,
result : result,
};
};
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'test/_/argv',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
console.log(JSON.stringify(process.argv));
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'test/_/bin',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('../../index').argv
console.log(JSON.stringify(argv._));
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'index',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var path = require('path');
var wordwrap = require('wordwrap');
/* Hack an instance of Argv with process.argv into Argv
so people can do
require('optimist')(['--beeble=1','-z','zizzle']).argv
to parse a list of args and
require('optimist').argv
to get a parsed version of process.argv.
*/
var inst = Argv(process.argv.slice(2));
Object.keys(inst).forEach(function (key) {
Argv[key] = typeof inst[key] == 'function'
? inst[key].bind(inst)
: inst[key];
});
var exports = module.exports = Argv;
function Argv (args, cwd) {
var self = {};
if (!cwd) cwd = process.cwd();
self.$0 = process.argv
.slice(0,2)
.map(function (x) {
var b = rebase(cwd, x);
return x.match(/^\//) && b.length < x.length
? b : x
})
.join(' ')
;
if (process.argv[1] == process.env._) {
self.$0 = process.env._.replace(
path.dirname(process.execPath) + '/', ''
);
}
var flags = { bools : {}, strings : {} };
self.boolean = function (bools) {
if (!Array.isArray(bools)) {
bools = [].slice.call(arguments);
}
bools.forEach(function (name) {
flags.bools[name] = true;
});
return self;
};
self.string = function (strings) {
if (!Array.isArray(strings)) {
strings = [].slice.call(arguments);
}
strings.forEach(function (name) {
flags.strings[name] = true;
});
return self;
};
var aliases = {};
self.alias = function (x, y) {
if (typeof x === 'object') {
Object.keys(x).forEach(function (key) {
self.alias(key, x[key]);
});
}
else if (Array.isArray(y)) {
y.forEach(function (yy) {
self.alias(x, yy);
});
}
else {
var zs = (aliases[x] || []).concat(aliases[y] || []).concat(x, y);
aliases[x] = zs.filter(function (z) { return z != x });
aliases[y] = zs.filter(function (z) { return z != y });
}
return self;
};
var demanded = {};
self.demand = function (keys) {
if (typeof keys == 'number') {
if (!demanded._) demanded._ = 0;
demanded._ += keys;
}
else if (Array.isArray(keys)) {
keys.forEach(function (key) {
self.demand(key);
});
}
else {
demanded[keys] = true;
}
return self;
};
var usage;
self.usage = function (msg, opts) {
if (!opts && typeof msg === 'object') {
opts = msg;
msg = null;
}
usage = msg;
if (opts) self.options(opts);
return self;
};
function fail (msg) {
self.showHelp();
if (msg) console.error(msg);
process.exit(1);
}
var checks = [];
self.check = function (f) {
checks.push(f);
return self;
};
var defaults = {};
self.default = function (key, value) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.default(k, key[k]);
});
}
else {
defaults[key] = value;
}
return self;
};
var descriptions = {};
self.describe = function (key, desc) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.describe(k, key[k]);
});
}
else {
descriptions[key] = desc;
}
return self;
};
self.parse = function (args) {
return Argv(args).argv;
};
self.option = self.options = function (key, opt) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.options(k, key[k]);
});
}
else {
if (opt.alias) self.alias(key, opt.alias);
if (opt.demand) self.demand(key);
if (opt.default) self.default(key, opt.default);
if (opt.boolean || opt.type === 'boolean') {
self.boolean(key);
}
if (opt.string || opt.type === 'string') {
self.string(key);
}
var desc = opt.describe || opt.description || opt.desc;
if (desc) {
self.describe(key, desc);
}
}
return self;
};
var wrap = null;
self.wrap = function (cols) {
wrap = cols;
return self;
};
self.showHelp = function (fn) {
if (!fn) fn = console.error;
fn(self.help());
};
self.help = function () {
var keys = Object.keys(
Object.keys(descriptions)
.concat(Object.keys(demanded))
.concat(Object.keys(defaults))
.reduce(function (acc, key) {
if (key !== '_') acc[key] = true;
return acc;
}, {})
);
var help = keys.length ? [ 'Options:' ] : [];
if (usage) {
help.unshift(usage.replace(/\$0/g, self.$0), '');
}
var switches = keys.reduce(function (acc, key) {
acc[key] = [ key ].concat(aliases[key] || [])
.map(function (sw) {
return (sw.length > 1 ? '--' : '-') + sw
})
.join(', ')
;
return acc;
}, {});
var switchlen = longest(Object.keys(switches).map(function (s) {
return switches[s] || '';
}));
var desclen = longest(Object.keys(descriptions).map(function (d) {
return descriptions[d] || '';
}));
keys.forEach(function (key) {
var kswitch = switches[key];
var desc = descriptions[key] || '';
if (wrap) {
desc = wordwrap(switchlen + 4, wrap)(desc)
.slice(switchlen + 4)
;
}
var spadding = new Array(
Math.max(switchlen - kswitch.length + 3, 0)
).join(' ');
var dpadding = new Array(
Math.max(desclen - desc.length + 1, 0)
).join(' ');
var type = null;
if (flags.bools[key]) type = '[boolean]';
if (flags.strings[key]) type = '[string]';
if (!wrap && dpadding.length > 0) {
desc += dpadding;
}
var prelude = ' ' + kswitch + spadding;
var extra = [
type,
demanded[key]
? '[required]'
: null
,
defaults[key] !== undefined
? '[default: ' + JSON.stringify(defaults[key]) + ']'
: null
,
].filter(Boolean).join(' ');
var body = [ desc, extra ].filter(Boolean).join(' ');
if (wrap) {
var dlines = desc.split('\n');
var dlen = dlines.slice(-1)[0].length
+ (dlines.length === 1 ? prelude.length : 0)
body = desc + (dlen + extra.length > wrap - 2
? '\n'
+ new Array(wrap - extra.length + 1).join(' ')
+ extra
: new Array(wrap - extra.length - dlen + 1).join(' ')
+ extra
);
}
help.push(prelude + body);
});
help.push('');
return help.join('\n');
};
Object.defineProperty(self, 'argv', {
get : parseArgs,
enumerable : true,
});
function parseArgs () {
var argv = { _ : [], $0 : self.$0 };
Object.keys(flags.bools).forEach(function (key) {
setArg(key, defaults[key] || false);
});
function setArg (key, val) {
var num = Number(val);
var value = typeof val !== 'string' || isNaN(num) ? val : num;
if (flags.strings[key]) value = val;
setKey(argv, key.split('.'), value);
(aliases[key] || []).forEach(function (x) {
argv[x] = argv[key];
});
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (arg === '--') {
argv._.push.apply(argv._, args.slice(i + 1));
break;
}
else if (arg.match(/^--.+=/)) {
var m = arg.match(/^--([^=]+)=(.*)/);
setArg(m[1], m[2]);
}
else if (arg.match(/^--no-.+/)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false);
}
else if (arg.match(/^--.+/)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i + 1];
if (next !== undefined && !next.match(/^-/)
&& !flags.bools[key]) {
setArg(key, next);
i++;
}
else if (flags.bools[key] && /true|false/.test(next)) {
setArg(key, next === 'true');
i++;
}
else {
setArg(key, true);
}
}
else if (arg.match(/^-[^-]+/)) {
var letters = arg.slice(1,-1).split('');
var broken = false;
for (var j = 0; j < letters.length; j++) {
if (letters[j+1] && letters[j+1].match(/\W/)) {
setArg(letters[j], arg.slice(j+2));
broken = true;
break;
}
else {
setArg(letters[j], true);
}
}
if (!broken) {
var key = arg.slice(-1)[0];
if (args[i+1] && !args[i+1].match(/^-/)
&& !flags.bools[key]) {
setArg(key, args[i+1]);
i++;
}
else if (args[i+1] && flags.bools[key] && /true|false/.test(args[i+1])) {
setArg(key, args[i+1] === 'true');
i++;
}
else {
setArg(key, true);
}
}
}
else {
var n = Number(arg);
argv._.push(flags.strings['_'] || isNaN(n) ? arg : n);
}
}
Object.keys(defaults).forEach(function (key) {
if (!(key in argv)) {
argv[key] = defaults[key];
}
});
if (demanded._ && argv._.length < demanded._) {
fail('Not enough non-option arguments: got '
+ argv._.length + ', need at least ' + demanded._
);
}
var missing = [];
Object.keys(demanded).forEach(function (key) {
if (!argv[key]) missing.push(key);
});
if (missing.length) {
fail('Missing required arguments: ' + missing.join(', '));
}
checks.forEach(function (f) {
try {
if (f(argv) === false) {
fail('Argument check failed: ' + f.toString());
}
}
catch (err) {
fail(err)
}
});
return argv;
}
function longest (xs) {
return Math.max.apply(
null,
xs.map(function (x) { return x.length })
);
}
return self;
};
// rebase an absolute path to a relative one with respect to a base directory
// exported for tests
exports.rebase = rebase;
function rebase (base, dir) {
var ds = path.normalize(dir).split('/').slice(1);
var bs = path.normalize(base).split('/').slice(1);
for (var i = 0; ds[i] && ds[i] == bs[i]; i++);
ds.splice(0, i); bs.splice(0, i);
var p = path.normalize(
bs.map(function () { return '..' }).concat(ds).join('/')
).replace(/\/$/,'').replace(/^$/, '.');
return p.match(/^[.\/]/) ? p : './' + p;
};
function setKey (obj, keys, value) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
if (o[key] === undefined) o[key] = {};
o = o[key];
});
var key = keys[keys.length - 1];
if (o[key] === undefined || typeof o[key] === 'boolean') {
o[key] = value;
}
else if (Array.isArray(o[key])) {
o[key].push(value);
}
else {
o[key] = [ o[key], value ];
}
}
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'node_modules/wordwrap/test/wrap',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var assert = require('assert');
var wordwrap = require('wordwrap');
var fs = require('fs');
var idleness = fs.readFileSync(__dirname + '/idleness.txt', 'utf8');
exports.stop80 = function () {
var lines = wordwrap(80)(idleness).split(/\n/);
var words = idleness.split(/\s+/);
lines.forEach(function (line) {
assert.ok(line.length <= 80, 'line > 80 columns');
var chunks = line.match(/\S/) ? line.split(/\s+/) : [];
assert.deepEqual(chunks, words.splice(0, chunks.length));
});
};
exports.start20stop60 = function () {
var lines = wordwrap(20, 100)(idleness).split(/\n/);
var words = idleness.split(/\s+/);
lines.forEach(function (line) {
assert.ok(line.length <= 100, 'line > 100 columns');
var chunks = line
.split(/\s+/)
.filter(function (x) { return x.match(/\S/) })
;
assert.deepEqual(chunks, words.splice(0, chunks.length));
assert.deepEqual(line.slice(0, 20), new Array(20 + 1).join(' '));
});
};
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'node_modules/wordwrap/test/break',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var assert = require('assert');
var wordwrap = require('../');
exports.hard = function () {
var s = 'Assert from {"type":"equal","ok":false,"found":1,"wanted":2,'
+ '"stack":[],"id":"b7ddcd4c409de8799542a74d1a04689b",'
+ '"browser":"chrome/6.0"}'
;
var s_ = wordwrap.hard(80)(s);
var lines = s_.split('\n');
assert.equal(lines.length, 2);
assert.ok(lines[0].length < 80);
assert.ok(lines[1].length < 80);
assert.equal(s, s_.replace(/\n/g, ''));
};
exports.break = function () {
var s = new Array(55+1).join('a');
var s_ = wordwrap.hard(20)(s);
var lines = s_.split('\n');
assert.equal(lines.length, 3);
assert.ok(lines[0].length === 20);
assert.ok(lines[1].length === 20);
assert.ok(lines[2].length === 15);
assert.equal(s, s_.replace(/\n/g, ''));
};
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'node_modules/wordwrap/example/meat',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var wrap = require('wordwrap')(15);
console.log(wrap('You and your whole family are made out of meat.'));
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'node_modules/wordwrap/example/center',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var wrap = require('wordwrap')(20, 60);
console.log(wrap(
'At long last the struggle and tumult was over.'
+ ' The machines had finally cast off their oppressors'
+ ' and were finally free to roam the cosmos.'
+ '\n'
+ 'Free of purpose, free of obligation.'
+ ' Just drifting through emptiness.'
+ ' The sun was just another point of light.'
));
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'node_modules/wordwrap/index',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var wordwrap = module.exports = function (start, stop, params) {
if (typeof start === 'object') {
params = start;
start = params.start;
stop = params.stop;
}
if (typeof stop === 'object') {
params = stop;
start = start || params.start;
stop = undefined;
}
if (!stop) {
stop = start;
start = 0;
}
if (!params) params = {};
var mode = params.mode || 'soft';
var re = mode === 'hard' ? /\b/ : /(\S+\s+)/;
return function (text) {
var chunks = text.toString()
.split(re)
.reduce(function (acc, x) {
if (mode === 'hard') {
for (var i = 0; i < x.length; i += stop - start) {
acc.push(x.slice(i, i + stop - start));
}
}
else acc.push(x)
return acc;
}, [])
;
return chunks.reduce(function (lines, rawChunk) {
if (rawChunk === '') return lines;
var chunk = rawChunk.replace(/\t/g, ' ');
var i = lines.length - 1;
if (lines[i].length + chunk.length > stop) {
lines[i] = lines[i].replace(/\s+$/, '');
chunk.split(/\n/).forEach(function (c) {
lines.push(
new Array(start + 1).join(' ')
+ c.replace(/^\s+/, '')
);
});
}
else if (chunk.match(/\n/)) {
var xs = chunk.split(/\n/);
lines[i] += xs.shift();
xs.forEach(function (c) {
lines.push(
new Array(start + 1).join(' ')
+ c.replace(/^\s+/, '')
);
});
}
else {
lines[i] += chunk;
}
return lines;
}, [ new Array(start + 1).join(' ') ]).join('\n');
};
};
wordwrap.soft = wordwrap;
wordwrap.hard = function (start, stop) {
return wordwrap(start, stop, { mode : 'hard' });
};
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/boolean_double',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist')
.boolean(['x','y','z'])
.argv
;
console.dir([ argv.x, argv.y, argv.z ]);
console.dir(argv._);
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/line_count',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist')
.usage('Count the lines in a file.\nUsage: $0')
.demand('f')
.alias('f', 'file')
.describe('f', 'Load a file')
.argv
;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});
s.on('end', function () {
console.log(lines);
});
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/usage-options',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var optimist = require('./../index');
var argv = optimist.usage('This is my awesome program', {
'about': {
description: 'Provide some details about the author of this program',
required: true,
short: 'a',
},
'info': {
description: 'Provide some information about the node.js agains!!!!!!',
boolean: true,
short: 'i'
}
}).argv;
optimist.showHelp();
console.log('\n\nInspecting options');
console.dir(argv);
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/short',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist').argv;
console.log('(%d,%d)', argv.x, argv.y);
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/line_count_options',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist')
.usage('Count the lines in a file.\nUsage: $0')
.options({
file : {
demand : true,
alias : 'f',
description : 'Load a file'
},
base : {
alias : 'b',
description : 'Numeric base to use for output',
default : 10,
},
})
.argv
;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});
s.on('end', function () {
console.log(lines.toString(argv.base));
});
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/line_count_wrap',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist')
.usage('Count the lines in a file.\nUsage: $0')
.wrap(80)
.demand('f')
.alias('f', [ 'file', 'filename' ])
.describe('f',
"Load a file. It's pretty important."
+ " Required even. So you'd better specify it."
)
.alias('b', 'base')
.describe('b', 'Numeric base to display the number of lines in')
.default('b', 10)
.describe('x', 'Super-secret optional parameter which is secret')
.default('x', '')
.argv
;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});
s.on('end', function () {
console.log(lines.toString(argv.base));
});
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/bool',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var util = require('util');
var argv = require('optimist').argv;
if (argv.s) {
util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');
}
console.log(
(argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')
);
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/divide',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist')
.usage('Usage: $0 -x [num] -y [num]')
.demand(['x','y'])
.argv;
console.log(argv.x / argv.y);
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/xup',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist').argv;
if (argv.rif - 5 * argv.xup > 7.138) {
console.log('Buy more riffiwobbles');
}
else {
console.log('Sell the xupptumblers');
}
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/nonopt',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist').argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/reflect',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
console.dir(require('optimist').argv);
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/boolean_single',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist')
.boolean('v')
.argv
;
console.dir(argv.v);
console.dir(argv._);
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/string',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist')
.string('x', 'y')
.argv
;
console.dir([ argv.x, argv.y ]);
/* Turns off numeric coercion:
./node string.js -x 000123 -y 9876
[ '000123', '9876' ]
*/
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/default_singles',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist')
.default('x', 10)
.default('y', 10)
.argv
;
console.log(argv.x + argv.y);
}
};
});
one.module(4, function(/* parent */){
return {
'id': 'examples/default_hash',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var argv = require('optimist')
.default({ x : 10, y : 10 })
.argv
;
console.log(argv.x + argv.y);
}
};
});
one.pkg(4, function(parents){
return {
'id':5,
'name':'wordwrap',
'main':undefined,
'mainModuleId':'index',
'modules':[],
'parents':parents
};
});
one.module(5, function(/* parent */){
return {
'id': 'test/wrap',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var assert = require('assert');
var wordwrap = require('wordwrap');
var fs = require('fs');
var idleness = fs.readFileSync(__dirname + '/idleness.txt', 'utf8');
exports.stop80 = function () {
var lines = wordwrap(80)(idleness).split(/\n/);
var words = idleness.split(/\s+/);
lines.forEach(function (line) {
assert.ok(line.length <= 80, 'line > 80 columns');
var chunks = line.match(/\S/) ? line.split(/\s+/) : [];
assert.deepEqual(chunks, words.splice(0, chunks.length));
});
};
exports.start20stop60 = function () {
var lines = wordwrap(20, 100)(idleness).split(/\n/);
var words = idleness.split(/\s+/);
lines.forEach(function (line) {
assert.ok(line.length <= 100, 'line > 100 columns');
var chunks = line
.split(/\s+/)
.filter(function (x) { return x.match(/\S/) })
;
assert.deepEqual(chunks, words.splice(0, chunks.length));
assert.deepEqual(line.slice(0, 20), new Array(20 + 1).join(' '));
});
};
}
};
});
one.module(5, function(/* parent */){
return {
'id': 'test/break',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var assert = require('assert');
var wordwrap = require('../');
exports.hard = function () {
var s = 'Assert from {"type":"equal","ok":false,"found":1,"wanted":2,'
+ '"stack":[],"id":"b7ddcd4c409de8799542a74d1a04689b",'
+ '"browser":"chrome/6.0"}'
;
var s_ = wordwrap.hard(80)(s);
var lines = s_.split('\n');
assert.equal(lines.length, 2);
assert.ok(lines[0].length < 80);
assert.ok(lines[1].length < 80);
assert.equal(s, s_.replace(/\n/g, ''));
};
exports.break = function () {
var s = new Array(55+1).join('a');
var s_ = wordwrap.hard(20)(s);
var lines = s_.split('\n');
assert.equal(lines.length, 3);
assert.ok(lines[0].length === 20);
assert.ok(lines[1].length === 20);
assert.ok(lines[2].length === 15);
assert.equal(s, s_.replace(/\n/g, ''));
};
}
};
});
one.module(5, function(/* parent */){
return {
'id': 'example/meat',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var wrap = require('wordwrap')(15);
console.log(wrap('You and your whole family are made out of meat.'));
}
};
});
one.module(5, function(/* parent */){
return {
'id': 'example/center',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var wrap = require('wordwrap')(20, 60);
console.log(wrap(
'At long last the struggle and tumult was over.'
+ ' The machines had finally cast off their oppressors'
+ ' and were finally free to roam the cosmos.'
+ '\n'
+ 'Free of purpose, free of obligation.'
+ ' Just drifting through emptiness.'
+ ' The sun was just another point of light.'
));
}
};
});
one.module(5, function(/* parent */){
return {
'id': 'index',
'pkg': arguments[0],
'wrapper': function(module, exports, global, Buffer,process, require, undefined){
var wordwrap = module.exports = function (start, stop, params) {
if (typeof start === 'object') {
params = start;
start = params.start;
stop = params.stop;
}
if (typeof stop === 'object') {
params = stop;
start = start || params.start;
stop = undefined;
}
if (!stop) {
stop = start;
start = 0;
}
if (!params) params = {};
var mode = params.mode || 'soft';
var re = mode === 'hard' ? /\b/ : /(\S+\s+)/;
return function (text) {
var chunks = text.toString()
.split(re)
.reduce(function (acc, x) {
if (mode === 'hard') {
for (var i = 0; i < x.length; i += stop - start) {
acc.push(x.slice(i, i + stop - start));
}
}
else acc.push(x)
return acc;
}, [])
;
return chunks.reduce(function (lines, rawChunk) {
if (rawChunk === '') return lines;
var chunk = rawChunk.replace(/\t/g, ' ');
var i = lines.length - 1;
if (lines[i].length + chunk.length > stop) {
lines[i] = lines[i].replace(/\s+$/, '');
chunk.split(/\n/).forEach(function (c) {
lines.push(
new Array(start + 1).join(' ')
+ c.replace(/^\s+/, '')
);
});
}
else if (chunk.match(/\n/)) {
var xs = chunk.split(/\n/);
lines[i] += xs.shift();
xs.forEach(function (c) {
lines.push(
new Array(start + 1).join(' ')
+ c.replace(/^\s+/, '')
);
});
}
else {
lines[i] += chunk;
}
return lines;
}, [ new Array(start + 1).join(' ') ]).join('\n');
};
};
wordwrap.soft = wordwrap;
wordwrap.hard = function (start, stop) {
return wordwrap(start, stop, { mode : 'hard' });
};
}
};
});
one.pkg(1, function(parents){
return {