/* this rollup was created with utility2 (https://github.com/kaizhu256/node-utility2) */
/*
assets.app.js
openid app
instruction
1. save this script as assets.app.js
2. run the shell command:
$ PORT=8081 node assets.app.js
3. open a browser to http://127.0.0.1:8081 and play with the web-demo
4. edit this script to suit your needs
*/
/* utility2.rollup.js begin */
/* istanbul ignore all */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 100,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
"use strict";
var local;
local = {};
local.modeJs = (function () {
try {
return typeof navigator.userAgent === "string" &&
typeof document.querySelector("body") === "object" &&
typeof XMLHttpRequest.prototype.open === "function" &&
"browser";
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === "string" &&
typeof require("http").createServer === "function" &&
"node";
}
}());
local.global = local.modeJs === "browser"
? window
: global;
local.local = local.global.utility2_app = local.global.utility2_app_old || local;
local.global.utility2_app_old = null;
}());
/* script-begin /assets.utility2.rollup.js */
/* this rollup was created with utility2 (https://github.com/kaizhu256/node-utility2) */
/* script-begin /assets.utility2.rollup.begin.js */
/* utility2.rollup.js begin */
/* istanbul ignore all */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 100,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
"use strict";
var local;
local = {};
local.modeJs = (function () {
try {
return typeof navigator.userAgent === "string" &&
typeof document.querySelector("body") === "object" &&
typeof XMLHttpRequest.prototype.open === "function" &&
"browser";
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === "string" &&
typeof require("http").createServer === "function" &&
"node";
}
}());
local.global = local.modeJs === "browser"
? window
: global;
local.local = local.global.utility2_rollup = local.global.utility2_rollup_old || local;
local.global.utility2_rollup_old = null;
}());
/* script-end /assets.utility2.rollup.begin.js */
/* script-begin /assets.utility2.lib.apidoc.js */
///usr/bin/env node
/* istanbul instrument in package apidoc */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 100,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || local;
/* istanbul ignore next */
if (!local) {
local = local.global.utility2_rollup ||
local.global.utility2_rollup_old ||
require('./assets.utility2.rollup.js');
local.fs = null;
}
// init exports
if (local.modeJs === 'browser') {
local.global.utility2_apidoc = local;
} else {
// require builtins
Object.keys(process.binding('natives')).forEach(function (key) {
if (!local[key] && !(/\/|^_|^sys$/).test(key)) {
local[key] = require(key);
}
});
module.exports = local;
module.exports.__dirname = __dirname;
}
// init lib
local.local = local.apidoc = local;
}());
// run shared js-env code - function-before
/* istanbul ignore next */
(function () {
local.assert = function (passed, message) {
/*
* this function will throw the error message if passed is falsey
*/
var error;
if (passed) {
return;
}
error = message && message.message
// if message is an error-object, then leave it as is
? message
: new Error(typeof message === 'string'
// if message is a string, then leave it as is
? message
// else JSON.stringify message
: JSON.stringify(message));
throw error;
};
local.cliRun = function (fnc) {
/*
* this function will run the cli
*/
var nop;
nop = function () {
/*
* this function will do nothing
*/
return;
};
local.cliDict._eval = local.cliDict._eval || function () {
/*
* code
* eval code
*/
local.global.local = local;
require('vm').runInThisContext(process.argv[3]);
};
local.cliDict['--eval'] = local.cliDict['--eval'] || local.cliDict._eval;
local.cliDict['-e'] = local.cliDict['-e'] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
* [none]
* print help
*/
var element, result, lengthList, sortDict;
sortDict = {};
result = [['[command]', '[args]', '[description]', -1]];
lengthList = [result[0][0].length, result[0][1].length];
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === '_' && key !== '_default') {
return;
}
sortDict[local.cliDict[key].toString()] =
sortDict[local.cliDict[key].toString()] || (ii + 1);
element = (/\n +\*(.*)\n +\*(.*)/).exec(local.cliDict[key].toString());
// coverage-hack - ignore else-statement
nop(local.global.__coverage__ && (function () {
element = element || ['', '', ''];
}()));
element = [
key.replace('_default', '[none]') + ' ',
element[1].trim() + ' ',
element[2].trim(),
(sortDict[local.cliDict[key].toString()] << 8) + ii
];
result.push(element);
lengthList.forEach(function (length, jj) {
lengthList[jj] = Math.max(element[jj].length, length);
});
});
result.sort(function (aa, bb) {
return aa[3] < bb[3]
? -1
: 1;
});
console.log('usage: ' + __filename + ' [command] [args]');
console.log('example: ' + __filename + ' --eval ' +
'"console.log(\'hello world\')"\n');
result.forEach(function (element, ii) {
lengthList.forEach(function (length, jj) {
while (element[jj].length < length) {
element[jj] += '-';
}
});
element = element.slice(0, 3).join('---- ');
if (ii === 0) {
element = element.replace((/-/g), ' ');
}
console.log(element);
});
};
local.cliDict['--help'] = local.cliDict['--help'] || local.cliDict._help;
local.cliDict['-h'] = local.cliDict['-h'] || local.cliDict._help;
local.cliDict._default = local.cliDict._default || local.cliDict._help;
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
* [none]
* start interactive-mode
*/
local.global.local = local;
local.replStart();
};
if (local.replStart) {
local.cliDict['--interactive'] = local.cliDict['--interactive'] ||
local.cliDict._interactive;
local.cliDict['-i'] = local.cliDict['-i'] || local.cliDict._interactive;
}
// run fnc()
fnc = fnc || function () {
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
fnc();
};
local.moduleDirname = function (module, modulePathList) {
/*
* this function will search modulePathList for the module's __dirname
*/
var result, tmp;
// search process.cwd()
if (!module || module === '.' || module.indexOf('/') >= 0) {
return require('path').resolve(process.cwd(), module || '');
}
// search modulePathList
['node_modules']
.concat(modulePathList)
.concat(require('module').globalPaths)
.concat([process.env.HOME + '/node_modules', '/usr/local/lib/node_modules'])
.some(function (modulePath) {
try {
tmp = require('path').resolve(process.cwd(), modulePath + '/' + module);
result = require('fs').statSync(tmp).isDirectory() && tmp;
return result;
} catch (ignore) {
}
});
return result || '';
};
local.nop = function () {
/*
* this function will do nothing
*/
return;
};
local.objectSetDefault = function (arg, defaults, depth) {
/*
* this function will recursively set defaults for undefined-items in the arg
*/
arg = arg || {};
defaults = defaults || {};
Object.keys(defaults).forEach(function (key) {
var arg2, defaults2;
arg2 = arg[key];
// handle misbehaving getter
try {
defaults2 = defaults[key];
} catch (ignore) {
}
if (defaults2 === undefined) {
return;
}
// init arg[key] to default value defaults[key]
switch (arg2) {
case '':
case null:
case undefined:
arg[key] = defaults2;
return;
}
// if arg2 and defaults2 are both non-null and non-array objects,
// then recurse with arg2 and defaults2
if (depth > 1 &&
// arg2 is a non-null and non-array object
arg2 &&
typeof arg2 === 'object' &&
!Array.isArray(arg2) &&
// defaults2 is a non-null and non-array object
defaults2 &&
typeof defaults2 === 'object' &&
!Array.isArray(defaults2)) {
// recurse
local.objectSetDefault(arg2, defaults2, depth - 1);
}
});
return arg;
};
local.stringHtmlSafe = function (text) {
/*
* this function will make the text html-safe
*/
// new RegExp('[' + '"&\'<>'.split('').sort().join('') + ']', 'g')
return text.replace((/["&'<>]/g), function (match0) {
return '' + match0.charCodeAt(0).toString(16) + ';';
});
};
local.templateRender = function (template, dict, options) {
/*
* this function will render the template with the given dict
*/
var argList, getValue, match, renderPartial, rgx, tryCatch, value;
dict = dict || {};
options = options || {};
getValue = function (key) {
argList = key.split(' ');
value = dict;
// iteratively lookup nested values in the dict
argList[0].split('.').forEach(function (key) {
value = value && value[key];
});
return value;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case 'each':
value = getValue(key);
return Array.isArray(value)
? value.map(function (dict) {
// recurse with partial
return local.templateRender(partial, dict, options);
}).join('')
: '';
case 'if':
partial = partial.split('{{#unless ' + key + '}}');
partial = getValue(key)
? partial[0]
// handle 'unless' case
: partial.slice(1).join('{{#unless ' + key + '}}');
// recurse with partial
return local.templateRender(partial, dict, options);
case 'unless':
return getValue(key)
? ''
// recurse with partial
: local.templateRender(partial, dict, options);
default:
// recurse with partial
return match0[0] + local.templateRender(match0.slice(1), dict, options);
}
};
tryCatch = function (fnc, message) {
/*
* this function will prepend the message to errorCaught
*/
try {
return fnc();
} catch (errorCaught) {
errorCaught.message = message + errorCaught.message;
throw errorCaught;
}
};
// render partials
rgx = (/\{\{#(\w+) ([^}]+?)\}\}/g);
template = template || '';
for (match = rgx.exec(template); match; match = rgx.exec(template)) {
rgx.lastIndex += 1 - match[0].length;
template = template.replace(
new RegExp('\\{\\{#(' + match[1] + ') (' + match[2] +
')\\}\\}([\\S\\s]*?)\\{\\{/' + match[1] + ' ' + match[2] +
'\\}\\}'),
renderPartial
);
}
// search for keys in the template
return template.replace((/\{\{[^}]+?\}\}/g), function (match0) {
var markdownToHtml, notHtmlSafe;
notHtmlSafe = options.notHtmlSafe;
return tryCatch(function () {
getValue(match0.slice(2, -2));
if (value === undefined) {
return match0;
}
argList.slice(1).forEach(function (arg) {
switch (arg) {
case 'alphanumeric':
value = value.replace((/\W/g), '_');
break;
case 'decodeURIComponent':
value = decodeURIComponent(value);
break;
case 'encodeURIComponent':
value = encodeURIComponent(value);
break;
case 'jsonStringify':
value = JSON.stringify(value);
break;
case 'jsonStringify4':
value = JSON.stringify(value, null, 4);
break;
case 'markdownSafe':
value = value.replace((/`/g), '\'');
break;
case 'markdownToHtml':
markdownToHtml = true;
break;
case 'notHtmlSafe':
notHtmlSafe = true;
break;
// default to String.prototype[arg]()
default:
value = value[arg]();
break;
}
});
value = String(value);
// default to htmlSafe
if (!notHtmlSafe) {
value = value.replace((/["&'<>]/g), function (match0) {
return '' + match0.charCodeAt(0).toString(16) + ';';
});
}
if (markdownToHtml) {
value = local.marked(value);
}
return value;
}, 'templateRender could not render expression ' + JSON.stringify(match0) + '\n');
});
};
local.tryCatchOnError = function (fnc, onError) {
/*
* this function will try to run the fnc in a try-catch block,
* else call onError with the errorCaught
*/
var result;
// validate onError
local.assert(typeof onError === 'function', typeof onError);
try {
// reset errorCaught
local._debugTryCatchError = null;
result = fnc();
local._debugTryCatchError = null;
return result;
} catch (errorCaught) {
// debug errorCaught
local._debugTryCatchError = errorCaught;
return onError(errorCaught);
}
};
}());
// run shared js-env code - init-before
/* jslint-ignore-begin */
local.templateApidocHtml = '\
\n\
\n\
\n\
{{env.npm_package_description}}
\n\
\n\
{{#each moduleList}}\n\
\n\
\n\
{{#each elementList}}\n\
{{#if source}}\n\
\n\
\n\
- description and source-code
{{source}}
\n\
- example usage
{{example}}
\n\
\n\
{{/if source}}\n\
{{/each elementList}}\n\
\n\
{{/each moduleList}}\n\
\n\
\n\
';
/* jslint-ignore-end */
// run shared js-env code - function
(function () {
local.apidocCreate = function (options) {
/*
* this function will create the apidoc from options.dir
*/
var elementCreate, module, moduleMain, readExample, tmp, toString, trimLeft;
elementCreate = function (module, prefix, key) {
/*
* this function will create the apidoc-element in the given module
*/
var element;
if (options.modeNoApidoc) {
return element;
}
element = {};
element.moduleName = prefix.split('.');
// handle case where module is a function
if (element.moduleName.slice(-1)[0] === key) {
element.moduleName.pop();
}
element.moduleName = element.moduleName.join('.');
element.id = encodeURIComponent('apidoc.element.' + prefix + '.' + key);
element.typeof = typeof module[key];
element.name = (element.typeof + ' ' +
element.moduleName + '.' + key)
// handle case where module is a function
.replace('>.<', '><');
if (element.typeof !== 'function') {
return element;
}
// init source
element.source = trimLeft(toString(module[key])) || 'n/a';
if (element.source.length > 4096) {
element.source = element.source.slice(0, 4096).trimRight() + ' ...';
}
element.source = local.stringHtmlSafe(element.source)
.replace((/\([\S\s]*?\)/), function (match0) {
// init signature
element.signature = match0
.replace((/ *?\/\*[\S\s]*?\*\/ */g), '')
.replace((/,/g), ', ')
.replace((/\s+/g), ' ');
return element.signature;
})
.replace(
(/( *?\/\*[\S\s]*?\*\/\n)/),
''
)
.replace((/^function \(/), key + ' = function (');
// init example
options.exampleList.some(function (example) {
example.replace(
new RegExp('((?:\n.*?){8}\\.)(' + key + ')(\\((?:.*?\n){8})'),
function (match0, match1, match2, match3) {
// jslint-hack
local.nop(match0);
element.example = '...' + trimLeft(local.stringHtmlSafe(match1) +
'' +
local.stringHtmlSafe(match2) +
'' +
local.stringHtmlSafe(match3)).trimRight() + '\n...';
}
);
return element.example;
});
element.example = element.example || 'n/a';
return element;
};
readExample = function (file) {
/*
* this function will read the example from the given file
*/
var result;
local.tryCatchOnError(function () {
file = local.path.resolve(options.dir, file);
console.error('apidocCreate - readExample ' + file);
result = '';
result = ('\n\n\n\n\n\n\n\n' +
local.fs.readFileSync(file, 'utf8').slice(0, 262144) +
'\n\n\n\n\n\n\n\n').replace((/\r\n*/g), '\n');
}, console.error);
return result;
};
toString = function (value) {
/*
* this function will try to return the string form of the value
*/
var result;
local.tryCatchOnError(function () {
result = '';
result = String(value);
}, console.error);
return result;
};
trimLeft = function (text) {
/*
* this function will normalize the whitespace around the text
*/
var whitespace;
whitespace = '';
text.trim().replace((/^ */gm), function (match0) {
if (!whitespace || match0.length < whitespace.length) {
whitespace = match0;
}
});
text = text.replace(new RegExp('^' + whitespace, 'gm'), '');
// enforce 128 character column limit
text = text.replace((/^.{128}[^\\\n]+/gm), function (match0) {
return match0.replace((/(.{128}(?:\b|\w+))/g), '$1\n').trimRight();
});
return text;
};
// init options
options.dir = local.moduleDirname(
options.dir,
options.modulePathList || local.module.paths
);
local.objectSetDefault(options, {
env: { npm_package_description: '' },
packageJson: JSON.parse(readExample('package.json')),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
}, console.error);
}
});
Object.keys(options.packageJson).forEach(function (key) {
tmp = options.packageJson[key];
// strip email from npmdoc documentation
// https://github.com/npmdoc/node-npmdoc-hpp/issues/1
if (tmp) {
if (tmp.email) {
delete tmp.email;
}
if (Array.isArray(tmp)) {
tmp.forEach(function (element) {
if (element && element.email) {
delete element.email;
}
});
}
}
if (key[0] === '_' || key === 'readme') {
delete options.packageJson[key];
} else if (typeof tmp === 'string') {
options.env['npm_package_' + key] = tmp;
}
});
local.objectSetDefault(options, {
blacklistDict: { global: global },
circularList: [global],
exampleDict: {},
exampleList: [],
html: '',
libFileList: [],
moduleDict: {},
moduleExtraDict: {},
packageJson: { bin: {} },
template: local.templateApidocHtml,
whitelistDict: {}
}, 2);
// init exampleList
[1, 2, 3, 4].forEach(function (depth) {
options.exampleList = options.exampleList.concat(
// http://stackoverflow.com
// /questions/4509624/how-to-limit-depth-for-recursive-file-list
// find . -maxdepth 1 -mindepth 1 -name "*.js" -type f
local.child_process.execSync('find "' + options.dir +
'" -maxdepth ' + depth + ' -mindepth ' + depth +
' -type f | sed -e "s|' + options.dir +
'/||" | grep -iv ' +
/* jslint-ignore-begin */
'"\
/\\.\\|\\(\\b\\|_\\)\\(\
bower_component\\|\
coverage\\|\
git\\|\
min\\|\
node_module\\|\
rollup\\|\
tmp\\|\
vendor\\)s\\{0,1\\}\\(\\b\\|_\\)\
" ' +
/* jslint-ignore-end */
' | sort | head -n 256').toString()
.split('\n')
);
});
options.exampleList = options.exampleList.filter(function (file) {
if (file && !options.exampleDict[file]) {
options.exampleDict[file] = true;
return true;
}
}).slice(0, 256).map(readExample);
// init moduleMain
local.tryCatchOnError(function () {
console.error('apidocCreate - requiring ' + options.dir + ' ...');
moduleMain = {};
moduleMain = options.moduleDict[options.env.npm_package_name] ||
options.require(options.dir) ||
options.require(options.dir + '/' +
(options.packageJson.bin)[Object.keys(options.packageJson.bin)[0]]) || {};
options.circularList.push(moduleMain);
console.error('apidocCreate - ... required ' + options.dir);
}, console.error);
tmp = {};
// handle case where module is a function
if (typeof moduleMain === 'function') {
(function () {
var text;
text = toString(moduleMain);
tmp = function () {
return;
};
// coverage-hack
tmp();
Object.defineProperties(tmp, { toString: { get: function () {
return function () {
return text;
};
} } });
}());
}
// normalize moduleMain
moduleMain = options.moduleDict[options.env.npm_package_name] = local.objectSetDefault(
tmp,
moduleMain
);
// init circularList - builtin
Object.keys(process.binding('natives')).forEach(function (key) {
if (!(/\/|^_linklist$|^sys$/).test(key)) {
options.circularList.push(require(key));
}
});
// init circularList - blacklistDict
Object.keys(options.blacklistDict).forEach(function (key) {
options.circularList.push(options.blacklistDict[key]);
});
// init circularList - moduleDict
Object.keys(options.moduleDict).forEach(function (key) {
options.circularList.push(options.moduleDict[key]);
});
// init circularList - prototype
Object.keys(options.circularList).forEach(function (key) {
tmp = options.circularList[key];
options.circularList.push(tmp && tmp.prototype);
});
// deduplicate circularList
tmp = options.circularList;
options.circularList = [];
tmp.forEach(function (element) {
if (options.circularList.indexOf(element) < 0) {
options.circularList.push(element);
}
});
// init moduleDict child
local.apidocModuleDictAdd(options, options.moduleDict);
// init swgg.apiDict
Object.keys((moduleMain.swgg && moduleMain.swgg.apiDict) || {}).forEach(function (key) {
tmp = 'swgg.apiDict';
tmp = options.moduleDict[tmp] = options.moduleDict[tmp] || {};
tmp[key + '.ajax'] = moduleMain.swgg.apiDict[key] &&
moduleMain.swgg.apiDict[key].ajax;
});
// init moduleExtraDict
module = options.moduleExtraDict[options.env.npm_package_name] =
options.moduleExtraDict[options.env.npm_package_name] || {};
[1, 2, 3, 4].forEach(function (depth) {
options.libFileList = options.libFileList.concat(
// http://stackoverflow.com
// /questions/4509624/how-to-limit-depth-for-recursive-file-list
// find . -maxdepth 1 -mindepth 1 -name "*.js" -type f
local.child_process.execSync('find "' + options.dir +
'" -maxdepth ' + depth + ' -mindepth ' + depth +
' -name "*.js" -type f | sed -e "s|' + options.dir +
'/||" | grep -iv ' +
/* jslint-ignore-begin */
'"\
/\\.\\|\\(\\b\\|_\\)\\(\
archive\\|artifact\\|asset\\|\
bower_component\\|build\\|\
coverage\\|\
doc\\|dist\\|\
example\\|external\\|\
fixture\\|\
git\\|\
log\\|\
min\\|mock\\|\
node_module\\|\
rollup\\|\
spec\\|\
test\\|tmp\\|\
vendor\\)s\\{0,1\\}\\(\\b\\|_\\)\
" ' +
/* jslint-ignore-end */
' | sort | head -n 256').toString()
.split('\n')
);
});
options.ii = 256;
options.libFileList.every(function (file) {
local.tryCatchOnError(function () {
tmp = {};
tmp.name = local.path.basename(file)
.replace('lib.', '')
.replace((/\.[^.]*?$/), '')
.replace((/\W/g), '_');
[
tmp.name,
tmp.name.slice(0, 1).toUpperCase() + tmp.name.slice(1)
].some(function (name) {
tmp.isFiltered = name && (!options.packageJson.main ||
('./' + file).indexOf(options.packageJson.main) < 0) &&
!module[name];
return !tmp.isFiltered;
});
if (!tmp.isFiltered) {
return;
}
console.error('apidocCreate - libFile ' + file);
tmp.module = options.require(options.dir + '/' + file);
// filter circular-reference
if (!(tmp.module && options.circularList.indexOf(tmp.module) < 0)) {
return;
}
options.ii -= 1;
module[tmp.name] = tmp.module;
}, console.error);
return options.ii;
});
local.apidocModuleDictAdd(options, options.moduleExtraDict);
Object.keys(options.moduleDict).forEach(function (key) {
if (key.indexOf(options.env.npm_package_name + '.') !== 0) {
return;
}
tmp = key.split('.').slice(1).join('.');
moduleMain[tmp] = moduleMain[tmp] || options.moduleDict[key];
});
// init moduleList
options.moduleList = Object.keys(options.moduleDict)
.sort()
.map(function (prefix) {
module = options.moduleDict[prefix];
// handle case where module is a function
if (typeof module === 'function') {
local.tryCatchOnError(function () {
module[prefix.split('.').slice(-1)[0]] =
module[prefix.split('.').slice(-1)[0]] || module;
}, console.error);
}
return {
elementList: Object.keys(module)
.filter(function (key) {
return local.tryCatchOnError(function () {
return key &&
(/^\w[\w\-.]*?$/).test(key) &&
key.indexOf('testCase_') !== 0 &&
(module[key] !== options.blacklistDict[key]
|| options.whitelistDict[key]);
}, console.error);
})
.map(function (key) {
return elementCreate(module, prefix, key);
})
.sort(function (aa, bb) {
return aa.name > bb.name
? 1
: -1;
}),
id: encodeURIComponent('apidoc.module.' + prefix),
name: prefix
};
});
// render apidoc
options.result = local.templateRender(options.template, options, { notHtmlSafe: true })
.trim()
.replace((/ +$/gm), '') + '\n';
return options.result;
};
local.apidocModuleDictAdd = function (options, moduleDict) {
/*
* this function will add the modules in moduleDict to options.moduleDict
*/
var isModule, tmp;
['child', 'prototype', 'grandchild', 'prototype'].forEach(function (element) {
Object.keys(moduleDict).sort().forEach(function (prefix) {
if (!(/^\w[\w\-.]*?$/).test(prefix)) {
return;
}
Object.keys(moduleDict[prefix]).forEach(function (key) {
// bug-workaround - buggy electron getter / setter
local.tryCatchOnError(function () {
if (!(/^\w[\w\-.]*?$/).test(key) || !moduleDict[prefix][key]) {
return;
}
tmp = element === 'prototype'
? {
module: moduleDict[prefix][key].prototype,
name: prefix + '.' + key + '.prototype'
}
: {
module: moduleDict[prefix][key],
name: prefix + '.' + key
};
if (!tmp.module ||
!(typeof tmp.module === 'function' ||
typeof tmp.module === 'object') ||
Array.isArray(tmp.module) ||
options.moduleDict[tmp.name] ||
options.circularList.indexOf(tmp.module) >= 0) {
return;
}
isModule = [
tmp.module,
tmp.module.prototype
].some(function (dict) {
return Object.keys(dict || {}).some(function (key) {
// bug-workaround - buggy electron getter / setter
return local.tryCatchOnError(function () {
return typeof dict[key] === 'function';
}, console.error);
});
});
if (!isModule) {
return;
}
options.circularList.push(tmp.module);
options.moduleDict[tmp.name] = tmp.module;
}, console.error);
});
});
});
};
}());
switch (local.modeJs) {
// run node js-env code - init-after
/* istanbul ignore next */
case 'node':
// init cli
if (module !== require.main || local.global.utility2_rollup) {
break;
}
local.cliDict = {};
local.cliDict._default = function () {
/*
* moduleDirectory
* create apidoc from moduleDirectory
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
};
local.cliRun();
break;
}
}());
/* script-end /assets.utility2.lib.apidoc.js */
/* script-begin /assets.utility2.lib.db.js */
///usr/bin/env node
/*
* assets.db-lite.js
*
* this zero-dependency package will provide a persistent, in-browser database
*
* browser example:
*
*
*
* node example:
* var db, dbTable1;
* utility2_db = require("./assets.db-lite.js");
* dbTable1 = global.dbTable1 = utility2_db.dbTableCreateOne({ name: "dbTable1" });
* dbTable1.idIndexCreate({ name: "field1" });
* dbTable1.crudSetOneById({ field1: "hello", field2: "world" });
* console.log(dbTable1.crudGetManyByQuery({
* limit: Infinity,
* query: { field1: "hello" },
* skip: 0,
* sort: [{ fieldName: 'field1', isDescending: false }]
* }));
*/
/* istanbul instrument in package db */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 100,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || local;
/* istanbul ignore next */
if (!local) {
local = local.global.utility2_rollup ||
local.global.utility2_rollup_old ||
require('./assets.utility2.rollup.js');
local.fs = null;
}
// init exports
if (local.modeJs === 'browser') {
local.global.utility2_db = local;
} else {
// require builtins
Object.keys(process.binding('natives')).forEach(function (key) {
if (!local[key] && !(/\/|^_|^sys$/).test(key)) {
local[key] = require(key);
}
});
module.exports = local;
module.exports.__dirname = __dirname;
}
// init lib
local.local = local.db = local;
}());
// run shared js-env code - function-before
/* istanbul ignore next */
(function () {
local.assert = function (passed, message) {
/*
* this function will throw the error message if passed is falsey
*/
var error;
if (passed) {
return;
}
error = message && message.message
// if message is an error-object, then leave it as is
? message
: new Error(typeof message === 'string'
// if message is a string, then leave it as is
? message
// else JSON.stringify message
: JSON.stringify(message));
throw error;
};
local.cliRun = function (fnc) {
/*
* this function will run the cli
*/
var nop;
nop = function () {
/*
* this function will do nothing
*/
return;
};
local.cliDict._eval = local.cliDict._eval || function () {
/*
* code
* eval code
*/
local.global.local = local;
require('vm').runInThisContext(process.argv[3]);
};
local.cliDict['--eval'] = local.cliDict['--eval'] || local.cliDict._eval;
local.cliDict['-e'] = local.cliDict['-e'] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
* [none]
* print help
*/
var element, result, lengthList, sortDict;
sortDict = {};
result = [['[command]', '[args]', '[description]', -1]];
lengthList = [result[0][0].length, result[0][1].length];
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === '_' && key !== '_default') {
return;
}
sortDict[local.cliDict[key].toString()] =
sortDict[local.cliDict[key].toString()] || (ii + 1);
element = (/\n +\*(.*)\n +\*(.*)/).exec(local.cliDict[key].toString());
// coverage-hack - ignore else-statement
nop(local.global.__coverage__ && (function () {
element = element || ['', '', ''];
}()));
element = [
key.replace('_default', '[none]') + ' ',
element[1].trim() + ' ',
element[2].trim(),
(sortDict[local.cliDict[key].toString()] << 8) + ii
];
result.push(element);
lengthList.forEach(function (length, jj) {
lengthList[jj] = Math.max(element[jj].length, length);
});
});
result.sort(function (aa, bb) {
return aa[3] < bb[3]
? -1
: 1;
});
console.log('usage: ' + __filename + ' [command] [args]');
console.log('example: ' + __filename + ' --eval ' +
'"console.log(\'hello world\')"\n');
result.forEach(function (element, ii) {
lengthList.forEach(function (length, jj) {
while (element[jj].length < length) {
element[jj] += '-';
}
});
element = element.slice(0, 3).join('---- ');
if (ii === 0) {
element = element.replace((/-/g), ' ');
}
console.log(element);
});
};
local.cliDict['--help'] = local.cliDict['--help'] || local.cliDict._help;
local.cliDict['-h'] = local.cliDict['-h'] || local.cliDict._help;
local.cliDict._default = local.cliDict._default || local.cliDict._help;
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
* [none]
* start interactive-mode
*/
local.global.local = local;
local.replStart();
};
if (local.replStart) {
local.cliDict['--interactive'] = local.cliDict['--interactive'] ||
local.cliDict._interactive;
local.cliDict['-i'] = local.cliDict['-i'] || local.cliDict._interactive;
}
// run fnc()
fnc = fnc || function () {
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
fnc();
};
local.jsonCopy = function (jsonObj) {
/*
* this function will return a deep-copy of the jsonObj
*/
return jsonObj === undefined
? undefined
: JSON.parse(JSON.stringify(jsonObj));
};
local.jsonStringifyOrdered = function (jsonObj, replacer, space) {
/*
* this function will JSON.stringify the jsonObj,
* with object-keys sorted and circular-references removed
*/
var circularList, stringify, tmp;
stringify = function (jsonObj) {
/*
* this function will recursively JSON.stringify the jsonObj,
* with object-keys sorted and circular-references removed
*/
// if jsonObj is an object, then recurse its items with object-keys sorted
if (jsonObj &&
typeof jsonObj === 'object' &&
typeof jsonObj.toJSON !== 'function') {
// ignore circular-reference
if (circularList.indexOf(jsonObj) >= 0) {
return;
}
circularList.push(jsonObj);
// if jsonObj is an array, then recurse its jsonObjs
if (Array.isArray(jsonObj)) {
return '[' + jsonObj.map(function (jsonObj) {
// recurse
tmp = stringify(jsonObj);
return typeof tmp === 'string'
? tmp
: 'null';
}).join(',') + ']';
}
return '{' + Object.keys(jsonObj)
// sort object-keys
.sort()
.map(function (key) {
// recurse
tmp = stringify(jsonObj[key]);
if (typeof tmp === 'string') {
return JSON.stringify(key) + ':' + tmp;
}
})
.filter(function (jsonObj) {
return typeof jsonObj === 'string';
})
.join(',') + '}';
}
// else JSON.stringify as normal
return JSON.stringify(jsonObj);
};
circularList = [];
return JSON.stringify(typeof jsonObj === 'object' && jsonObj
// recurse
? JSON.parse(stringify(jsonObj))
: jsonObj, replacer, space);
};
local.listShuffle = function (list) {
/*
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
* this function will inplace shuffle the list, via fisher-yates algorithm
*/
var ii, random, swap;
for (ii = list.length - 1; ii > 0; ii -= 1) {
// coerce to finite integer
random = (Math.random() * (ii + 1)) | 0;
swap = list[ii];
list[ii] = list[random];
list[random] = swap;
}
return list;
};
local.nop = function () {
/*
* this function will do nothing
*/
return;
};
local.normalizeValue = function (type, value, valueDefault) {
/*
* this function will normalize the value by type
*/
switch (type) {
case 'list':
return Array.isArray(value)
? value
: valueDefault || [];
case 'number':
return Number(value) || valueDefault || 0;
case 'string':
return typeof value === 'string'
? value
: valueDefault || '';
}
};
local.objectSetOverride = function (arg, overrides, depth, env) {
/*
* this function will recursively set overrides for items in the arg
*/
arg = arg || {};
env = env || (typeof process === 'object' && process.env) || {};
overrides = overrides || {};
Object.keys(overrides).forEach(function (key) {
var arg2, overrides2;
arg2 = arg[key];
overrides2 = overrides[key];
if (overrides2 === undefined) {
return;
}
// if both arg2 and overrides2 are non-null and non-array objects,
// then recurse with arg2 and overrides2
if (depth > 1 &&
// arg2 is a non-null and non-array object
(arg2 &&
typeof arg2 === 'object' &&
!Array.isArray(arg2)) &&
// overrides2 is a non-null and non-array object
(overrides2 &&
typeof overrides2 === 'object' &&
!Array.isArray(overrides2))) {
local.objectSetOverride(arg2, overrides2, depth - 1, env);
return;
}
// else set arg[key] with overrides[key]
arg[key] = arg === env
// if arg is env, then overrides falsey value with empty string
? overrides2 || ''
: overrides2;
});
return arg;
};
local.onErrorDefault = function (error) {
/*
* this function will if error exists, then print error.stack to stderr
*/
if (error && !local.global.__coverage__) {
console.error(error);
}
};
local.onErrorWithStack = function (onError) {
/*
* this function will create a new callback that will call onError,
* and append the current stack to any error
*/
var stack;
stack = new Error().stack.replace((/(.*?)\n.*?$/m), '$1');
return function (error, data, meta) {
if (error &&
error !== local.errorDefault &&
String(error.stack).indexOf(stack.split('\n')[2]) < 0) {
// append the current stack to error.stack
error.stack += '\n' + stack;
}
onError(error, data, meta);
};
};
local.onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or error occurred, then call onError with error
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (error, data) {
if (onRetry(error, data)) {
return;
}
// decrement counter
onParallel.counter -= 1;
// validate counter
local.assert(
onParallel.counter >= 0 || error || onParallel.error,
'invalid onParallel.counter = ' + onParallel.counter
);
// ensure onError is run only once
if (onParallel.counter < 0) {
return;
}
// handle error
if (error) {
onParallel.error = error;
// ensure counter <= 0
onParallel.counter = -Math.abs(onParallel.counter);
}
// call onError when isDone
if (onParallel.counter <= 0) {
onError(error, data);
return;
}
onEach();
};
// init counter
onParallel.counter = 0;
// return callback
return onParallel;
};
local.replStart = function () {
/*
* this function will start the repl-debugger
*/
/*jslint evil: true*/
var self;
if (global.utility2_serverRepl1) {
return;
}
// start replServer
self = global.utility2_serverRepl1 = require('repl').start({ useGlobal: true });
self.nop = function () {
/*
* this function will do nothing
*/
return;
};
self.onError = function (error) {
/*
* this function will debug any repl-error
*/
// debug error
global.utility2_debugReplError = error;
console.error(error);
};
// save repl eval function
self.evalDefault = self.eval;
// hook custom repl eval function
self.eval = function (script, context, file, onError) {
var match, onError2;
match = (/^(\S+)(.*?)\n/).exec(script) || {};
onError2 = function (error, data) {
// debug error
global.utility2_debugReplError = error || global.utility2_debugReplError;
onError(error, data);
};
switch (match[1]) {
// syntax sugar to run async shell command
case '$':
switch (match[2]) {
// syntax sugar to run git diff
case ' git diff':
match[2] = ' git diff --color | cat';
break;
// syntax sugar to run git log
case ' git log':
match[2] = ' git log -n 4 | cat';
break;
}
// run async shell command
require('child_process').spawn(match[2], {
shell: true,
stdio: ['ignore', 1, 2]
})
// on shell exit, print return prompt
.on('exit', function (exitCode) {
console.error('exit-code ' + exitCode);
self.evalDefault(
'\n',
context,
file,
onError2
);
});
script = '\n';
break;
// syntax sugar to grep current dir
case 'grep':
// run async shell command
require('child_process').spawn('find . -type f | grep -v ' +
/* jslint-ignore-begin */
'"\
/\\.\\|\\(\\b\\|_\\)\\(\\.\\d\\|\
archive\\|artifact\\|\
bower_component\\|build\\|\
coverage\\|\
doc\\|\
external\\|\
fixture\\|\
git_module\\|\
jquery\\|\
log\\|\
min\\|mock\\|\
node_module\\|\
rollup\\|\
swp\\|\
tmp\\|\
vendor\\)s\\{0,1\\}\\(\\b\\|_\\)\
" ' +
/* jslint-ignore-end */
'| tr "\\n" "\\000" | xargs -0 grep -in "' +
match[2].trim() + '"', { shell: true, stdio: ['ignore', 1, 2] })
// on shell exit, print return prompt
.on('exit', function (exitCode) {
console.error('exit-code ' + exitCode);
self.evalDefault(
'\n',
context,
file,
onError2
);
});
script = '\n';
break;
// syntax sugar to list object's keys, sorted by item-type
case 'keys':
script = 'console.error(Object.keys(' + match[2] +
').map(function (key) {' +
'return typeof ' + match[2] + '[key] + " " + key + "\\n";' +
'}).sort().join("") + Object.keys(' + match[2] + ').length)\n';
break;
// syntax sugar to print stringified arg
case 'print':
script = 'console.error(String(' + match[2] + '))\n';
break;
}
// eval the script
self.evalDefault(script, context, file, onError2);
};
self.socket = { end: self.nop, on: self.nop, write: self.nop };
// init process.stdout
process.stdout._writeDefault = process.stdout._writeDefault ||
process.stdout._write;
process.stdout._write = function (chunk, encoding, callback) {
process.stdout._writeDefault(chunk, encoding, callback);
// coverage-hack - ignore else-statement
self.nop(self.socket.writable && (function () {
self.socket.write(chunk, encoding);
}()));
};
// start tcp-server
global.utility2_serverReplTcp1 = require('net').createServer(function (socket) {
// init socket
self.socket = socket;
self.socket.on('data', self.write.bind(self));
self.socket.on('error', self.onError);
self.socket.setKeepAlive(true);
});
// coverage-hack - ignore else-statement
self.nop(process.env.PORT_REPL && (function () {
console.error('repl-server listening on tcp-port ' + process.env.PORT_REPL);
global.utility2_serverReplTcp1.listen(process.env.PORT_REPL);
}()));
};
local.setTimeoutOnError = function (onError, timeout, error, data) {
/*
* this function will async-call onError
*/
if (typeof onError === 'function') {
setTimeout(function () {
onError(error, data);
}, timeout);
}
return data;
};
}());
// run shared js-env code - lib.storage.js
(function (local) {
var child_process,
clear,
defer,
deferList,
fs,
getItem,
init,
keys,
length,
modeJs,
os,
removeItem,
setItem,
storage,
storageDir;
// init modeJs
modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
storageDir = 'tmp/storage.' + (local.modeJs === 'browser'
? 'undefined'
: process.env.NODE_ENV);
switch (modeJs) {
case 'node':
// require modules
child_process = require('child_process');
fs = require('fs');
os = require('os');
break;
}
clear = function (onError) {
/*
* this function will clear storage
*/
defer({ action: 'clear' }, onError);
};
defer = function (options, onError) {
/*
* this function will defer options.action until storage is ready
*/
var data, isDone, objectStore, onError2, request, tmp;
onError = onError || function (error) {
// validate no error occurred
local.assert(!error, error);
};
if (!storage) {
deferList.push(function () {
defer(options, onError);
});
init();
return;
}
switch (modeJs) {
case 'browser':
onError2 = function () {
/* istanbul ignore next */
if (isDone) {
return;
}
isDone = true;
onError(
request && (request.error || request.transaction.error),
data || request.result || ''
);
};
switch (options.action) {
case 'clear':
case 'removeItem':
case 'setItem':
objectStore = storage
.transaction(storageDir, 'readwrite')
.objectStore(storageDir);
break;
default:
objectStore = storage
.transaction(storageDir, 'readonly')
.objectStore(storageDir);
}
switch (options.action) {
case 'clear':
request = objectStore.clear();
break;
case 'getItem':
request = objectStore.get(String(options.key));
break;
case 'keys':
data = [];
request = objectStore.openCursor();
request.onsuccess = function () {
if (!request.result) {
onError2();
return;
}
data.push(request.result.key);
request.result.continue();
};
break;
case 'length':
request = objectStore.count();
break;
case 'removeItem':
request = objectStore.delete(String(options.key));
break;
case 'setItem':
request = objectStore.put(options.value, String(options.key));
break;
}
['onabort', 'onerror', 'onsuccess'].forEach(function (handler) {
request[handler] = request[handler] || onError2;
});
// debug request
local._debugStorageRequest = request;
break;
case 'node':
switch (options.action) {
case 'clear':
child_process.spawnSync('rm -f ' + storage + '/*', {
shell: true,
stdio: ['ignore', 1, 2]
});
setTimeout(onError);
break;
case 'getItem':
fs.readFile(
storage + '/' + encodeURIComponent(String(options.key)),
'utf8',
// ignore error
function (error, data) {
onError(error && null, data || '');
}
);
break;
case 'keys':
fs.readdir(storage, function (error, data) {
onError(error, data && data.map(decodeURIComponent));
});
break;
case 'length':
fs.readdir(storage, function (error, data) {
onError(error, data && data.length);
});
break;
case 'removeItem':
fs.unlink(
storage + '/' + encodeURIComponent(String(options.key)),
// ignore error
function () {
onError();
}
);
break;
case 'setItem':
tmp = os.tmpdir() + '/' + Date.now() + Math.random();
// save to tmp
fs.writeFile(tmp, options.value, function (error) {
// validate no error occurred
local.assert(!error, error);
// rename tmp to key
fs.rename(
tmp,
storage + '/' + encodeURIComponent(String(options.key)),
onError
);
});
break;
}
break;
}
};
deferList = [];
getItem = function (key, onError) {
/*
* this function will get the item with the given key from storage
*/
defer({ action: 'getItem', key: key }, onError);
};
init = function () {
/*
* this function will init storage
*/
var onError, request;
onError = function (error) {
// validate no error occurred
local.assert(!error, error);
if (modeJs === 'browser') {
storage = window[storageDir];
}
while (deferList.length) {
deferList.shift()();
}
};
if (modeJs === 'browser') {
storage = window[storageDir];
}
if (storage) {
onError();
return;
}
switch (modeJs) {
case 'browser':
// init indexedDB
try {
request = window.indexedDB.open(storageDir);
// debug request
local._debugStorageRequestIndexedDB = request;
request.onerror = onError;
request.onsuccess = function () {
window[storageDir] = request.result;
onError();
};
request.onupgradeneeded = function () {
if (!request.result.objectStoreNames.contains(storageDir)) {
request.result.createObjectStore(storageDir);
}
};
} catch (ignore) {
}
break;
case 'node':
// mkdirp storage
storage = storageDir;
child_process.spawnSync(
'mkdir',
['-p', storage],
{ stdio: ['ignore', 1, 2] }
);
onError();
break;
}
};
keys = function (onError) {
/*
* this function will get all the keys in storage
*/
defer({ action: 'keys' }, onError);
};
length = function (onError) {
/*
* this function will get the number of items in storage
*/
defer({ action: 'length' }, onError);
};
removeItem = function (key, onError) {
/*
* this function will remove the item with the given key from storage
*/
defer({ action: 'removeItem', key: key }, onError);
};
setItem = function (key, value, onError) {
/*
* this function will set the item with the given key and value to storage
*/
defer({ action: 'setItem', key: key, value: value }, onError);
};
// init local
local.storage = storage;
local.storageClear = clear;
local.storageDefer = defer;
local.storageDeferList = deferList;
local.storageDir = storageDir;
local.storageGetItem = getItem;
local.storageInit = init;
local.storageKeys = keys;
local.storageLength = length;
local.storageRemoveItem = removeItem;
local.storageSetItem = setItem;
}(local));
// run shared js-env code - lib.dbTable.js
(function () {
local._DbTable = function (options) {
/*
* this function will create a dbTable
*/
options = local.objectSetOverride(options);
this.name = String(options.name);
// register dbTable in dbTableDict
local.dbTableDict[this.name] = this;
this.dbRowList = [];
this.isDirty = null;
this.idIndexList = [{ isInteger: false, name: '_id', dict: {} }];
this.onSaveList = [];
this.sizeLimit = options.sizeLimit || 0;
};
local._DbTable.prototype._cleanup = function () {
/*
* this function will cleanup soft-deleted records from the dbTable
*/
var dbRow, ii, list;
if (!this.isDirty && this.dbRowList.length <= this.sizeLimit) {
return;
}
this.isDirty = null;
// cleanup dbRowList
list = this.dbRowList;
this.dbRowList = [];
// optimization - for-loop
for (ii = 0; ii < list.length; ii += 1) {
dbRow = list[ii];
// cleanup isRemoved
if (!dbRow.$meta.isRemoved) {
this.dbRowList.push(dbRow);
}
}
if (this.sizeLimit && this.dbRowList.length >= 1.5 * this.sizeLimit) {
this.dbRowList = this._crudGetManyByQuery(
{},
this.sortDefault,
0,
this.sizeLimit
);
}
};
local._DbTable.prototype._crudGetManyByQuery = function (
query,
sort,
skip,
limit,
shuffle
) {
/*
* this function will get the dbRow's in the dbTable,
* with the given query, sort, skip, and limit
*/
var ii, result;
result = this.dbRowList;
// get by query
if (result.length && query && Object.keys(query).length) {
result = local.dbRowListGetManyByQuery(this.dbRowList, query);
}
// sort
local.normalizeValue('list', sort).forEach(function (element) {
// bug-workaround - v8 does not have stable-sort
// optimization - for-loop
for (ii = 0; ii < result.length; ii += 1) {
result[ii].$meta.ii = ii;
}
if (element.isDescending) {
result.sort(function (aa, bb) {
return -local.sortCompare(
local.dbRowGetItem(aa, element.fieldName),
local.dbRowGetItem(bb, element.fieldName),
aa.$meta.ii,
bb.$meta.ii
);
});
} else {
result.sort(function (aa, bb) {
return local.sortCompare(
local.dbRowGetItem(aa, element.fieldName),
local.dbRowGetItem(bb, element.fieldName),
aa.$meta.ii,
bb.$meta.ii
);
});
}
});
// skip
result = result.slice(skip || 0);
// shuffle
((shuffle && local.listShuffle) || local.nop)(result);
// limit
result = result.slice(0, limit || Infinity);
return result;
};
local._DbTable.prototype._crudGetOneById = function (idDict) {
/*
* this function will get the dbRow in the dbTable with the given idDict
*/
var id, result;
idDict = local.objectSetOverride(idDict);
result = null;
this.idIndexList.some(function (idIndex) {
id = idDict[idIndex.name];
// optimization - hasOwnProperty
if (idIndex.dict.hasOwnProperty(id)) {
result = idIndex.dict[id];
return result;
}
});
return result;
};
local._DbTable.prototype._crudRemoveOneById = function (idDict, circularList) {
/*
* this function will remove the dbRow from the dbTable with the given idDict
*/
var id, result, self;
if (!idDict) {
return null;
}
self = this;
circularList = circularList || [idDict];
result = null;
self.idIndexList.forEach(function (idIndex) {
id = idDict[idIndex.name];
// optimization - hasOwnProperty
if (!idIndex.dict.hasOwnProperty(id)) {
return;
}
result = idIndex.dict[id];
delete idIndex.dict[id];
// optimization - soft-delete
result.$meta.isRemoved = true;
self.isDirty = true;
if (circularList.indexOf(result) >= 0) {
return;
}
circularList.push(result);
// recurse
self._crudRemoveOneById(result, circularList);
});
self.save();
return result;
};
local._DbTable.prototype._crudSetOneById = function (dbRow) {
/*
* this function will set the dbRow into the dbTable with the given dbRow._id
* WARNING - existing dbRow with conflicting dbRow._id will be removed
*/
var existing, id, normalize, timeNow;
normalize = function (dbRow) {
/*
* this function will recursively normalize dbRow
*/
if (typeof dbRow === 'object' && dbRow) {
Object.keys(dbRow).forEach(function (key) {
// remove invalid property
if (key[0] === '$' || key.indexOf('.') >= 0 || dbRow[key] === null) {
// optimization - soft-delete
dbRow[key] = undefined;
return;
}
// recurse
normalize(dbRow[key]);
});
}
};
dbRow = local.jsonCopy(typeof dbRow === 'object' && dbRow
? dbRow
: {});
// update timestamp
timeNow = new Date().toISOString();
dbRow._timeCreated = dbRow._timeCreated || timeNow;
if (!local.modeImport) {
dbRow._timeUpdated = timeNow;
}
// normalize
normalize(dbRow);
dbRow = local.jsonCopy(dbRow);
// remove existing dbRow
existing = this._crudRemoveOneById(dbRow) || dbRow;
// init meta
dbRow.$meta = { isRemoved: null };
this.idIndexList.forEach(function (idIndex) {
// auto-set id
id = local.dbRowSetId(existing, idIndex);
// copy id from existing to dbRow
dbRow[idIndex.name] = id;
// set dbRow
idIndex.dict[id] = dbRow;
});
// update dbRowList
this.dbRowList.push(dbRow);
this.save();
return dbRow;
};
local._DbTable.prototype._crudUpdateOneById = function (dbRow) {
/*
* this function will update the dbRow in the dbTable,
* if it exists with the given dbRow._id
* WARNING
* existing dbRow's with conflicting unique-keys (besides the one being updated)
* will be removed
*/
var id, result;
dbRow = local.jsonCopy(local.objectSetOverride(dbRow));
result = null;
this.idIndexList.some(function (idIndex) {
id = dbRow[idIndex.name];
// optimization - hasOwnProperty
if (idIndex.dict.hasOwnProperty(id)) {
result = idIndex.dict[id];
return true;
}
});
result = result || {};
// remove existing dbRow
this._crudRemoveOneById(result);
// update dbRow
dbRow._timeCreated = undefined;
local.objectSetOverride(result, dbRow, 10);
// replace dbRow
result = this._crudSetOneById(result);
return result;
};
local._DbTable.prototype.crudCountAll = function (onError) {
/*
* this function will count all of dbRow's in the dbTable
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, this.dbRowList.length);
};
local._DbTable.prototype.crudCountManyByQuery = function (query, onError) {
/*
* this function will count the number of dbRow's in the dbTable with the given query
*/
this._cleanup();
return local.setTimeoutOnError(
onError,
0,
null,
this._crudGetManyByQuery(query).length
);
};
local._DbTable.prototype.crudGetManyById = function (idDictList, onError) {
/*
* this function will get the dbRow's in the dbTable with the given idDictList
*/
var self;
this._cleanup();
self = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
local.normalizeValue('list', idDictList).map(function (idDict) {
return self._crudGetOneById(idDict);
})
));
};
local._DbTable.prototype.crudGetManyByQuery = function (options, onError) {
/*
* this function will get the dbRow's in the dbTable with the given options.query
*/
this._cleanup();
options = local.objectSetOverride(options);
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudGetManyByQuery(
options.query,
options.sort || this.sortDefault,
options.skip,
options.limit,
options.shuffle
),
options.fieldList
));
};
local._DbTable.prototype.crudGetOneById = function (idDict, onError) {
/*
* this function will get the dbRow in the dbTable with the given idDict
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudGetOneById(idDict)
));
};
local._DbTable.prototype.crudGetOneByQuery = function (query, onError) {
/*
* this function will get the dbRow in the dbTable with the given query
*/
var ii, result;
this._cleanup();
// optimization - for-loop
for (ii = 0; ii < this.dbRowList.length; ii += 1) {
result = local.dbRowListGetManyByQuery([this.dbRowList[ii]], query)[0];
if (result) {
break;
}
}
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(result));
};
local._DbTable.prototype.crudGetOneByRandom = function (onError) {
/*
* this function will get a random dbRow in the dbTable
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this.dbRowList[Math.floor(Math.random() * this.dbRowList.length)]
));
};
local._DbTable.prototype.crudRemoveAll = function (onError) {
/*
* this function will remove all of the dbRow's from the dbTable
*/
var idIndexList;
// save idIndexList
idIndexList = this.idIndexList;
// reset dbTable
local._DbTable.call(this, this);
// restore idIndexList
local.dbTableCreateOne({
name: this.name,
idIndexCreateList: idIndexList
}, onError);
};
local._DbTable.prototype.crudRemoveManyById = function (idDictList, onError) {
/*
* this function will remove the dbRow's from the dbTable with the given idDictList
*/
var self;
self = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
local.normalizeValue('list', idDictList).map(function (dbRow) {
return self._crudRemoveOneById(dbRow);
})
));
};
local._DbTable.prototype.crudRemoveManyByQuery = function (query, onError) {
/*
* this function will remove the dbRow's from the dbTable with the given query
*/
var self;
self = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
self._crudGetManyByQuery(query).map(function (dbRow) {
return self._crudRemoveOneById(dbRow);
})
));
};
local._DbTable.prototype.crudRemoveOneById = function (idDict, onError) {
/*
* this function will remove the dbRow from the dbTable with the given idDict
*/
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudRemoveOneById(idDict)
));
};
local._DbTable.prototype.crudSetManyById = function (dbRowList, onError) {
/*
* this function will set the dbRowList into the dbTable
*/
var self;
self = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
local.normalizeValue('list', dbRowList).map(function (dbRow) {
return self._crudSetOneById(dbRow);
})
));
};
local._DbTable.prototype.crudSetOneById = function (dbRow, onError) {
/*
* this function will set the dbRow into the dbTable with the given dbRow._id
*/
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudSetOneById(dbRow)
));
};
local._DbTable.prototype.crudUpdateManyById = function (dbRowList, onError) {
/*
* this function will update the dbRowList in the dbTable,
* if they exist with the given dbRow._id's
*/
var self;
self = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
local.normalizeValue('list', dbRowList).map(function (dbRow) {
return self._crudUpdateOneById(dbRow);
})
));
};
local._DbTable.prototype.crudUpdateManyByQuery = function (query, dbRow, onError) {
/*
* this function will update the dbRow's in the dbTable with the given query
*/
var result, self, tmp;
self = this;
tmp = local.jsonCopy(local.objectSetOverride(dbRow));
result = self._crudGetManyByQuery(query).map(function (dbRow) {
tmp._id = dbRow._id;
return self._crudUpdateOneById(tmp);
});
return local.setTimeoutOnError(onError, 0, null, result);
};
local._DbTable.prototype.crudUpdateOneById = function (dbRow, onError) {
/*
* this function will update the dbRow in the dbTable,
* if it exists with the given dbRow._id
*/
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudUpdateOneById(dbRow)
));
};
local._DbTable.prototype.drop = function (onError) {
/*
* this function will drop the dbTable
*/
console.error('dropping dbTable ' + this.name + ' ...');
// cancel pending save
this.timerSave = null;
while (this.onSaveList.length) {
this.onSaveList.shift()();
}
// reset dbTable
local._DbTable.call(this, this);
// clear persistence
local.storageRemoveItem('dbTable.' + this.name + '.json', onError);
};
local._DbTable.prototype.export = function (onError) {
/*
* this function will export the db
*/
var result, self;
this._cleanup();
self = this;
result = '';
self.idIndexList.forEach(function (idIndex) {
result += self.name + ' idIndexCreate ' + JSON.stringify({
isInteger: idIndex.isInteger,
name: idIndex.name
}) + '\n';
});
result += self.name + ' sizeLimit ' + self.sizeLimit + '\n';
result += self.name + ' sortDefault ' + JSON.stringify(self.sortDefault) + '\n';
self.crudGetManyByQuery({}).forEach(function (dbRow) {
result += self.name + ' dbRowSet ' + JSON.stringify(dbRow) + '\n';
});
return local.setTimeoutOnError(onError, 0, null, result.trim());
};
local._DbTable.prototype.idIndexCreate = function (options, onError) {
/*
* this function will create an idIndex with the given options.name
*/
var dbRow, idIndex, ii, name;
options = local.objectSetOverride(options);
name = String(options.name);
// disallow idIndex with dot-name
if (name.indexOf('.') >= 0 || name === '_id') {
return local.setTimeoutOnError(onError);
}
// remove existing idIndex
this.idIndexRemove(options);
// init idIndex
idIndex = {
dict: {},
isInteger: !!options.isInteger,
name: name
};
this.idIndexList.push(idIndex);
// populate idIndex with dbRowList
// optimization - for-loop
for (ii = 0; ii < this.dbRowList.length; ii += 1) {
dbRow = this.dbRowList[ii];
// auto-set id
if (!dbRow.$meta.isRemoved) {
idIndex.dict[local.dbRowSetId(dbRow, idIndex)] = dbRow;
}
}
this.save();
return local.setTimeoutOnError(onError);
};
local._DbTable.prototype.idIndexRemove = function (options, onError) {
/*
* this function will remove the idIndex with the given options.name
*/
var name;
options = local.objectSetOverride(options);
name = String(options.name);
this.idIndexList = this.idIndexList.filter(function (idIndex) {
return idIndex.name !== name || idIndex.name === '_id';
});
this.save();
return local.setTimeoutOnError(onError);
};
local._DbTable.prototype.save = function (onError) {
/*
* this function will save the dbTable to storage
*/
var self;
self = this;
if (local.modeImport) {
return;
}
if (onError) {
self.onSaveList.push(onError);
}
// throttle storage-writes to once every 1000 ms
self.timerSave = self.timerSave || setTimeout(function () {
self.timerSave = null;
local.storageSetItem('dbTable.' + self.name + '.json', self.export(), function (
error
) {
while (self.onSaveList.length) {
self.onSaveList.shift()(error);
}
});
}, 1000);
};
local.dbCrudRemoveAll = function (onError) {
/*
* this function will remove all dbRow's from the db
*/
var onParallel;
onParallel = local.onParallel(function (error) {
local.setTimeoutOnError(onError, 0, error);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].crudRemoveAll(onParallel);
});
onParallel();
};
local.dbDrop = function (onError) {
/*
* this function will drop the db
*/
var onParallel;
onParallel = local.onParallel(function (error) {
local.setTimeoutOnError(onError, 0, error);
});
onParallel.counter += 1;
onParallel.counter += 1;
local.storageClear(onParallel);
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].drop(onParallel);
});
onParallel();
};
local.dbExport = function (onError) {
/*
* this function will export the db as serialized text
*/
var result;
result = '';
Object.keys(local.dbTableDict).forEach(function (key) {
result += local.dbTableDict[key].export();
result += '\n\n';
});
return local.setTimeoutOnError(onError, 0, null, result.trim());
};
local.dbImport = function (text, onError) {
/*
* this function will import the serialized text into the db
*/
var dbTable;
local.modeImport = true;
setTimeout(function () {
local.modeImport = null;
});
text.replace((/^(\w\S*?) (\S+?) (\S.*?)$/gm), function (
match0,
match1,
match2,
match3
) {
// jslint-hack
local.nop(match0);
switch (match2) {
case 'dbRowSet':
dbTable = local.dbTableCreateOne({ isLoaded: true, name: match1 });
dbTable.crudSetOneById(JSON.parse(match3));
break;
case 'idIndexCreate':
dbTable = local.dbTableCreateOne({ isLoaded: true, name: match1 });
dbTable.idIndexCreate(JSON.parse(match3));
break;
case 'sizeLimit':
dbTable = local.dbTableCreateOne({ isLoaded: true, name: match1 });
dbTable.sizeLimit = JSON.parse(match3);
break;
case 'sortDefault':
dbTable = local.dbTableCreateOne({ isLoaded: true, name: match1 });
break;
default:
local.onErrorDefault(new Error('dbImport - invalid operation - ' + match0));
}
});
local.modeImport = null;
return local.setTimeoutOnError(onError);
};
local.dbLoad = function (onError) {
/*
* this function will load the db from storage
*/
var onParallel;
onParallel = local.onParallel(function (error) {
local.setTimeoutOnError(onError, 0, error);
});
local.storageKeys(function (error, data) {
onParallel.counter += 1;
onParallel.counter += 1;
onParallel(error);
local.normalizeValue('list', data)
.filter(function (key) {
return key.indexOf('dbTable.') === 0;
})
.forEach(function (key) {
onParallel.counter += 1;
local.storageGetItem(key, function (error, data) {
onParallel.counter += 1;
onParallel(error);
local.dbImport(data, onParallel);
});
});
onParallel();
});
};
local.dbRowGetItem = function (dbRow, key) {
/*
* this function will get the item with the given key from dbRow
*/
var ii, value;
value = dbRow;
key = String(key).split('.');
// optimization - for-loop
for (ii = 0; ii < key.length && typeof value === 'object' && value; ii += 1) {
value = value[key[ii]];
}
return value === undefined
? null
: value;
};
local.dbRowListGetManyByOperator = function (dbRowList, fieldName, operator, bb, not) {
/*
* this function will get the dbRow's in dbRowList with the given operator
*/
var ii, jj, result, fieldValue, test, typeof2;
result = [];
typeof2 = typeof bb;
if (bb && typeof2 === 'object') {
switch (operator) {
case '$in':
case '$nin':
case '$regex':
break;
default:
return result;
}
}
switch (operator) {
case '$eq':
test = function (aa, bb) {
return aa === bb;
};
break;
case '$exists':
bb = !bb;
test = function (aa, bb) {
return !((aa === null) ^ bb);
};
break;
case '$gt':
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && aa > bb;
};
break;
case '$gte':
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && aa >= bb;
};
break;
case '$in':
if (bb && typeof bb.indexOf === 'function') {
if (typeof2 === 'string') {
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && bb.indexOf(aa) >= 0;
};
} else {
test = function (aa, bb) {
return bb.indexOf(aa) >= 0;
};
}
}
break;
case '$lt':
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && aa < bb;
};
break;
case '$lte':
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && aa <= bb;
};
break;
case '$ne':
test = function (aa, bb) {
return aa !== bb;
};
break;
case '$nin':
if (bb && typeof bb.indexOf === 'function') {
if (typeof2 === 'string') {
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && bb.indexOf(aa) < 0;
};
} else {
test = function (aa, bb) {
return bb.indexOf(aa) < 0;
};
}
}
break;
case '$regex':
if (bb && typeof bb.test === 'function') {
test = function (aa, bb) {
return bb.test(aa);
};
}
break;
case '$typeof':
test = function (aa, bb, typeof1) {
// jslint-hack
local.nop(aa);
return typeof1 === bb;
};
break;
}
if (!test) {
return result;
}
// optimization - for-loop
for (ii = dbRowList.length - 1; ii >= 0; ii -= 1) {
fieldValue = local.dbRowGetItem(dbRowList[ii], fieldName);
// normalize to list
if (!Array.isArray(fieldValue)) {
fieldValue = [fieldValue];
}
// optimization - for-loop
for (jj = fieldValue.length - 1; jj >= 0; jj -= 1) {
if (not ^ test(fieldValue[jj], bb, typeof fieldValue[jj], typeof2)) {
result.push(dbRowList[ii]);
break;
}
}
}
return result;
};
local.dbRowListGetManyByQuery = function (dbRowList, query, fieldName, not) {
/*
* this function will get the dbRow's in dbRowList with the given query
*/
var bb, dbRowDict, result;
// optimization - convert to boolean
not = !!not;
result = dbRowList;
if (!(typeof query === 'object' && query)) {
result = local.dbRowListGetManyByOperator(result, fieldName, '$eq', query, not);
return result;
}
Object.keys(query).some(function (key) {
bb = query[key];
switch (key) {
case '$not':
key = fieldName;
not = !not;
break;
case '$or':
if (!Array.isArray(bb)) {
break;
}
dbRowDict = {};
bb.forEach(function (query) {
// recurse
local.dbRowListGetManyByQuery(result, query).forEach(function (dbRow) {
dbRowDict[dbRow._id] = dbRow;
});
});
result = Object.keys(dbRowDict).map(function (id) {
return dbRowDict[id];
});
return !result.length;
}
if (key[0] === '$') {
result = local.dbRowListGetManyByOperator(result, fieldName, key, bb, not);
return !result.length;
}
// recurse
result = local.dbRowListGetManyByQuery(result, bb, key, not);
return !result.length;
});
return result;
};
local.dbRowProject = function (dbRow, fieldList) {
/*
* this function will deepcopy and project the dbRow with the given fieldList
*/
var result;
if (!dbRow) {
return null;
}
// handle list-case
if (Array.isArray(dbRow)) {
return dbRow.map(function (dbRow) {
// recurse
return local.dbRowProject(dbRow, fieldList);
});
}
// normalize to list
if (!(Array.isArray(fieldList) && fieldList.length)) {
fieldList = Object.keys(dbRow);
}
result = {};
fieldList.forEach(function (key) {
if (key[0] !== '$') {
result[key] = dbRow[key];
}
});
return JSON.parse(local.jsonStringifyOrdered(result));
};
local.dbRowSetId = function (dbRow, idIndex) {
/*
* this function will set a random and unique id into dbRow for the given idIndex,
* if it does not exist
*/
var id;
id = dbRow[idIndex.name];
if (typeof id !== 'number' && typeof id !== 'string') {
do {
id = idIndex.isInteger
? (1 + Math.random()) * 0x10000000000000
: 'a' + ((1 + Math.random()) * 0x10000000000000).toString(36).slice(1);
// optimization - hasOwnProperty
} while (idIndex.dict.hasOwnProperty(id));
dbRow[idIndex.name] = id;
}
return id;
};
local.dbSave = function (onError) {
/*
* this function will save the db to storage
*/
var onParallel;
onParallel = local.onParallel(function (error) {
local.setTimeoutOnError(onError, 0, error);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].save(onParallel);
});
onParallel();
};
local.dbTableCreateMany = function (optionsList, onError) {
/*
* this function will set the optionsList into the db
*/
var onParallel, result;
onParallel = local.onParallel(function (error) {
local.setTimeoutOnError(onError, 0, error, result);
});
onParallel.counter += 1;
result = local.normalizeValue('list', optionsList).map(function (options) {
onParallel.counter += 1;
return local.dbTableCreateOne(options, onParallel);
});
return local.setTimeoutOnError(onParallel, 0, null, result);
};
local.dbTableCreateOne = function (options, onError) {
/*
* this function will create a dbTable with the given options
*/
var self;
options = local.objectSetOverride(options);
// register dbTable
self = local.dbTableDict[options.name] =
local.dbTableDict[options.name] || new local._DbTable(options);
self.sortDefault = options.sortDefault ||
self.sortDefault ||
[{ fieldName: '_timeUpdated', isDescending: true }];
// remove idIndex
local.normalizeValue('list', options.idIndexRemoveList).forEach(function (idIndex) {
self.idIndexRemove(idIndex);
});
// create idIndex
local.normalizeValue('list', options.idIndexCreateList).forEach(function (idIndex) {
self.idIndexCreate(idIndex);
});
// upsert dbRow
self.crudSetManyById(options.dbRowList);
// restore dbTable from persistent-storage
self.isLoaded = self.isLoaded || options.isLoaded;
if (!self.isLoaded) {
local.storageGetItem('dbTable.' + self.name + '.json', function (error, data) {
// validate no error occurred
local.assert(!error, error);
if (!self.isLoaded) {
local.dbImport(data);
}
self.isLoaded = true;
local.setTimeoutOnError(onError, 0, null, self);
});
return self;
}
return local.setTimeoutOnError(onError, 0, null, self);
};
local.dbTableDict = {};
local.sortCompare = function (aa, bb, ii, jj) {
/*
* this function will compare aa vs bb and return:
* -1 if aa < bb
* 0 if aa === bb
* 1 if aa > bb
* the priority for comparing different typeof's is:
* null < boolean < number < string < object < undefined
*/
var typeof1, typeof2;
if (aa === bb) {
return ii < jj
? -1
: 1;
}
if (aa === null) {
return -1;
}
if (bb === null) {
return 1;
}
typeof1 = typeof aa;
typeof2 = typeof bb;
if (typeof1 === typeof2) {
return typeof1 === 'object'
? 0
: aa > bb
? 1
: -1;
}
if (typeof1 === 'boolean') {
return -1;
}
if (typeof2 === 'boolean') {
return 1;
}
if (typeof1 === 'number') {
return -1;
}
if (typeof2 === 'number') {
return 1;
}
if (typeof1 === 'string') {
return -1;
}
if (typeof2 === 'string') {
return 1;
}
return 0;
};
}());
switch (local.modeJs) {
// run node js-env code - init-after
/* istanbul ignore next */
case 'node':
// init cli
if (module !== require.main || local.global.utility2_rollup) {
break;
}
local.cliDict = {};
local.cliDict.dbTableCrudGetManyByQuery = function () {
/*
* dbTable query
* query dbRowList from dbTable
*/
local.dbTableCreateOne({ name: process.argv[3] }, function (error, self) {
// validate no error occurred
local.assert(!error, error);
console.log(JSON.stringify(self.crudGetManyByQuery(
JSON.parse(process.argv[4] || '{}')
), null, 4));
});
};
local.cliDict.dbTableCrudRemoveManyByQuery = function () {
/*
* dbTable query
* query and remove dbRowList from dbTable
*/
local.dbTableCreateOne({ name: process.argv[3] }, function (error, self) {
// validate no error occurred
local.assert(!error, error);
console.log(JSON.stringify(self.crudRemoveManyByQuery(
JSON.parse(process.argv[4])
), null, 4));
});
};
local.cliDict.dbTableCrudSetManyById = function () {
/*
* dbTable dbRowList
* set dbRowList into dbTable
*/
local.dbTableCreateOne({ name: process.argv[3] }, function (error, self) {
// validate no error occurred
local.assert(!error, error);
self.crudSetManyById(JSON.parse(process.argv[4]));
});
};
local.cliDict.dbTableHeaderDictGet = function () {
/*
* dbTable
* get headerDict from dbTable
*/
local.dbTableCreateOne({ name: process.argv[3] }, function (error, self) {
// validate no error occurred
local.assert(!error, error);
var tmp;
tmp = [];
self.idIndexList.forEach(function (idIndex) {
tmp.push({ isInteger: idIndex.isInteger, name: idIndex.name });
});
console.log(JSON.stringify({
idIndexList: tmp,
sizeLimit: self.sizeLimit,
sortDefault: self.sortDefault
}, null, 4));
});
};
local.cliDict.dbTableHeaderDictSet = function () {
/*
* dbTable
* set headerDict into dbTable
*/
local.dbTableCreateOne({ name: process.argv[3] }, function (error, self) {
// validate no error occurred
local.assert(!error, error);
local.tmp = JSON.parse(process.argv[4]);
self.sizeLimit = local.tmp.sizeLimit || self.sizeLimit;
self.sortDefault = local.tmp.sortDefault || self.sortDefault;
self.save();
local.tmp = [];
self.idIndexList.forEach(function (idIndex) {
local.tmp.push({ isInteger: idIndex.isInteger, name: idIndex.name });
});
local.cliDict.dbTableHeaderDictGet();
});
};
local.cliDict.dbTableIdIndexCreate = function () {
/*
* dbTable idIndex
* create idIndex in dbTable
*/
local.dbTableCreateOne({ name: process.argv[3] }, function (error, self) {
// validate no error occurred
local.assert(!error, error);
self.idIndexCreate(JSON.parse(process.argv[4]));
self.save();
local.tmp = [];
self.idIndexList.forEach(function (idIndex) {
local.tmp.push({ isInteger: idIndex.isInteger, name: idIndex.name });
});
local.cliDict.dbTableHeaderDictGet();
});
};
local.cliDict.dbTableIdIndexRemove = function () {
/*
* dbTable idIndex
* remove idIndex from dbTable
*/
local.dbTableCreateOne({ name: process.argv[3] }, function (error, self) {
// validate no error occurred
local.assert(!error, error);
self.idIndexRemove(JSON.parse(process.argv[4]));
self.save();
local.cliDict.dbTableHeaderDictGet();
});
};
local.cliDict.dbTableList = function () {
/*
* [none]
* list dbTable's in db
*/
local.storageKeys(function (error, data) {
// validate no error occurred
local.assert(!error, error);
console.log(JSON.stringify(data.map(function (element) {
return element.split('.').slice(1, -1).join('.');
}), null, 4));
});
};
local.cliDict.dbTableRemove = function () {
/*
* dbTable
* remove dbTable from db
*/
local.storageRemoveItem('dbTable.' + process.argv[3] + '.json', function (error) {
// validate no error occurred
local.assert(!error, error);
local.cliDict.dbTableList();
});
};
local.cliRun();
break;
}
}());
/* script-end /assets.utility2.lib.db.js */
/* script-begin /assets.utility2.lib.github_crud.js */
///usr/bin/env node
/* istanbul instrument in package github_crud */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 100,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || local;
/* istanbul ignore next */
if (!local) {
local = local.global.utility2_rollup ||
local.global.utility2_rollup_old ||
require('./assets.utility2.rollup.js');
local.fs = null;
}
// init exports
if (local.modeJs === 'browser') {
local.global.utility2_github_crud = local;
} else {
// require builtins
Object.keys(process.binding('natives')).forEach(function (key) {
if (!local[key] && !(/\/|^_|^sys$/).test(key)) {
local[key] = require(key);
}
});
module.exports = local;
module.exports.__dirname = __dirname;
}
// init lib
local.local = local.github_crud = local;
}());
/* istanbul ignore next */
// run shared js-env code - function-before
(function () {
local.assert = function (passed, message) {
/*
* this function will throw the error message if passed is falsey
*/
var error;
if (passed) {
return;
}
error = message && message.message
// if message is an error-object, then leave it as is
? message
: new Error(typeof message === 'string'
// if message is a string, then leave it as is
? message
// else JSON.stringify message
: JSON.stringify(message));
throw error;
};
local.cliRun = function (fnc) {
/*
* this function will run the cli
*/
var nop;
nop = function () {
/*
* this function will do nothing
*/
return;
};
local.cliDict._eval = local.cliDict._eval || function () {
/*
* code
* eval code
*/
local.global.local = local;
require('vm').runInThisContext(process.argv[3]);
};
local.cliDict['--eval'] = local.cliDict['--eval'] || local.cliDict._eval;
local.cliDict['-e'] = local.cliDict['-e'] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
* [none]
* print help
*/
var element, result, lengthList, sortDict;
sortDict = {};
result = [['[command]', '[args]', '[description]', -1]];
lengthList = [result[0][0].length, result[0][1].length];
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === '_' && key !== '_default') {
return;
}
sortDict[local.cliDict[key].toString()] =
sortDict[local.cliDict[key].toString()] || (ii + 1);
element = (/\n +\*(.*)\n +\*(.*)/).exec(local.cliDict[key].toString());
// coverage-hack - ignore else-statement
nop(local.global.__coverage__ && (function () {
element = element || ['', '', ''];
}()));
element = [
key.replace('_default', '[none]') + ' ',
element[1].trim() + ' ',
element[2].trim(),
(sortDict[local.cliDict[key].toString()] << 8) + ii
];
result.push(element);
lengthList.forEach(function (length, jj) {
lengthList[jj] = Math.max(element[jj].length, length);
});
});
result.sort(function (aa, bb) {
return aa[3] < bb[3]
? -1
: 1;
});
console.log('usage: ' + __filename + ' [command] [args]');
console.log('example: ' + __filename + ' --eval ' +
'"console.log(\'hello world\')"\n');
result.forEach(function (element, ii) {
lengthList.forEach(function (length, jj) {
while (element[jj].length < length) {
element[jj] += '-';
}
});
element = element.slice(0, 3).join('---- ');
if (ii === 0) {
element = element.replace((/-/g), ' ');
}
console.log(element);
});
};
local.cliDict['--help'] = local.cliDict['--help'] || local.cliDict._help;
local.cliDict['-h'] = local.cliDict['-h'] || local.cliDict._help;
local.cliDict._default = local.cliDict._default || local.cliDict._help;
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
* [none]
* start interactive-mode
*/
local.global.local = local;
local.replStart();
};
if (local.replStart) {
local.cliDict['--interactive'] = local.cliDict['--interactive'] ||
local.cliDict._interactive;
local.cliDict['-i'] = local.cliDict['-i'] || local.cliDict._interactive;
}
// run fnc()
fnc = fnc || function () {
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
fnc();
};
local.httpRequest = function (options, onError) {
/*
* this function will request the data from options.url
*/
var chunkList,
isDone,
onError2,
serverLog,
timerTimeout,
request,
response,
timeStart,
urlParsed;
// init onError2
onError2 = function (error) {
if (isDone) {
return;
}
isDone = true;
// debug httpResponse
serverLog({
type: 'httpResponse',
time: new Date(timeStart).toISOString(),
method: options.method,
url: options.url,
statusCode: Number(response && response.statusCode) || 0,
duration: Date.now() - timeStart
});
// cleanup timerTimeout
clearTimeout(timerTimeout);
// cleanup request and response
[request, response].forEach(function (stream) {
// try to end the stream
try {
stream.end();
// else try to destroy the stream
} catch (errorCaught) {
try {
stream.destroy();
} catch (ignore) {
}
}
});
onError(error, response);
};
// init serverLog
serverLog = local.serverLog || console.error;
// init timerTimeout
timerTimeout = setTimeout(function () {
onError2(new Error('http-request timeout'));
}, options.timeout || 30000);
urlParsed = require('url').parse(options.url);
urlParsed.headers = options.headers;
urlParsed.method = options.method;
// debug request
timeStart = Date.now();
request = require(
urlParsed.protocol.slice(0, -1)
).request(urlParsed, function (_response) {
response = _response;
if (response.statusCode < 200 || response.statusCode > 299) {
onError2(new Error(response.statusCode));
return;
}
chunkList = [];
response
.on('data', function (chunk) {
chunkList.push(chunk);
})
.on('end', function () {
response.data = Buffer.concat(chunkList);
onError2();
})
.on('error', onError2);
}).on('error', onError2);
request.end(options.data);
};
local.nop = function () {
/*
* this function will do nothing
*/
return;
};
local.onErrorWithStack = function (onError) {
/*
* this function will create a new callback that will call onError,
* and append the current stack to any error
*/
var stack;
stack = new Error().stack.replace((/(.*?)\n.*?$/m), '$1');
return function (error, data, meta) {
if (error &&
error !== local.errorDefault &&
String(error.stack).indexOf(stack.split('\n')[2]) < 0) {
// append the current stack to error.stack
error.stack += '\n' + stack;
}
onError(error, data, meta);
};
};
local.onNext = function (options, onError) {
/*
* this function will wrap onError inside the recursive function options.onNext,
* and append the current stack to any error
*/
options.onNext = local.onErrorWithStack(function (error, data, meta) {
try {
options.modeNext = error && !options.modeErrorIgnore
? Infinity
: options.modeNext + 1;
onError(error, data, meta);
} catch (errorCaught) {
// throw errorCaught to break infinite recursion-loop
if (options.errorCaught) {
throw options.errorCaught;
}
options.errorCaught = errorCaught;
options.onNext(errorCaught, data, meta);
}
});
return options;
};
local.onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or error occurred, then call onError with error
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (error, data) {
if (onRetry(error, data)) {
return;
}
// decrement counter
onParallel.counter -= 1;
// validate counter
local.assert(
onParallel.counter >= 0 || error || onParallel.error,
'invalid onParallel.counter = ' + onParallel.counter
);
// ensure onError is run only once
if (onParallel.counter < 0) {
return;
}
// handle error
if (error) {
onParallel.error = error;
// ensure counter <= 0
onParallel.counter = -Math.abs(onParallel.counter);
}
// call onError when isDone
if (onParallel.counter <= 0) {
onError(error, data);
return;
}
onEach();
};
// init counter
onParallel.counter = 0;
// return callback
return onParallel;
};
local.onParallelList = function (options, onEach, onError) {
/*
* this function will
* 1. async-run onEach in parallel,
* with the given options.rateLimit and options.retryLimit
* 2. call onError when isDone
*/
var ii, onEach2, onParallel;
options.list = options.list || [];
onEach2 = function () {
while (ii + 1 < options.list.length &&
onParallel.counter < options.rateLimit + 1) {
ii += 1;
onParallel.ii += 1;
onParallel.remaining -= 1;
onEach({
element: options.list[ii],
ii: ii,
list: options.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (error, data) {
if (error && data && data.retry < options.retryLimit) {
local.onErrorDefault(error);
data.retry += 1;
setTimeout(function () {
onParallel.counter -= 1;
onEach(data, onParallel);
}, 1000);
return true;
}
});
ii = -1;
onParallel.ii = -1;
onParallel.remaining = options.list.length;
options.rateLimit = Number(options.rateLimit) || 6;
options.rateLimit = Math.max(options.rateLimit, 1);
options.retryLimit = Number(options.retryLimit) || 2;
onParallel.counter += 1;
onEach2();
onParallel();
};
local.onReadyAfter = function (onError) {
/*
* this function will call onError when onReadyBefore.counter === 0
*/
local.onReadyBefore.counter += 1;
local.taskCreate({ key: 'utility2.onReadyAfter' }, null, onError);
local.onResetAfter(local.onReadyBefore);
return onError;
};
}());
switch (local.modeJs) {
// run node js-env code - function
case 'node':
local.contentDelete = function (options, onError) {
/*
* this function will delete the github file
* https://developer.github.com/v3/repos/contents/#delete-a-file
*/
options = { message: options.message, url: options.url };
local.onNext(options, function (error, data) {
switch (options.modeNext) {
case 1:
// get sha
local.contentRequest({ method: 'GET', url: options.url }, options.onNext);
break;
case 2:
// delete file with sha
if (!error && data.sha) {
local.contentRequest({
message: options.message,
method: 'DELETE',
sha: data.sha,
url: options.url
}, options.onNext);
return;
}
// delete tree
local.onParallelList({ list: data }, function (data, onParallel) {
onParallel.counter += 1;
// recurse
local.contentDelete({
message: options.message,
url: data.element.url
}, onParallel);
}, options.onNext);
break;
default:
onError();
}
});
options.modeNext = 0;
options.onNext();
};
local.contentGet = function (options, onError) {
/*
* this function will get the github file
* https://developer.github.com/v3/repos/contents/#get-contents
*/
options = { url: options.url };
local.onNext(options, function (error, data) {
switch (options.modeNext) {
case 1:
local.contentRequest({ method: 'GET', url: options.url }, options.onNext);
break;
case 2:
options.onNext(null, new Buffer(data.content, 'base64'));
break;
default:
onError(error, !error && data);
}
});
options.modeNext = 0;
options.onNext();
};
local.contentPut = function (options, onError) {
/*
* this function will put options.content into the github file
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
options = {
content: options.content,
message: options.message,
modeErrorIgnore: true,
url: options.url
};
local.onNext(options, function (error, data) {
switch (options.modeNext) {
case 1:
// get sha
local.contentRequest({ method: 'GET', url: options.url }, options.onNext);
break;
case 2:
// put file with sha
local.contentRequest({
content: options.content,
message: options.message,
method: 'PUT',
sha: data.sha,
url: options.url
}, options.onNext);
break;
default:
onError(error);
}
});
options.modeNext = 0;
options.onNext();
};
local.contentPutFile = function (options, onError) {
/*
* this function will put options.file into the github file
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
options = { file: options.file, message: options.message, url: options.url };
local.onNext(options, function (error, data) {
switch (options.modeNext) {
case 1:
// get file from url
if ((/^(?:http|https):\/\//).test(options.file)) {
local.httpRequest({
method: 'GET',
url: options.file
}, function (error, response) {
options.onNext(error, response && response.data);
});
return;
}
// get file
local.fs.readFile(
local.path.resolve(process.cwd(), options.file),
options.onNext
);
break;
case 2:
local.contentPut({
content: data,
message: options.message,
// resolve file in url
url: (/\/$/).test(options.url)
? options.url + local.path.basename(options.file)
: options.url
}, options.onNext);
break;
default:
onError(error);
}
});
options.modeNext = 0;
options.onNext();
};
local.contentRequest = function (options, onError) {
/*
* this function will request the content from github
*/
// init options
options = {
chunkList: [],
content: options.content,
headers: {
// github oauth authentication
Authorization: 'token ' + process.env.GITHUB_TOKEN,
// bug-workaround - https://developer.github.com/v3/#user-agent-required
'User-Agent': 'undefined'
},
message: options.message,
method: options.method,
responseJson: {},
sha: options.sha,
url: options.url
};
options.url = options.url
/* jslint-ignore-begin */
// parse https://github.com/:owner/:repo/blob/:branch/:path
.replace(
(/^https:\/\/github.com\/([^\/]+?\/[^\/]+?)\/blob\/([^\/]+?)\/(.+)/),
'https://api.github.com/repos/$1/contents/$3?branch=$2'
)
// parse https://github.com/:owner/:repo/tree/:branch/:path
.replace(
(/^https:\/\/github.com\/([^\/]+?\/[^\/]+?)\/tree\/([^\/]+?)\/(.+)/),
'https://api.github.com/repos/$1/contents/$3?branch=$2'
)
// parse https://raw.githubusercontent.com/:owner/:repo/:branch/:path
.replace(
(/^https:\/\/raw.githubusercontent.com\/([^\/]+?\/[^\/]+?)\/([^\/]+?)\/(.+)/),
'https://api.github.com/repos/$1/contents/$3?branch=$2'
)
// parse https://:owner.github.io/:repo/:path
.replace(
(/^https:\/\/([^\.]+?)\.github\.io\/([^\/]+?)\/(.+)/),
'https://api.github.com/repos/$1/$2/contents/$3?branch=gh-pages'
)
/* jslint-ignore-end */
.replace((/\?branch=(.*)/), function (match0, match1) {
options.branch = match1;
if (options.method === 'GET') {
match0 = match0.replace('branch', 'ref');
}
return match0;
});
if (options.url.indexOf('https://api.github.com/repos/') !== 0) {
onError(new Error('invalid url ' + options.url));
return;
}
if (options.method !== 'GET') {
options.message = options.message ||
'[ci skip] ' + options.method + ' file ' + options.url
.replace((/\?.*/), '');
options.url += '&message=' + encodeURIComponent(options.message);
if (options.sha) {
options.url += '&sha=' + options.sha;
}
options.data = JSON.stringify({
branch: options.branch,
content: new Buffer(options.content || '').toString('base64'),
message: options.message,
sha: options.sha
});
}
local.httpRequest(options, function (error, response) {
try {
options.responseJson = JSON.parse(response.data.toString());
} catch (ignore) {
}
onError(error, options.responseJson);
});
};
local.contentTouch = function (options, onError) {
/*
* this function will touch options.url
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
options = {
message: options.message,
modeErrorIgnore: true,
url: options.url
};
local.onNext(options, function (error, data) {
switch (options.modeNext) {
case 1:
// get sha
local.contentRequest({ method: 'GET', url: options.url }, options.onNext);
break;
case 2:
// put file with sha
local.contentRequest({
content: new Buffer(data.content || '', 'base64'),
message: options.message,
method: 'PUT',
sha: data.sha,
url: options.url
}, options.onNext);
break;
default:
onError(error);
}
});
options.modeNext = 0;
options.onNext();
};
local.contentTouchList = function (options, onError) {
/*
* this function will touch options.urlList in parallel
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
local.onParallelList({ list: options.urlList }, function (data, onParallel) {
onParallel.counter += 1;
local.contentTouch({
message: options.message,
modeErrorIgnore: true,
url: data.element
}, onParallel);
}, onError);
};
break;
}
switch (local.modeJs) {
/* istanbul ignore next */
// run node js-env code - init-after
case 'node':
// init cli
if (module !== require.main || local.global.utility2_rollup) {
break;
}
local.cliDict = {};
local.cliDict.delete = function () {
/*
* fileRemote commitMessage
* delete fileRemote from github
*/
local.contentDelete({
message: process.argv[4],
url: process.argv[3]
}, function (error) {
// validate no error occurred
console.assert(!error, error);
});
};
local.cliDict.get = function () {
/*
* fileRemote
* get fileRemote from github
*/
local.contentGet({ url: process.argv[3] }, function (error, data) {
// validate no error occurred
console.assert(!error, error);
try {
process.stdout.write(data);
} catch (ignore) {
}
});
};
local.cliDict.put = function () {
/*
* fileRemote fileLocal commitMessage
* put fileLocal as fileRemote on github
*/
local.contentPutFile({
message: process.argv[5],
url: process.argv[3],
file: process.argv[4]
}, function (error) {
// validate no error occurred
console.assert(!error, error);
});
};
local.cliDict.touch = function () {
/*
* fileRemote commitMessage
* touch fileRemote on github
*/
local.contentTouch({
message: process.argv[4],
url: process.argv[3]
}, function (error) {
// validate no error occurred
console.assert(!error, error);
});
};
local.cliDict.touchList = function () {
/*
* fileRemoteList commitMessage
* touch comma-separated fileRemoteList on github
*/
local.contentTouchList({
message: process.argv[4],
urlList: process.argv[3].split(',').filter(function (element) {
return element;
})
}, function (error) {
// validate no error occurred
console.assert(!error, error);
});
};
local.cliRun();
break;
}
}());
/* script-end /assets.utility2.lib.github_crud.js */
/* script-begin /assets.utility2.lib.istanbul.js */
///usr/bin/env node
/* istanbul instrument in package istanbul */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 100,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || local;
/* istanbul ignore next */
if (!local) {
local = local.global.utility2_rollup ||
local.global.utility2_rollup_old ||
require('./assets.utility2.rollup.js');
local.fs = null;
}
// init exports
if (local.modeJs === 'browser') {
local.global.utility2_istanbul = local;
} else {
// require builtins
Object.keys(process.binding('natives')).forEach(function (key) {
if (!local[key] && !(/\/|^_|^sys$/).test(key)) {
local[key] = require(key);
}
});
module.exports = local;
module.exports.__dirname = __dirname;
}
// init lib
local.local = local.istanbul = local;
// init custom
if (local.modeJs === 'node') {
local._istanbul_module = require('module');
local.process = process;
local.require = require;
}
}());
// run shared js-env code - function-before
/* istanbul ignore next */
(function () {
local.cliRun = function (fnc) {
/*
* this function will run the cli
*/
var nop;
nop = function () {
/*
* this function will do nothing
*/
return;
};
local.cliDict._eval = local.cliDict._eval || function () {
/*
* code
* eval code
*/
local.global.local = local;
require('vm').runInThisContext(process.argv[3]);
};
local.cliDict['--eval'] = local.cliDict['--eval'] || local.cliDict._eval;
local.cliDict['-e'] = local.cliDict['-e'] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
* [none]
* print help
*/
var element, result, lengthList, sortDict;
sortDict = {};
result = [['[command]', '[args]', '[description]', -1]];
lengthList = [result[0][0].length, result[0][1].length];
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === '_' && key !== '_default') {
return;
}
sortDict[local.cliDict[key].toString()] =
sortDict[local.cliDict[key].toString()] || (ii + 1);
element = (/\n +\*(.*)\n +\*(.*)/).exec(local.cliDict[key].toString());
// coverage-hack - ignore else-statement
nop(local.global.__coverage__ && (function () {
element = element || ['', '', ''];
}()));
element = [
key.replace('_default', '[none]') + ' ',
element[1].trim() + ' ',
element[2].trim(),
(sortDict[local.cliDict[key].toString()] << 8) + ii
];
result.push(element);
lengthList.forEach(function (length, jj) {
lengthList[jj] = Math.max(element[jj].length, length);
});
});
result.sort(function (aa, bb) {
return aa[3] < bb[3]
? -1
: 1;
});
console.log('usage: ' + __filename + ' [command] [args]');
console.log('example: ' + __filename + ' --eval ' +
'"console.log(\'hello world\')"\n');
result.forEach(function (element, ii) {
lengthList.forEach(function (length, jj) {
while (element[jj].length < length) {
element[jj] += '-';
}
});
element = element.slice(0, 3).join('---- ');
if (ii === 0) {
element = element.replace((/-/g), ' ');
}
console.log(element);
});
};
local.cliDict['--help'] = local.cliDict['--help'] || local.cliDict._help;
local.cliDict['-h'] = local.cliDict['-h'] || local.cliDict._help;
local.cliDict._default = local.cliDict._default || local.cliDict._help;
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
* [none]
* start interactive-mode
*/
local.global.local = local;
local.replStart();
};
if (local.replStart) {
local.cliDict['--interactive'] = local.cliDict['--interactive'] ||
local.cliDict._interactive;
local.cliDict['-i'] = local.cliDict['-i'] || local.cliDict._interactive;
}
// run fnc()
fnc = fnc || function () {
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
fnc();
};
local.fsWriteFileWithMkdirpSync = function (file, data) {
/*
* this function will synchronously 'mkdir -p' and write the data to file
*/
// try to write to file
try {
require('fs').writeFileSync(file, data);
} catch (errorCaught) {
// mkdir -p
require('child_process').spawnSync(
'mkdir',
['-p', require('path').dirname(file)],
{ stdio: ['ignore', 1, 2] }
);
// re-write to file
require('fs').writeFileSync(file, data);
}
};
local.nop = function () {
/*
* this function will do nothing
*/
return;
};
}());
// run shared js-env code - function
(function () {
var __dirname, process, require;
// jslint-hack
local.nop(__dirname, require);
/* istanbul ignore next */
local.global.__coverageCodeDict__ = local.global.__coverageCodeDict__ || {};
// mock builtins
__dirname = '';
process = local.process || {
cwd: function () {
return '';
},
env: {},
stdout: {}
};
require = function (key) {
try {
return local['_istanbul_' + key] || local[key] || local.require(key);
} catch (ignore) {
}
};
local['./package.json'] = {};
// mock module fs
local._istanbul_fs = {};
local._istanbul_fs.readFileSync = function (file) {
// return head.txt or foot.txt
file = local[file.slice(-8)];
if (local.modeJs === 'browser') {
file = file
.replace((/\bhtml\b/g), 'x-istanbul-html')
.replace((/\n\
\n\
\n\
\n\
\n\
';
/* jslint-ignore-end */
// init lib istanbul.util.file-writer
/* istanbul ignore next */
// 2013-03-31T22:11:41Z
// https://github.com/gotwarlost/istanbul/blob/v0.2.16/lib/util/file-writer.js
local.writer = {
write: function (data) {
local.writerData += data;
},
writeFile: function (file, onError) {
local.coverageReportHtml += local.writerData + '\n\n';
if (local.modeJs === 'node' && local.writerFile) {
local.fsWriteFileWithMkdirpSync(local.writerFile, local.writerData);
}
local.writerData = '';
local.writerFile = file;
onError(local.writer);
}
};
// init lib istanbul.util.tree-summarizer
/* istanbul ignore next */
// 2014-03-05T18:58:42Z
// https://github.com/gotwarlost/istanbul/blob/v0.2.16/lib/util/tree-summarizer.js
(function () {
var module;
module = {};
/* jslint-ignore-begin */
// https://github.com/gotwarlost/istanbul/blob/v0.2.16/lib/util/tree-summarizer.js
// utility2-uglifyjs https://raw.githubusercontent.com/gotwarlost/istanbul/v0.2.16/lib/util/tree-summarizer.js
function commonArrayPrefix(e,t){var n=e.length
0&&(t.pop(),s=i,o=s.children,s.children=[],i=new
Node(t.join(SEP)+SEP,"dir"),i.addChild(s),o.forEach(function(e){e.kind==="dir"?i
.addChild(e):s.addChild(e)})),this.fixupNodes(i,t.join(SEP)+SEP),this.calculateMetrics
(i),this.root=i,this.map={},this.indexAndSortTree(i,this.map)},fixupNodes:function(
e,t,n){var r=this;e.name.indexOf(t)===0&&(e.name=e.name.substring(t.length)),e.name
.charAt(0)===SEP&&(e.name=e.name.substring(1)),n?n.name!=="__root__/"?e.relativeName=
e.name.substring(n.name.length):e.relativeName=e.name:e.relativeName=e.name.substring
(t.length),e.children.forEach(function(n){r.fixupNodes(n,t,e)})},calculateMetrics
:function(e){var t=this,n;if(e.kind!=="dir")return;e.children.forEach(function(e
){t.calculateMetrics(e)}),e.metrics=utils.mergeSummaryObjects.apply(null,e.children
.map(function(e){return e.metrics})),n=e.children.filter(function(e){return e.kind!=="dir"
}),n.length>0?e.packageMetrics=utils.mergeSummaryObjects.apply(null,n.map(function(
e){return e.metrics})):e.packageMetrics=null},indexAndSortTree:function(e,t){var n=
this;t[e.name]=e,e.children.sort(function(e,t){return e=e.relativeName,t=t.relativeName
,et?1:0}),e.children.forEach(function(e){n.indexAndSortTree(e,t)})},toJSON
:function(){return{prefix:this.prefix,root:this.root.toJSON()}}},TreeSummarizer.
prototype={addFileCoverageSummary:function(e,t){this.summaryMap[e]=t},getTreeSummary
:function(){var e=findCommonArrayPrefix(Object.keys(this.summaryMap));return new
TreeSummary(this.summaryMap,e)}},module.exports=TreeSummarizer
/* jslint-ignore-end */
local['../util/tree-summarizer'] = module.exports;
module.exports.prototype._getTreeSummary = module.exports.prototype.getTreeSummary;
module.exports.prototype.getTreeSummary = function () {
local.coverageReportSummary = this._getTreeSummary();
return local.coverageReportSummary;
};
}());
// init lib istanbul.report.html
/* istanbul ignore next */
/* jslint-ignore-begin */
// 2014-01-17T21:08:38Z
// https://github.com/gotwarlost/istanbul/blob/v0.2.16/lib/report/html.js
// utility2-uglifyjs https://raw.githubusercontent.com/gotwarlost/istanbul/v0.2.16/lib/report/html.js
(function () { var module; module = {};
function customEscape(e){return e=e.toString(),e.replace(RE_AMP,"&").replace
(RE_LT,"<").replace(RE_GT,">").replace(RE_lt,"<").replace(RE_gt,">")}function title
(e){return' title="'+e+'" '}function annotateLines(e,t){var n=e.l;if(!n)return;Object
.keys(n).forEach(function(e){var r=n[e];t[e].covered=r>0?"yes":"no"}),t.forEach(
function(e){e.covered===null&&(e.covered="neutral")})}function annotateStatements
(e,t){var n=e.s,r=e.statementMap;Object.keys(n).forEach(function(e){var i=n[e],s=
r[e],o=i>0?"yes":"no",u=s.start.column,a=s.end.column+1,f=s.start.line,l=s.end.line
,c=lt+'span class="'+(s.skip?"cstat-skip":"cstat-no")+'"'+title("statement not covered"
)+gt,h=lt+"/span"+gt,p;o==="no"&&(l!==f&&(l=f,a=t[f].text.originalLength()),p=t[
f].text,p.wrap(u,c,f===l?a:p.originalLength(),h))})}function annotateFunctions(e
,t){var n=e.f,r=e.fnMap;if(!n)return;Object.keys(n).forEach(function(e){var i=n[
e],s=r[e],o=i>0?"yes":"no",u=s.loc.start.column,a=s.loc.end.column+1,f=s.loc.start
.line,l=s.loc.end.line,c=lt+'span class="'+(s.skip?"fstat-skip":"fstat-no")+'"'+
title("function not covered")+gt,h=lt+"/span"+gt,p;o==="no"&&(l!==f&&(l=f,a=t[f]
.text.originalLength()),p=t[f].text,p.wrap(u,c,f===l?a:p.originalLength(),h))})}
function annotateBranches(e,t){var n=e.b,r=e.branchMap;if(!n)return;Object.keys(
n).forEach(function(e){var i=n[e],s=i.reduce(function(e,t){return e+t},0),o=r[e]
.locations,u,a,f,l,c,h,p,d,v,m,g;if(s>0)for(u=0;u0?"yes":"no",c=f.start.column,h=f.end.column+1,p=f.start.line,d=f.end.line,v=lt+'span class="branch-'+
u+" "+(f.skip?"cbranch-skip":"cbranch-no")+'"'+title("branch not covered")+gt,m=
lt+"/span"+gt,a===0&&(d!==p&&(d=p,h=t[p].text.originalLength()),g=t[p].text,r[e]
.type==="if"?g.insertAt(c,lt+'span class="'+(f.skip?"skip-if-branch":"missing-if-branch"
)+'"'+title((u===0?"if":"else")+" path not taken")+gt+(u===0?"I":"E")+lt+"/span"+
gt,!0,!1):g.wrap(c,v,p===d?h:g.originalLength(),m))})}function getReportClass(e,
t){var n=e.pct,r=1;return n*r===n?n>=t[1]?"high":n>=t[0]?"medium":"low":""}function HtmlReport
(e){Report.call(this),this.opts=e||{},this.opts.dir=this.opts.dir||path.resolve(
process.cwd(),"html-report"),this.opts.sourceStore=this.opts.sourceStore||Store.
create("fslookup"),this.opts.linkMapper=this.opts.linkMapper||this.standardLinkMapper
(),this.opts.writer=this.opts.writer||null,this.opts.templateData={datetime:Date
()},this.opts.watermarks=this.opts.watermarks||defaults.watermarks()}var handlebars=
require("handlebars"),defaults=require("./common/defaults"),path=require("path")
,SEP=path.sep||"/",fs=require("fs"),util=require("util"),FileWriter=require("../util/file-writer"
),Report=require("./index"),Store=require("../store"),InsertionText=require("../util/insertion-text"
),TreeSummarizer=require("../util/tree-summarizer"),utils=require("../object-utils"
),templateFor=function(e){return handlebars.compile(fs.readFileSync(path.resolve
(__dirname,"templates",e+".txt"),"utf8"))},headerTemplate=templateFor("head"),footerTemplate=
templateFor("foot"),pathTemplate=handlebars.compile('{{{html}}}
'
),detailTemplate=handlebars.compile(["",'{{#show_lines}}{{maxLines}}{{/show_lines}} | '
,'{{#show_line_execution_counts fileCoverage}}{{maxLines}}{{/show_line_execution_counts}} | '
,'{{#show_code structured}}{{/show_code}} | '
,"
\n"].join("")),summaryTableHeader=['',"
"
,"","",' File | '
,' | '
,' Statements | '
,' | '
,' Branches | '
,' | '
,' Functions | '
,' | '
,' Lines | '
,' | '
,"
","",""].join("\n"),summaryLineTemplate=handlebars.compile
(["",'{{file}} | '
,'{{#show_picture}}{{metrics.statements.pct}}{{/show_picture}} | '
,'{{metrics.statements.pct}}% | '
,'({{metrics.statements.covered}} / {{metrics.statements.total}}) | '
,'{{metrics.branches.pct}}% | '
,'({{metrics.branches.covered}} / {{metrics.branches.total}}) | '
,'{{metrics.functions.pct}}% | '
,'({{metrics.functions.covered}} / {{metrics.functions.total}}) | '
,'{{metrics.lines.pct}}% | '
,'({{metrics.lines.covered}} / {{metrics.lines.total}}) | '
,"
\n"].join("\n ")),summaryTableFooter=["","
","
"].join
("\n"),lt="",gt="",RE_LT=//g,RE_AMP=/&/g,RE_lt=/\u0001/g,RE_gt=/\u0002/g
;handlebars.registerHelper("show_picture",function(e){var t=Number(e.fn(this)),n
,r="";return isFinite(t)?(t===100&&(r=" cover-full"),t=Math.floor(t),n=100-t,''+''):""}),handlebars.registerHelper("show_ignores",function(e){var t=
e.statements.skipped,n=e.functions.skipped,r=e.branches.skipped,i;return t===0&&
n===0&&r===0?'none':(i=[],t>0&&i.push(t===1?"1 statement"
:t+" statements"),n>0&&i.push(n===1?"1 function":n+" functions"),r>0&&i.push(r===1?"1 branch"
:r+" branches"),i.join(", "))}),handlebars.registerHelper("show_lines",function(
e){var t=Number(e.fn(this)),n,r=[];for(n=0;n0?(u="yes",a=n[s]):u="no"),o.push(''+a+"");return o.join("\n")}),handlebars.registerHelper("show_code",
function(e){var t=[];return e.forEach(function(e){t.push(customEscape(e.text)||" "
)}),t.join("\n")}),HtmlReport.TYPE="html",util.inherits(HtmlReport,Report),Report
.mix(HtmlReport,{getPathHtml:function(e,t){var n=e.parent,r=[],i=[],s;while(n)r.
push(n),n=n.parent;for(s=0;s'+
(r[s].relativeName||"All files")+"");return i.reverse(),i.length>0?i.join(" » "
)+" » "+e.displayShortName():""},fillTemplate:function(e,t){var n=this.opts
,r=n.linkMapper;t.entity=e.name||"All files",t.metrics=e.metrics,t.reportClass=getReportClass
(e.metrics.statements,n.watermarks.statements),t.pathHtml=pathTemplate({html:this
.getPathHtml(e,r)}),t.prettify={js:r.asset(e,"prettify.js"),css:r.asset(e,"prettify.css"
)}},writeDetailPage:function(e,t,n){var r=this.opts,i=r.sourceStore,s=r.templateData
,o=n.code&&Array.isArray(n.code)?n.code.join("\n")+"\n":i.get(n.path),u=o.split(/(?:\r?\n)|\r/
),a=0,f=u.map(function(e){return a+=1,{line:a,covered:null,text:new InsertionText
(e,!0)}}),l;f.unshift({line:0,covered:null,text:new InsertionText("")}),this.fillTemplate
(t,s),e.write(headerTemplate(s)),e.write('\n'),annotateLines
(n,f),annotateBranches(n,f),annotateFunctions(n,f),annotateStatements(n,f),f.shift
(),l={structured:f,maxLines:f.length,fileCoverage:n},e.write(detailTemplate(l)),
e.write("
\n"),e.write(footerTemplate(s))},writeIndexPage:function(
e,t){var n=this.opts.linkMapper,r=this.opts.templateData,i=Array.prototype.slice
.apply(t.children),s=this.opts.watermarks;i.sort(function(e,t){return e.name0&&(o>=l?(f=padding(o-l),a=n?f+e:
e+f):(a=e.substring(l-o),a="... "+a.substring(4))),a=defaults.colorize(a,i),u+a}
function formatName(e,t,n,r){return fill(e,t,!1,n,r)}function formatPct(e,t){return fill
(e,PCT_COLS,!0,0,t)}function nodeName(e){return e.displayShortName()||"All files"
}function tableHeader(e){var t=[];return t.push(formatName("File",e,0)),t.push(formatPct
("% Stmts")),t.push(formatPct("% Branches")),t.push(formatPct("% Funcs")),t.push
(formatPct("% Lines")),t.join(" |")+" |"}function tableRow(e,t,n,r){var i=nodeName
(e),s=e.metrics.statements.pct,o=e.metrics.branches.pct,u=e.metrics.functions.pct
,a=e.metrics.lines.pct,f=[];return f.push(formatName(i,t,n,defaults.classFor("statements"
,e.metrics,r))),f.push(formatPct(s,defaults.classFor("statements",e.metrics,r)))
,f.push(formatPct(o,defaults.classFor("branches",e.metrics,r))),f.push(formatPct
(u,defaults.classFor("functions",e.metrics,r))),f.push(formatPct(a,defaults.classFor
("lines",e.metrics,r))),f.join(DELIM)+DELIM}function findNameWidth(e,t,n){n=n||0
,t=t||0;var r=TAB_SIZE*t+nodeName(e).length;return r>n&&(n=r),e.children.forEach
(function(e){n=findNameWidth(e,t+1,n)}),n}function makeLine(e){var t=padding(e,"-"
),n=padding(PCT_COLS,"-"),r=[];return r.push(t),r.push(n),r.push(n),r.push(n),r.
push(n),r.join(COL_DELIM)+COL_DELIM}function walk(e,t,n,r,i){var s;r===0?(s=makeLine
(t),n.push(s),n.push(tableHeader(t)),n.push(s)):n.push(tableRow(e,t,r,i)),e.children
.forEach(function(e){walk(e,t,n,r+1,i)}),r===0&&(n.push(s),n.push(tableRow(e,t,r
,i)),n.push(s))}var path=require("path"),mkdirp=require("mkdirp"),fs=require("fs"
),defaults=require("./common/defaults"),Report=require("./index"),TreeSummarizer=
require("../util/tree-summarizer"),utils=require("../object-utils"),PCT_COLS=10,
TAB_SIZE=3,DELIM=" |",COL_DELIM="-|";TextReport.TYPE="text",Report.mix(TextReport
,{writeReport:function(e){var t=new TreeSummarizer,n,r,i,s=4*(PCT_COLS+2),o,u=[]
,a;e.files().forEach(function(n){t.addFileCoverageSummary(n,utils.summarizeFileCoverage
(e.fileCoverageFor(n)))}),n=t.getTreeSummary(),r=n.root,i=findNameWidth(r),this.
maxCols>0&&(o=this.maxCols-s-2,i>o&&(i=o)),walk(r,i,u,0,this.watermarks),a=u.join
("\n")+"\n",this.file?(mkdirp.sync(this.dir),fs.writeFileSync(path.join(this.dir
,this.file),a,"utf8")):console.log(a)}}),module.exports=TextReport
local.TextReport = module.exports; }());
/* jslint-ignore-end */
/* jslint-ignore-begin */
// https://img.shields.io/badge/coverage-100.0%-00dd00.svg?style=flat
local.templateCoverageBadgeSvg =
'';
/* jslint-ignore-end */
}());
switch (local.modeJs) {
// run node js-env code - init-after
/* istanbul ignore next */
case 'node':
// init cli
if (module !== local.require.main || local.global.utility2_rollup) {
break;
}
local.cliDict = {};
local.cliDict.cover = function () {
/*
* script
* run and cover the script
*/
var tmp;
try {
tmp = JSON.parse(local.fs.readFileSync('package.json', 'utf8'));
process.env.npm_package_nameLib = process.env.npm_package_nameLib ||
tmp.nameLib ||
tmp.name.replace((/-/g), '_');
} catch (ignore) {
}
process.env.npm_config_mode_coverage = process.env.npm_config_mode_coverage ||
process.env.npm_package_nameLib ||
'all';
// add coverage hook to require
local._istanbul_moduleExtensionsJs = local._istanbul_module._extensions['.js'];
local._istanbul_module._extensions['.js'] = function (module, file) {
if (typeof file === 'string' && (
file.indexOf(process.env.npm_config_mode_coverage_dir) === 0 ||
(file.indexOf(process.cwd()) === 0 &&
file.indexOf(process.cwd() + '/node_modules/') !== 0)
)) {
module._compile(local.instrumentInPackage(
local.fs.readFileSync(file, 'utf8'),
file
), file);
return;
}
local._istanbul_moduleExtensionsJs(module, file);
};
// init process.argv
process.argv.splice(1, 2);
process.argv[1] = local.path.resolve(process.cwd(), process.argv[1]);
console.log('\ncovering $ ' + process.argv.join(' '));
// create coverage on exit
process.on('exit', function () {
local.coverageReportCreate({ coverage: local.global.__coverage__ });
});
// re-init cli
local._istanbul_module.runMain();
};
local.cliDict.instrument = function () {
/*
* script
* instrument the script and print result to stdout
*/
process.argv[3] = local.path.resolve(process.cwd(), process.argv[3]);
process.stdout.write(local.instrumentSync(
local.fs.readFileSync(process.argv[3], 'utf8'),
process.argv[3]
));
};
//
local.cliDict.test = function () {
/*
* script
* run and cover the script if env var $npm_config_mode_coverage is set
*/
if (process.env.npm_config_mode_coverage) {
process.argv[2] = 'cover';
// re-init cli
local.cliDict[process.argv[2]]();
return;
}
// init process.argv
process.argv.splice(1, 2);
process.argv[1] = local.path.resolve(process.cwd(), process.argv[1]);
// re-init cli
local._istanbul_module.runMain();
};
local.cliRun();
break;
}
}());
/* script-end /assets.utility2.lib.istanbul.js */
/* script-begin /assets.utility2.lib.jslint.js */
///usr/bin/env node
/* istanbul instrument in package jslint */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 100,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || local;
/* istanbul ignore next */
if (!local) {
local = local.global.utility2_rollup ||
local.global.utility2_rollup_old ||
require('./assets.utility2.rollup.js');
local.fs = null;
}
// init exports
if (local.modeJs === 'browser') {
local.global.utility2_jslint = local;
} else {
// require builtins
Object.keys(process.binding('natives')).forEach(function (key) {
if (!local[key] && !(/\/|^_|^sys$/).test(key)) {
local[key] = require(key);
}
});
module.exports = local;
module.exports.__dirname = __dirname;
}
// init lib
local.local = local.jslint = local;
}());
// run shared js-env code - function-before
/* istanbul ignore next */
(function () {
local.cliRun = function (fnc) {
/*
* this function will run the cli
*/
var nop;
nop = function () {
/*
* this function will do nothing
*/
return;
};
local.cliDict._eval = local.cliDict._eval || function () {
/*
* code
* eval code
*/
local.global.local = local;
require('vm').runInThisContext(process.argv[3]);
};
local.cliDict['--eval'] = local.cliDict['--eval'] || local.cliDict._eval;
local.cliDict['-e'] = local.cliDict['-e'] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
* [none]
* print help
*/
var element, result, lengthList, sortDict;
sortDict = {};
result = [['[command]', '[args]', '[description]', -1]];
lengthList = [result[0][0].length, result[0][1].length];
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === '_' && key !== '_default') {
return;
}
sortDict[local.cliDict[key].toString()] =
sortDict[local.cliDict[key].toString()] || (ii + 1);
element = (/\n +\*(.*)\n +\*(.*)/).exec(local.cliDict[key].toString());
// coverage-hack - ignore else-statement
nop(local.global.__coverage__ && (function () {
element = element || ['', '', ''];
}()));
element = [
key.replace('_default', '[none]') + ' ',
element[1].trim() + ' ',
element[2].trim(),
(sortDict[local.cliDict[key].toString()] << 8) + ii
];
result.push(element);
lengthList.forEach(function (length, jj) {
lengthList[jj] = Math.max(element[jj].length, length);
});
});
result.sort(function (aa, bb) {
return aa[3] < bb[3]
? -1
: 1;
});
console.log('usage: ' + __filename + ' [command] [args]');
console.log('example: ' + __filename + ' --eval ' +
'"console.log(\'hello world\')"\n');
result.forEach(function (element, ii) {
lengthList.forEach(function (length, jj) {
while (element[jj].length < length) {
element[jj] += '-';
}
});
element = element.slice(0, 3).join('---- ');
if (ii === 0) {
element = element.replace((/-/g), ' ');
}
console.log(element);
});
};
local.cliDict['--help'] = local.cliDict['--help'] || local.cliDict._help;
local.cliDict['-h'] = local.cliDict['-h'] || local.cliDict._help;
local.cliDict._default = local.cliDict._default || local.cliDict._help;
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
* [none]
* start interactive-mode
*/
local.global.local = local;
local.replStart();
};
if (local.replStart) {
local.cliDict['--interactive'] = local.cliDict['--interactive'] ||
local.cliDict._interactive;
local.cliDict['-i'] = local.cliDict['-i'] || local.cliDict._interactive;
}
// run fnc()
fnc = fnc || function () {
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
fnc();
};
}());
/* jslint-ignore-begin */
// init lib csslint
/* istanbul ignore next */
// 2013-08-15T10:18:30Z
// https://github.com/CSSLint/csslint/blob/v1.0.5/dist/csslint.js
// utility2-uglifyjs https://raw.githubusercontent.com/CSSLint/csslint/v1.0.5/dist/csslint.js
(function () {
var CSSLint=function(){function s(e,t,n,r){"use strict";this.messages=[],this.stats=
[],this.lines=e,this.ruleset=t,this.allow=n,this.allow||(this.allow={}),this.ignore=
r,this.ignore||(this.ignore=[])}var e=e||{},t=t||{},n=function(){var e;return e=
function t(n,r,i){function s(u,a){if(!r[u]){if(!n[u]){var f=typeof e=="function"&&
e;if(!a&&f)return f(u,!0);if(o)return o(u,!0);var l=new Error("Cannot find module '"+
u+"'");throw l.code="MODULE_NOT_FOUND",l}var c=r[u]={exports:{}};n[u][0].call(c.
exports,function(e){var t=n[u][1][e];return s(t?t:e)},c,c.exports,t,n,r,i)}return r
[u].exports}var o=typeof e=="function"&&e;for(var u=0;u"?this.type="child"
:e==="+"?this.type="adjacent-sibling":e==="~"&&(this.type="sibling")}t.exports=s
;var r=e("../util/SyntaxUnit"),i=e("./Parser");s.prototype=new r,s.prototype.constructor=
s},{"../util/SyntaxUnit":26,"./Parser":6}],3:[function(e,t,n){"use strict";function s
(e,t){this.match=function(t){var n;return t.mark(),n=e(t),n?t.drop():t.restore()
,n},this.toString=typeof t=="function"?t:function(){return t}}t.exports=s;var r=
e("../util/StringReader"),i=e("../util/SyntaxError");s.prec={MOD:5,SEQ:4,ANDAND:3
,OROR:2,ALT:1},s.parse=function(e){var t,n,o,u,a,f,l,c,h;t=new r(e),n=function(e
){var n=t.readMatch(e);if(n===null)throw new i("Expected "+e,t.getLine(),t.getCol
());return n},o=function(){var e=[u()];while(t.readMatch(" | ")!==null)e.push(u(
));return e.length===1?e[0]:s.alt.apply(s,e)},u=function(){var e=[a()];while(t.readMatch
(" || ")!==null)e.push(a());return e.length===1?e[0]:s.oror.apply(s,e)},a=function(
){var e=[f()];while(t.readMatch(" && ")!==null)e.push(f());return e.length===1?e
[0]:s.andand.apply(s,e)},f=function(){var e=[l()];while(t.readMatch(/^ (?![&|\]])/
)!==null)e.push(l());return e.length===1?e[0]:s.seq.apply(s,e)},l=function(){var e=
c();if(t.readMatch("?")!==null)return e.question();if(t.readMatch("*")!==null)return e
.star();if(t.readMatch("+")!==null)return e.plus();if(t.readMatch("#")!==null)return e
.hash();if(t.readMatch(/^\{\s*/)!==null){var r=n(/^\d+/);n(/^\s*,\s*/);var i=n(/^\d+/
);return n(/^\s*\}/),e.braces(+r,+i)}return e},c=function(){if(t.readMatch("[ ")!==
null){var e=o();return n(" ]"),e}return s.fromType(n(/^[^ ?*+#{]+/))},h=o();if(!
t.eof())throw new i("Expected end of string",t.getLine(),t.getCol());return h},s
.cast=function(e){return e instanceof s?e:s.parse(e)},s.fromType=function(t){var n=
e("./ValidationTypes");return new s(function(e){return e.hasNext()&&n.isType(e,t
)},t)},s.seq=function(){var e=Array.prototype.slice.call(arguments).map(s.cast);
return e.length===1?e[0]:new s(function(t){var n,r=!0;for(n=0;r&&nn&&(r="[ "+r+" ]"),r})},s.alt=function(){var e=
Array.prototype.slice.call(arguments).map(s.cast);return e.length===1?e[0]:new s
(function(t){var n,r=!1;for(n=0;!r&&n
n&&(r="[ "+r+" ]"),r})},s.many=function(t){var n=Array.prototype.slice.call(arguments
,1).reduce(function(t,n){if(n.expand){var r=e("./ValidationTypes");t.push.apply(
t,r.complex[n.expand].options)}else t.push(s.cast(n));return t},[]);t===!0&&(t=n
.map(function(){return!0}));var r=new s(function(e){var r=[],i=0,s=0,o=function(
e){return s===0?(i=Math.max(e,i),e===n.length):e===i},u=function(i){for(var s=0;
s0;for(var a=0;ar&&(i="[ "+i+" ]"),i});return r.options=n,r},s.andand=function(
){var e=Array.prototype.slice.call(arguments);return e.unshift(!0),s.many.apply(
s,e)},s.oror=function(){var e=Array.prototype.slice.call(arguments);return e.unshift
(!1),s.many.apply(s,e)},s.prototype={constructor:s,match:function(){throw new Error
("unimplemented")},toString:function(){throw new Error("unimplemented")},func:function(
){return this.match.bind(this)},then:function(e){return s.seq(this,e)},or:function(
e){return s.alt(this,e)},andand:function(e){return s.many(!0,this,e)},oror:function(
e){return s.many(!1,this,e)},star:function(){return this.braces(0,Infinity,"*")}
,plus:function(){return this.braces(1,Infinity,"+")},question:function(){return this
.braces(0,1,"?")},hash:function(){return this.braces(1,Infinity,"#",s.cast(","))
},braces:function(e,t,n,r){var i=this,o=r?r.then(this):this;return n||(n="{"+e+","+
t+"}"),new s(function(n){var s=!0,u;for(u=0;u0&&r?s=o.match(n):s=i.match
(n);if(!s)break}return u>=e},function(){return i.toString(s.prec.MOD)+n})}}},{"../util/StringReader"
:24,"../util/SyntaxError":25,"./ValidationTypes":21}],4:[function(e,t,n){"use strict"
;function s(e,t){r.call(this,"("+e+(t!==null?":"+t:"")+")",e.startLine,e.startCol
,i.MEDIA_FEATURE_TYPE),this.name=e,this.value=t}t.exports=s;var r=e("../util/SyntaxUnit"
),i=e("./Parser");s.prototype=new r,s.prototype.constructor=s},{"../util/SyntaxUnit"
:26,"./Parser":6}],5:[function(e,t,n){"use strict";function s(e,t,n,s,o){r.call(
this,(e?e+" ":"")+(t?t:"")+(t&&n.length>0?" and ":"")+n.join(" and "),s,o,i.MEDIA_QUERY_TYPE
),this.modifier=e,this.mediaType=t,this.features=n}t.exports=s;var r=e("../util/SyntaxUnit"
),i=e("./Parser");s.prototype=new r,s.prototype.constructor=s},{"../util/SyntaxUnit"
:26,"./Parser":6}],6:[function(e,t,n){"use strict";function y(e){r.call(this),this
.options=e||{},this._tokenStream=null}t.exports=y;var r=e("../util/EventTarget")
,i=e("../util/SyntaxError"),s=e("../util/SyntaxUnit"),o=e("./Combinator"),u=e("./MediaFeature"
),a=e("./MediaQuery"),f=e("./PropertyName"),l=e("./PropertyValue"),c=e("./PropertyValuePart"
),h=e("./Selector"),p=e("./SelectorPart"),d=e("./SelectorSubPart"),v=e("./TokenStream"
),m=e("./Tokens"),g=e("./Validation");y.DEFAULT_TYPE=0,y.COMBINATOR_TYPE=1,y.MEDIA_FEATURE_TYPE=2
,y.MEDIA_QUERY_TYPE=3,y.PROPERTY_NAME_TYPE=4,y.PROPERTY_VALUE_TYPE=5,y.PROPERTY_VALUE_PART_TYPE=6
,y.SELECTOR_TYPE=7,y.SELECTOR_PART_TYPE=8,y.SELECTOR_SUB_PART_TYPE=9,y.prototype=
function(){var e=new r,t,n={__proto__:null,constructor:y,DEFAULT_TYPE:0,COMBINATOR_TYPE
:1,MEDIA_FEATURE_TYPE:2,MEDIA_QUERY_TYPE:3,PROPERTY_NAME_TYPE:4,PROPERTY_VALUE_TYPE
:5,PROPERTY_VALUE_PART_TYPE:6,SELECTOR_TYPE:7,SELECTOR_PART_TYPE:8,SELECTOR_SUB_PART_TYPE
:9,_stylesheet:function(){var e=this._tokenStream,t,n,r;this.fire("startstylesheet"
),this._charset(),this._skipCruft();while(e.peek()===m.IMPORT_SYM)this._import()
,this._skipCruft();while(e.peek()===m.NAMESPACE_SYM)this._namespace(),this._skipCruft
();r=e.peek();while(r>m.EOF){try{switch(r){case m.MEDIA_SYM:this._media(),this._skipCruft
();break;case m.PAGE_SYM:this._page(),this._skipCruft();break;case m.FONT_FACE_SYM
:this._font_face(),this._skipCruft();break;case m.KEYFRAMES_SYM:this._keyframes(
),this._skipCruft();break;case m.VIEWPORT_SYM:this._viewport(),this._skipCruft()
;break;case m.DOCUMENT_SYM:this._document(),this._skipCruft();break;case m.SUPPORTS_SYM
:this._supports(),this._skipCruft();break;case m.UNKNOWN_SYM:e.get();if(!!this.options
.strict)throw new i("Unknown @ rule.",e.LT(0).startLine,e.LT(0).startCol);this.fire
({type:"error",error:null,message:"Unknown @ rule: "+e.LT(0).value+".",line:e.LT
(0).startLine,col:e.LT(0).startCol}),t=0;while(e.advance([m.LBRACE,m.RBRACE])===
m.LBRACE)t++;while(t)e.advance([m.RBRACE]),t--;break;case m.S:this._readWhitespace
();break;default:if(!this._ruleset())switch(r){case m.CHARSET_SYM:throw n=e.LT(1
),this._charset(!1),new i("@charset not allowed here.",n.startLine,n.startCol);case m
.IMPORT_SYM:throw n=e.LT(1),this._import(!1),new i("@import not allowed here.",n
.startLine,n.startCol);case m.NAMESPACE_SYM:throw n=e.LT(1),this._namespace(!1),new
i("@namespace not allowed here.",n.startLine,n.startCol);default:e.get(),this._unexpectedToken
(e.token())}}}catch(s){if(!(s instanceof i&&!this.options.strict))throw s;this.fire
({type:"error",error:s,message:s.message,line:s.line,col:s.col})}r=e.peek()}r!==
m.EOF&&this._unexpectedToken(e.token()),this.fire("endstylesheet")},_charset:function(
e){var t=this._tokenStream,n,r,i,s;t.match(m.CHARSET_SYM)&&(i=t.token().startLine
,s=t.token().startCol,this._readWhitespace(),t.mustMatch(m.STRING),r=t.token(),n=
r.value,this._readWhitespace(),t.mustMatch(m.SEMICOLON),e!==!1&&this.fire({type:"charset"
,charset:n,line:i,col:s}))},_import:function(e){var t=this._tokenStream,n,r,i=[]
;t.mustMatch(m.IMPORT_SYM),r=t.token(),this._readWhitespace(),t.mustMatch([m.STRING
,m.URI]),n=t.token().value.replace(/^(?:url\()?["']?([^"']+?)["']?\)?$/,"$1"),this
._readWhitespace(),i=this._media_query_list(),t.mustMatch(m.SEMICOLON),this._readWhitespace
(),e!==!1&&this.fire({type:"import",uri:n,media:i,line:r.startLine,col:r.startCol
})},_namespace:function(e){var t=this._tokenStream,n,r,i,s;t.mustMatch(m.NAMESPACE_SYM
),n=t.token().startLine,r=t.token().startCol,this._readWhitespace(),t.match(m.IDENT
)&&(i=t.token().value,this._readWhitespace()),t.mustMatch([m.STRING,m.URI]),s=t.
token().value.replace(/(?:url\()?["']([^"']+)["']\)?/,"$1"),this._readWhitespace
(),t.mustMatch(m.SEMICOLON),this._readWhitespace(),e!==!1&&this.fire({type:"namespace"
,prefix:i,uri:s,line:n,col:r})},_supports:function(e){var t=this._tokenStream,n,
r;if(t.match(m.SUPPORTS_SYM)){n=t.token().startLine,r=t.token().startCol,this._readWhitespace
(),this._supports_condition(),this._readWhitespace(),t.mustMatch(m.LBRACE),this.
_readWhitespace(),e!==!1&&this.fire({type:"startsupports",line:n,col:r});for(;;)
if(!this._ruleset())break;t.mustMatch(m.RBRACE),this._readWhitespace(),this.fire
({type:"endsupports",line:n,col:r})}},_supports_condition:function(){var e=this.
_tokenStream,t;if(e.match(m.IDENT))t=e.token().value.toLowerCase(),t==="not"?(e.
mustMatch(m.S),this._supports_condition_in_parens()):e.unget();else{this._supports_condition_in_parens
(),this._readWhitespace();while(e.peek()===m.IDENT){t=e.LT(1).value.toLowerCase(
);if(t==="and"||t==="or")e.mustMatch(m.IDENT),this._readWhitespace(),this._supports_condition_in_parens
(),this._readWhitespace()}}},_supports_condition_in_parens:function(){var e=this
._tokenStream,t;e.match(m.LPAREN)?(this._readWhitespace(),e.match(m.IDENT)?(t=e.
token().value.toLowerCase(),t==="not"?(this._readWhitespace(),this._supports_condition
(),this._readWhitespace(),e.mustMatch(m.RPAREN)):(e.unget(),this._supports_declaration_condition
(!1))):(this._supports_condition(),this._readWhitespace(),e.mustMatch(m.RPAREN))
):this._supports_declaration_condition()},_supports_declaration_condition:function(
e){var t=this._tokenStream;e!==!1&&t.mustMatch(m.LPAREN),this._readWhitespace(),
this._declaration(),t.mustMatch(m.RPAREN)},_media:function(){var e=this._tokenStream
,t,n,r;e.mustMatch(m.MEDIA_SYM),t=e.token().startLine,n=e.token().startCol,this.
_readWhitespace(),r=this._media_query_list(),e.mustMatch(m.LBRACE),this._readWhitespace
(),this.fire({type:"startmedia",media:r,line:t,col:n});for(;;)if(e.peek()===m.PAGE_SYM
)this._page();else if(e.peek()===m.FONT_FACE_SYM)this._font_face();else if(e.peek
()===m.VIEWPORT_SYM)this._viewport();else if(e.peek()===m.DOCUMENT_SYM)this._document
();else if(e.peek()===m.SUPPORTS_SYM)this._supports();else if(e.peek()===m.MEDIA_SYM
)this._media();else if(!this._ruleset())break;e.mustMatch(m.RBRACE),this._readWhitespace
(),this.fire({type:"endmedia",media:r,line:t,col:n})},_media_query_list:function(
){var e=this._tokenStream,t=[];this._readWhitespace(),(e.peek()===m.IDENT||e.peek
()===m.LPAREN)&&t.push(this._media_query());while(e.match(m.COMMA))this._readWhitespace
(),t.push(this._media_query());return t},_media_query:function(){var e=this._tokenStream
,t=null,n=null,r=null,i=[];e.match(m.IDENT)&&(n=e.token().value.toLowerCase(),n!=="only"&&
n!=="not"?(e.unget(),n=null):r=e.token()),this._readWhitespace(),e.peek()===m.IDENT?
(t=this._media_type(),r===null&&(r=e.token())):e.peek()===m.LPAREN&&(r===null&&(
r=e.LT(1)),i.push(this._media_expression()));if(t===null&&i.length===0)return null
;this._readWhitespace();while(e.match(m.IDENT))e.token().value.toLowerCase()!=="and"&&
this._unexpectedToken(e.token()),this._readWhitespace(),i.push(this._media_expression
());return new a(n,t,i,r.startLine,r.startCol)},_media_type:function(){return this
._media_feature()},_media_expression:function(){var e=this._tokenStream,t=null,n
,r=null;return e.mustMatch(m.LPAREN),t=this._media_feature(),this._readWhitespace
(),e.match(m.COLON)&&(this._readWhitespace(),n=e.LT(1),r=this._expression()),e.mustMatch
(m.RPAREN),this._readWhitespace(),new u(t,r?new s(r,n.startLine,n.startCol):null
)},_media_feature:function(){var e=this._tokenStream;return this._readWhitespace
(),e.mustMatch(m.IDENT),s.fromToken(e.token())},_page:function(){var e=this._tokenStream
,t,n,r=null,i=null;e.mustMatch(m.PAGE_SYM),t=e.token().startLine,n=e.token().startCol
,this._readWhitespace(),e.match(m.IDENT)&&(r=e.token().value,r.toLowerCase()==="auto"&&
this._unexpectedToken(e.token())),e.peek()===m.COLON&&(i=this._pseudo_page()),this
._readWhitespace(),this.fire({type:"startpage",id:r,pseudo:i,line:t,col:n}),this
._readDeclarations(!0,!0),this.fire({type:"endpage",id:r,pseudo:i,line:t,col:n})
},_margin:function(){var e=this._tokenStream,t,n,r=this._margin_sym();return r?(
t=e.token().startLine,n=e.token().startCol,this.fire({type:"startpagemargin",margin
:r,line:t,col:n}),this._readDeclarations(!0),this.fire({type:"endpagemargin",margin
:r,line:t,col:n}),!0):!1},_margin_sym:function(){var e=this._tokenStream;return e
.match([m.TOPLEFTCORNER_SYM,m.TOPLEFT_SYM,m.TOPCENTER_SYM,m.TOPRIGHT_SYM,m.TOPRIGHTCORNER_SYM
,m.BOTTOMLEFTCORNER_SYM,m.BOTTOMLEFT_SYM,m.BOTTOMCENTER_SYM,m.BOTTOMRIGHT_SYM,m.
BOTTOMRIGHTCORNER_SYM,m.LEFTTOP_SYM,m.LEFTMIDDLE_SYM,m.LEFTBOTTOM_SYM,m.RIGHTTOP_SYM
,m.RIGHTMIDDLE_SYM,m.RIGHTBOTTOM_SYM])?s.fromToken(e.token()):null},_pseudo_page
:function(){var e=this._tokenStream;return e.mustMatch(m.COLON),e.mustMatch(m.IDENT
),e.token().value},_font_face:function(){var e=this._tokenStream,t,n;e.mustMatch
(m.FONT_FACE_SYM),t=e.token().startLine,n=e.token().startCol,this._readWhitespace
(),this.fire({type:"startfontface",line:t,col:n}),this._readDeclarations(!0),this
.fire({type:"endfontface",line:t,col:n})},_viewport:function(){var e=this._tokenStream
,t,n;e.mustMatch(m.VIEWPORT_SYM),t=e.token().startLine,n=e.token().startCol,this
._readWhitespace(),this.fire({type:"startviewport",line:t,col:n}),this._readDeclarations
(!0),this.fire({type:"endviewport",line:t,col:n})},_document:function(){var e=this
._tokenStream,t,n=[],r="";e.mustMatch(m.DOCUMENT_SYM),t=e.token(),/^@\-([^\-]+)\-/
.test(t.value)&&(r=RegExp.$1),this._readWhitespace(),n.push(this._document_function
());while(e.match(m.COMMA))this._readWhitespace(),n.push(this._document_function
());e.mustMatch(m.LBRACE),this._readWhitespace(),this.fire({type:"startdocument"
,functions:n,prefix:r,line:t.startLine,col:t.startCol});var i=!0;while(i)switch(
e.peek()){case m.PAGE_SYM:this._page();break;case m.FONT_FACE_SYM:this._font_face
();break;case m.VIEWPORT_SYM:this._viewport();break;case m.MEDIA_SYM:this._media
();break;case m.KEYFRAMES_SYM:this._keyframes();break;case m.DOCUMENT_SYM:this._document
();break;default:i=Boolean(this._ruleset())}e.mustMatch(m.RBRACE),t=e.token(),this
._readWhitespace(),this.fire({type:"enddocument",functions:n,prefix:r,line:t.startLine
,col:t.startCol})},_document_function:function(){var e=this._tokenStream,t;return e
.match(m.URI)?(t=e.token().value,this._readWhitespace()):t=this._function(),t},_operator
:function(e){var t=this._tokenStream,n=null;if(t.match([m.SLASH,m.COMMA])||e&&t.
match([m.PLUS,m.STAR,m.MINUS]))n=t.token(),this._readWhitespace();return n?c.fromToken
(n):null},_combinator:function(){var e=this._tokenStream,t=null,n;return e.match
([m.PLUS,m.GREATER,m.TILDE])&&(n=e.token(),t=new o(n.value,n.startLine,n.startCol
),this._readWhitespace()),t},_unary_operator:function(){var e=this._tokenStream;
return e.match([m.MINUS,m.PLUS])?e.token().value:null},_property:function(){var e=
this._tokenStream,t=null,n=null,r,i,s,o;return e.peek()===m.STAR&&this.options.starHack&&
(e.get(),i=e.token(),n=i.value,s=i.startLine,o=i.startCol),e.match(m.IDENT)&&(i=
e.token(),r=i.value,r.charAt(0)==="_"&&this.options.underscoreHack&&(n="_",r=r.substring
(1)),t=new f(r,n,s||i.startLine,o||i.startCol),this._readWhitespace()),t},_ruleset
:function(){var e=this._tokenStream,t,n;try{n=this._selectors_group()}catch(r){if(
r instanceof i&&!this.options.strict){this.fire({type:"error",error:r,message:r.
message,line:r.line,col:r.col}),t=e.advance([m.RBRACE]);if(t!==m.RBRACE)throw r;
return!0}throw r}return n&&(this.fire({type:"startrule",selectors:n,line:n[0].line
,col:n[0].col}),this._readDeclarations(!0),this.fire({type:"endrule",selectors:n
,line:n[0].line,col:n[0].col})),n},_selectors_group:function(){var e=this._tokenStream
,t=[],n;n=this._selector();if(n!==null){t.push(n);while(e.match(m.COMMA))this._readWhitespace
(),n=this._selector(),n!==null?t.push(n):this._unexpectedToken(e.LT(1))}return t
.length?t:null},_selector:function(){var e=this._tokenStream,t=[],n=null,r=null,
i=null;n=this._simple_selector_sequence();if(n===null)return null;t.push(n);do{r=
this._combinator();if(r!==null)t.push(r),n=this._simple_selector_sequence(),n===
null?this._unexpectedToken(e.LT(1)):t.push(n);else{if(!this._readWhitespace())break;
i=new o(e.token().value,e.token().startLine,e.token().startCol),r=this._combinator
(),n=this._simple_selector_sequence(),n===null?r!==null&&this._unexpectedToken(e
.LT(1)):(r!==null?t.push(r):t.push(i),t.push(n))}}while(!0);return new h(t,t[0].
line,t[0].col)},_simple_selector_sequence:function(){var e=this._tokenStream,t=null
,n=[],r="",i=[function(){return e.match(m.HASH)?new d(e.token().value,"id",e.token
().startLine,e.token().startCol):null},this._class,this._attrib,this._pseudo,this
._negation],s=0,o=i.length,u=null,a,f;a=e.LT(1).startLine,f=e.LT(1).startCol,t=this
._type_selector(),t||(t=this._universal()),t!==null&&(r+=t);for(;;){if(e.peek()===
m.S)break;while(s1&&e.unget()),null)},_class:function(){var e=this._tokenStream,t;return e
.match(m.DOT)?(e.mustMatch(m.IDENT),t=e.token(),new d("."+t.value,"class",t.startLine
,t.startCol-1)):null},_element_name:function(){var e=this._tokenStream,t;return e
.match(m.IDENT)?(t=e.token(),new d(t.value,"elementName",t.startLine,t.startCol)
):null},_namespace_prefix:function(){var e=this._tokenStream,t="";if(e.LA(1)===m
.PIPE||e.LA(2)===m.PIPE)e.match([m.IDENT,m.STAR])&&(t+=e.token().value),e.mustMatch
(m.PIPE),t+="|";return t.length?t:null},_universal:function(){var e=this._tokenStream
,t="",n;return n=this._namespace_prefix(),n&&(t+=n),e.match(m.STAR)&&(t+="*"),t.
length?t:null},_attrib:function(){var e=this._tokenStream,t=null,n,r;return e.match
(m.LBRACKET)?(r=e.token(),t=r.value,t+=this._readWhitespace(),n=this._namespace_prefix
(),n&&(t+=n),e.mustMatch(m.IDENT),t+=e.token().value,t+=this._readWhitespace(),e
.match([m.PREFIXMATCH,m.SUFFIXMATCH,m.SUBSTRINGMATCH,m.EQUALS,m.INCLUDES,m.DASHMATCH
])&&(t+=e.token().value,t+=this._readWhitespace(),e.mustMatch([m.IDENT,m.STRING]
),t+=e.token().value,t+=this._readWhitespace()),e.mustMatch(m.RBRACKET),new d(t+"]"
,"attribute",r.startLine,r.startCol)):null},_pseudo:function(){var e=this._tokenStream
,t=null,n=":",r,s;if(e.match(m.COLON)){e.match(m.COLON)&&(n+=":"),e.match(m.IDENT
)?(t=e.token().value,r=e.token().startLine,s=e.token().startCol-n.length):e.peek
()===m.FUNCTION&&(r=e.LT(1).startLine,s=e.LT(1).startCol-n.length,t=this._functional_pseudo
());if(!t){var o=e.LT(1).startLine,u=e.LT(0).startCol;throw new i("Expected a `FUNCTION` or `IDENT` after colon at line "+
o+", col "+u+".",o,u)}t=new d(n+t,"pseudo",r,s)}return t},_functional_pseudo:function(
){var e=this._tokenStream,t=null;return e.match(m.FUNCTION)&&(t=e.token().value,
t+=this._readWhitespace(),t+=this._expression(),e.mustMatch(m.RPAREN),t+=")"),t}
,_expression:function(){var e=this._tokenStream,t="";while(e.match([m.PLUS,m.MINUS
,m.DIMENSION,m.NUMBER,m.STRING,m.IDENT,m.LENGTH,m.FREQ,m.ANGLE,m.TIME,m.RESOLUTION
,m.SLASH]))t+=e.token().value,t+=this._readWhitespace();return t.length?t:null},
_negation:function(){var e=this._tokenStream,t,n,r="",i,s=null;return e.match(m.
NOT)&&(r=e.token().value,t=e.token().startLine,n=e.token().startCol,r+=this._readWhitespace
(),i=this._negation_arg(),r+=i,r+=this._readWhitespace(),e.match(m.RPAREN),r+=e.
token().value,s=new d(r,"not",t,n),s.args.push(i)),s},_negation_arg:function(){var e=
this._tokenStream,t=[this._type_selector,this._universal,function(){return e.match
(m.HASH)?new d(e.token().value,"id",e.token().startLine,e.token().startCol):null
},this._class,this._attrib,this._pseudo],n=null,r=0,i=t.length,s,o,u;s=e.LT(1).startLine
,o=e.LT(1).startCol;while(r0?new
l(t,t[0].line,t[0].col):null},_term:function(e){var t=this._tokenStream,n=null,r=
null,i=null,s=null,o,u,a;return n=this._unary_operator(),n!==null&&(u=t.token().
startLine,a=t.token().startCol),t.peek()===m.IE_FUNCTION&&this.options.ieFilters?
(r=this._ie_function(),n===null&&(u=t.token().startLine,a=t.token().startCol)):e&&
t.match([m.LPAREN,m.LBRACE,m.LBRACKET])?(o=t.token(),i=o.endChar,r=o.value+this.
_expr(e).text,n===null&&(u=t.token().startLine,a=t.token().startCol),t.mustMatch
(m.type(i)),r+=i,this._readWhitespace()):t.match([m.NUMBER,m.PERCENTAGE,m.LENGTH
,m.ANGLE,m.TIME,m.FREQ,m.STRING,m.IDENT,m.URI,m.UNICODE_RANGE])?(r=t.token().value
,n===null&&(u=t.token().startLine,a=t.token().startCol,s=c.fromToken(t.token()))
,this._readWhitespace()):(o=this._hexcolor(),o===null?(n===null&&(u=t.LT(1).startLine
,a=t.LT(1).startCol),r===null&&(t.LA(3)===m.EQUALS&&this.options.ieFilters?r=this
._ie_function():r=this._function())):(r=o.value,n===null&&(u=o.startLine,a=o.startCol
))),s!==null?s:r!==null?new c(n!==null?n+r:r,u,a):null},_function:function(){var e=
this._tokenStream,t=null,n=null,r;if(e.match(m.FUNCTION)){t=e.token().value,this
._readWhitespace(),n=this._expr(!0),t+=n;if(this.options.ieFilters&&e.peek()===m
.EQUALS)do{this._readWhitespace()&&(t+=e.token().value),e.LA(0)===m.COMMA&&(t+=e
.token().value),e.match(m.IDENT),t+=e.token().value,e.match(m.EQUALS),t+=e.token
().value,r=e.peek();while(r!==m.COMMA&&r!==m.S&&r!==m.RPAREN)e.get(),t+=e.token(
).value,r=e.peek()}while(e.match([m.COMMA,m.S]));e.match(m.RPAREN),t+=")",this._readWhitespace
()}return t},_ie_function:function(){var e=this._tokenStream,t=null,n;if(e.match
([m.IE_FUNCTION,m.FUNCTION])){t=e.token().value;do{this._readWhitespace()&&(t+=e
.token().value),e.LA(0)===m.COMMA&&(t+=e.token().value),e.match(m.IDENT),t+=e.token
().value,e.match(m.EQUALS),t+=e.token().value,n=e.peek();while(n!==m.COMMA&&n!==
m.S&&n!==m.RPAREN)e.get(),t+=e.token().value,n=e.peek()}while(e.match([m.COMMA,m
.S]));e.match(m.RPAREN),t+=")",this._readWhitespace()}return t},_hexcolor:function(
){var e=this._tokenStream,t=null,n;if(e.match(m.HASH)){t=e.token(),n=t.value;if(!/#[a-f0-9]{3,6}/i
.test(n))throw new i("Expected a hex color but found '"+n+"' at line "+t.startLine+", col "+
t.startCol+".",t.startLine,t.startCol);this._readWhitespace()}return t},_keyframes
:function(){var e=this._tokenStream,t,n,r,i="";e.mustMatch(m.KEYFRAMES_SYM),t=e.
token(),/^@\-([^\-]+)\-/.test(t.value)&&(i=RegExp.$1),this._readWhitespace(),r=this
._keyframe_name(),this._readWhitespace(),e.mustMatch(m.LBRACE),this.fire({type:"startkeyframes"
,name:r,prefix:i,line:t.startLine,col:t.startCol}),this._readWhitespace(),n=e.peek
();while(n===m.IDENT||n===m.PERCENTAGE)this._keyframe_rule(),this._readWhitespace
(),n=e.peek();this.fire({type:"endkeyframes",name:r,prefix:i,line:t.startLine,col
:t.startCol}),this._readWhitespace(),e.mustMatch(m.RBRACE),this._readWhitespace(
)},_keyframe_name:function(){var e=this._tokenStream;return e.mustMatch([m.IDENT
,m.STRING]),s.fromToken(e.token())},_keyframe_rule:function(){var e=this._key_list
();this.fire({type:"startkeyframerule",keys:e,line:e[0].line,col:e[0].col}),this
._readDeclarations(!0),this.fire({type:"endkeyframerule",keys:e,line:e[0].line,col
:e[0].col})},_key_list:function(){var e=this._tokenStream,t=[];t.push(this._key(
)),this._readWhitespace();while(e.match(m.COMMA))this._readWhitespace(),t.push(this
._key()),this._readWhitespace();return t},_key:function(){var e=this._tokenStream
,t;if(e.match(m.PERCENTAGE))return s.fromToken(e.token());if(e.match(m.IDENT)){t=
e.token();if(/from|to/i.test(t.value))return s.fromToken(t);e.unget()}this._unexpectedToken
(e.LT(1))},_skipCruft:function(){while(this._tokenStream.match([m.S,m.CDO,m.CDC]
));},_readDeclarations:function(e,t){var n=this._tokenStream,r;this._readWhitespace
(),e&&n.mustMatch(m.LBRACE),this._readWhitespace();try{for(;;){if(!(n.match(m.SEMICOLON
)||t&&this._margin())){if(!this._declaration())break;if(!n.match(m.SEMICOLON))break}
this._readWhitespace()}n.mustMatch(m.RBRACE),this._readWhitespace()}catch(s){if(!
(s instanceof i&&!this.options.strict))throw s;this.fire({type:"error",error:s,message
:s.message,line:s.line,col:s.col}),r=n.advance([m.SEMICOLON,m.RBRACE]);if(r===m.
SEMICOLON)this._readDeclarations(!1,t);else if(r!==m.RBRACE)throw s}},_readWhitespace
:function(){var e=this._tokenStream,t="";while(e.match(m.S))t+=e.token().value;return t
},_unexpectedToken:function(e){throw new i("Unexpected token '"+e.value+"' at line "+
e.startLine+", col "+e.startCol+".",e.startLine,e.startCol)},_verifyEnd:function(
){this._tokenStream.LA(1)!==m.EOF&&this._unexpectedToken(this._tokenStream.LT(1)
)},_validateProperty:function(e,t){g.validate(e,t)},parse:function(e){this._tokenStream=new
v(e,m),this._stylesheet()},parseStyleSheet:function(e){return this.parse(e)},parseMediaQuery
:function(e){this._tokenStream=new v(e,m);var t=this._media_query();return this.
_verifyEnd(),t},parsePropertyValue:function(e){this._tokenStream=new v(e,m),this
._readWhitespace();var t=this._expr();return this._readWhitespace(),this._verifyEnd
(),t},parseRule:function(e){this._tokenStream=new v(e,m),this._readWhitespace();
var t=this._ruleset();return this._readWhitespace(),this._verifyEnd(),t},parseSelector
:function(e){this._tokenStream=new v(e,m),this._readWhitespace();var t=this._selector
();return this._readWhitespace(),this._verifyEnd(),t},parseStyleAttribute:function(
e){e+="}",this._tokenStream=new v(e,m),this._readDeclarations()}};for(t in n)Object
.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t]);return e}()},{"../util/EventTarget"
:23,"../util/SyntaxError":25,"../util/SyntaxUnit":26,"./Combinator":2,"./MediaFeature"
:4,"./MediaQuery":5,"./PropertyName":8,"./PropertyValue":9,"./PropertyValuePart"
:11,"./Selector":13,"./SelectorPart":14,"./SelectorSubPart":15,"./TokenStream":17
,"./Tokens":18,"./Validation":19}],7:[function(e,t,n){"use strict";var r=t.exports=
{__proto__:null,"align-items":"flex-start | flex-end | center | baseline | stretch"
,"align-content":"flex-start | flex-end | center | space-between | space-around | stretch"
,"align-self":"auto | flex-start | flex-end | center | baseline | stretch",all:"initial | inherit | unset"
,"-webkit-align-items":"flex-start | flex-end | center | baseline | stretch","-webkit-align-content"
:"flex-start | flex-end | center | space-between | space-around | stretch","-webkit-align-self"
:"auto | flex-start | flex-end | center | baseline | stretch","alignment-adjust"
:"auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | | "
,"alignment-baseline":"auto | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical"
,animation:1,"animation-delay":"