Dia antes primera install

This commit is contained in:
2025-12-08 15:20:28 -06:00
commit 1416478c9c
4130 changed files with 886376 additions and 0 deletions

4
node_modules/stringify-parameters/.jshintrc generated vendored Normal file
View File

@@ -0,0 +1,4 @@
{
"esversion": 6,
"node": true
}

1
node_modules/stringify-parameters/.npmignore generated vendored Normal file
View File

@@ -0,0 +1 @@
_private/

4
node_modules/stringify-parameters/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,4 @@
language: node_js
node_js:
- 6
- 8

32
node_modules/stringify-parameters/README.md generated vendored Normal file
View File

@@ -0,0 +1,32 @@
# stringify-parameters
[![Build Status](https://api.travis-ci.org/DiegoZoracKy/stringify-parameters.svg)](https://travis-ci.org/DiegoZoracKy/stringify-parameters)
Stringifies function's parameters definition. Useful to create automated tasks, intellisense, .
## Installation
```bash
npm install stringify-parameters
```
**CLI**
```bash
npm install stringify-parameters -g
```
## Usage
`stringifyParameters(fn);`
Where **fn** is a *function* reference or a *function* definition stringified (e.g. fn.toString())
```javascript
const stringifyParameters = require('stringify-parameters');
// Just a function to test
const testFunction = (a = "z", b = [1,2,3], c, {d,e: {f}, g} = {}) => console.log("noop");
// `result` will be: 'a = "z, b = [1,2,3], c, {d,e: {f}, g} = {}'
const result = stringifyParameters(testFunction);
```

3
node_modules/stringify-parameters/bin/cli.js generated vendored Executable file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
require('magicli')();

View File

@@ -0,0 +1,29 @@
'use strict';
const unpackString = require('unpack-string');
function stringifyParameters(fn) {
if (!fn || (fn.constructor !== String && fn.constructor !== Function)) {
return;
}
let fnString = fn.toString().replace(/^\s+|\s+$/g, '');
if (!fnString) {
return;
}
const isDeclaredWithFunctionKeyword = /^function/i;
const isNotArrowFunction = /^[^\s=>]+\(/i;
// Is an Arrow function with a parameter declared without parenthesis and with no default value
if (!isDeclaredWithFunctionKeyword.test(fnString) && !isNotArrowFunction.test(fnString)) {
let arrowWithoutParenthesis = fnString.match(/^(.*?)=>/);
if (arrowWithoutParenthesis) {
return unpackString(arrowWithoutParenthesis[1]).replace(/^\s+|\s+$/g, '');
}
}
return unpackString(fnString).replace(/^\s+|\s+$/g, '');
}
module.exports = stringifyParameters;

View File

@@ -0,0 +1,3 @@
node_modules/
_private/
npm-debug.log

View File

@@ -0,0 +1,3 @@
language: node_js
node_js:
- 6

View File

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

View File

@@ -0,0 +1,65 @@
# inspect-function
[![Build Status](https://api.travis-ci.org/DiegoZoracKy/inspect-function.svg)](https://travis-ci.org/DiegoZoracKy/inspect-function)
Inspects a function and returns informations about it (e.g. name, parameters names, parameters and default values, signature).
Useful when creating automated tasks, e.g., docs generations.
## Installation
```bash
npm install inspect-function
```
## Usage
`inspectFunction(fn, name);`
```javascript
// The module
const inspectFunction = require('inspect-function');
// Just a function to test
const testFunction = (a = 'z', b = [1,2,3], c, {d,e: {f}, g} = {}) => console.log('noop');
// Inspects
const result = inspectFunction(testFunction);
// `result` will be:
{
// If the second param, `name`, is passed in,
// it will be the value of "name" here
"name": "testFunction",
"parameters": {
"expected": [
"a",
"b",
"c",
"{d,e:{f},g}"
],
"defaultValues": {
"a": "'z'",
"b": "[1,2,3]",
"{d,e:{f},g}": "{}"
},
// Note that `"names"` contains also
// The parameters names after Destructuring
"names": [
"a",
"b",
"c",
"d",
"f",
"g"
],
"definitions": [
"a='z'",
"b=[1,2,3]",
"c",
"{d,e:{f},g}={}"
]
},
"signature": "testFunction(a = 'z', b = [1,2,3], c, {d,e:{f},g} = {});"
}
```

View File

@@ -0,0 +1,137 @@
#!/usr/bin/env node
'use strict';
const splitSkip = require('split-skip');
const unpackString = require('unpack-string');
const isArrayLike = p => p.match(/^\[+/) || null;
const isObjectLike = p => p.match(/^{+/) || null;
const matchObjectProperty = p => p.match(/^([^{]+):(.*)/) || null;
const getParametersStringfied = fn => {
let fnString = fn.constructor === String ? fn.replace(/\s/g, '') : fn.toString().replace(/\s/g, '');
// Is an Arrow function with only one argument defined without parenthesis
if (!fnString.match(/^function/) && !fnString.match(/^\(/)) {
let matchArrowWithoutParenthesis = fnString.match(/^(.*?)=>/);
return matchArrowWithoutParenthesis ? matchArrowWithoutParenthesis[1] : null;
}
return unpackString(fnString);
}
function splitSkipBrackets(string, delimiter) {
return splitSkip(string, delimiter, (state, char, i) => {
if ('{[('.indexOf(char) >= 0) {
state.skip += 1;
}
if ('}])'.indexOf(char) >= 0) {
state.skip -= 1;
}
return state;
});
}
function getParametersArray(paramsString) {
return splitSkipBrackets(paramsString, ',');
}
function inspectDestructuringParameters(param, list = []) {
param = param.trim();
const unpackedArray = getParametersArray(unpackString(param));
if (isArrayLike(param)) {
unpackedArray.forEach(param => inspectDestructuringParameters(param, list));
} else if (isObjectLike(param)) {
unpackedArray.forEach(param => {
let objectProperty = matchObjectProperty(param);
if (objectProperty) {
param = objectProperty[2];
inspectDestructuringParameters(param, list);
} else {
inspectDestructuringParameters(param, list);
}
});
} else {
const [ name, defaultValue ] = splitSkipBrackets(param, '=');
list.push([ name, defaultValue ]);
}
return list;
}
function getParametersInfo(paramsArray) {
let names = [];
let expected = [];
let defaultValues = {};
paramsArray.forEach((param) => {
let [ paramDefinition, defaultValue ] = splitSkipBrackets(param, '=');
expected.push(paramDefinition);
if (defaultValue) {
defaultValues[paramDefinition] = defaultValue;
}
if (isArrayLike(paramDefinition) || isObjectLike(paramDefinition)) {
inspectDestructuringParameters(paramDefinition)
.forEach(([paramName, defaultValue]) => {
names.push(paramName);
if(defaultValue){
defaultValues[paramName] = defaultValue;
}
});
} else {
names.push(paramDefinition);
}
});
return { parameters: { expected, defaultValues, names } };
}
function getSignatureFromParametersArray(name, paramsArray) {
return `${name}(${paramsArray.map(v => v.replace(/^([^=]*)=/, `$1 = `)).join(', ')});`
}
function getNameFromSourceCode(fn) {
let fnString = fn.constructor === String ? fn.replace(/(\r\n|\r|\n)/g, '') : fn.toString().replace(/(\r\n|\r|\n)/g, '');
fnString = fnString.replace(/function\(/g, '');
fnString = fnString.replace(/^const|let|var/, '');
let pattern = /([^ (]*)\(/;
let match = fnString.match(/([^ (]*)\(/);
if(!match){
match = fnString.match(/([^ (]*)\s?=/);
}
if(match){
return match[1].trim();
}
}
/**
* Inspects a function and returns informations about it
* @param {Function|String} fn - Function to be inspected
* @param {String} name - Name of the function to be used at the result set (it will supersed the one found during the inspection)
* @return {Object} Returns and object with fn, name, parameters, parameters, signature
*/
function inspectFunction(fn, name) {
name = name || fn.name || getNameFromSourceCode(fn) || '';
const parametersDefinitions = getParametersArray(getParametersStringfied(fn));
const { parameters } = getParametersInfo(parametersDefinitions);
const signature = getSignatureFromParametersArray(name, parametersDefinitions);
parameters.definitions = parametersDefinitions;
return {
fn: fn.constructor === Function ? fn : null,
name,
parameters,
signature
}
}
module.exports = inspectFunction;

View File

@@ -0,0 +1,34 @@
{
"name": "inspect-function",
"version": "0.2.2",
"description": "Inspects a function and returns informations about it (e.g. name, parameters names, parameters and default values, signature)",
"main": "lib/inspect-function.js",
"author": {
"name": "Diego ZoracKy",
"email": "diego.zoracky@gmail.com",
"url": "https://github.com/DiegoZoracKy/"
},
"keywords": [
"function",
"inspect",
"params",
"signature",
"parameters",
"arguments",
"jsdocs",
"docs"
],
"scripts": {
"test": "mocha ./tests/main.test.js",
"test:all": "mocha ./tests -b"
},
"license": "MIT",
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^3.3.0"
},
"dependencies": {
"split-skip": "0.0.1",
"unpack-string": "0.0.2"
}
}

View File

@@ -0,0 +1,208 @@
#!/usr/bin/env node
'use strict';
const inspectFunction = require('../');
const assert = require('assert');
describe('inspectFunction', function() {
const functionsSchemas = getTestData();
Object.keys(functionsSchemas).forEach(key => {
const inspectResult = inspectFunction(functionsSchemas[key][key]);
describe(`${inspectResult.signature}`, function() {
it(`Must find the same length of expected parameters`, function() {
assert.equal(functionsSchemas[key].parameters.expected.length, inspectResult.parameters.expected.length);
});
it(`Must find the same length of parameters names`, function() {
assert.equal(functionsSchemas[key].parameters.names.length, inspectResult.parameters.names.length);
});
it(`Must find the same parameters names`, function() {
functionsSchemas[key].parameters.names.sort();
inspectResult.parameters.names.sort();
assert.equal(true, functionsSchemas[key].parameters.names.every((param, i) => param === inspectResult.parameters.names[i]));
});
it(`Must find the same expected parameters`, function() {
functionsSchemas[key].parameters.expected.sort();
inspectResult.parameters.expected.sort();
assert.equal(true, functionsSchemas[key].parameters.expected.every((param, i) => param === inspectResult.parameters.expected[i]));
});
});
});
});
function getTestData(){
const functionsSchemas = {
arrowWithoutParenthesis: {
parameters: {
expected: ['param'],
names: ['param']
},
arrowWithoutParenthesis: param => console.log(a)
},
arrow: {
parameters: {
expected: ['paramA', 'paramB', 'c'],
names: ['paramA', 'paramB', 'c']
},
arrow: (paramA, paramB, c) => console.log(a, b, c)
},
arrowWithBraces: {
parameters: {
expected: ['a', 'b', 'c'],
names: ['a', 'b', 'c']
},
arrowWithBraces: (a, b, c) => {
return console.log(a, b, c)
}
},
arrowWithoutParenthesisWithBraces: {
parameters: {
expected: ['a'],
names: ['a']
},
arrowWithoutParenthesisWithBraces: a => {
return console.log(a)
}
},
function: {
parameters: {
expected: ['a', 'b', 'c'],
names: ['a', 'b', 'c']
},
function: function(a, b, c){
console.log(a, b, c)
}
},
functionWithName: {
parameters: {
expected: ['a'],
names: ['a']
},
functionWithName: function withName(a) {
console.log(a)
}
},
arrowWithBracesWithDefaultParameters: {
parameters: {
expected: ['option', 'a', 'b', 'arr', 'arr2', 'e', 'z'],
names: ['option', 'a', 'b', 'arr', 'arr2', 'e', 'z']
},
arrowWithBracesWithDefaultParameters: (option, a = 2, b= {c:1}, arr = ([]), arr2 = [1,2,3], e = { a: {
b: 3,
d: ([{}])}
},z) => (a = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s})
},
functionWithDefaultParameters: {
parameters: {
expected: ['option', 'a', 'b', 'arr', 'e', 'z'],
names: ['option', 'a', 'b', 'arr', 'e', 'z']
},
functionWithDefaultParameters: function (option, a = 2, b= {c:1}, arr = ([]), e = { a: {
b: 3,
d: ([{}])}
},z) {return (a = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s})}
},
functionWithNameWithDefaultParameters: {
parameters: {
expected: ['option', 'a', 'b', 'arr', 'e', 'z'],
names: ['option', 'a', 'b', 'arr', 'e', 'z']
},
functionWithNameWithDefaultParameters: function someFnName(option, a = 2, b= {c:1}, arr = ([]), e = { a: {
b: 3,
d: ([{}])}
},z) { return (a = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s})}
},
arrowFunctionWithDestructuringInnerDefaultParameters: {
parameters: {
expected: [`{str='strDefault',bool=false,obj={ob:1,j:2},arrObj=[{o}]}`],
names: ['str', 'bool', 'obj', 'arrObj']
},
arrowFunctionWithDestructuringInnerDefaultParameters: ({ str = 'strDefault', bool = false, obj = {ob:1,j:2}, arrObj = [{o}] } = {}) => {}
},
functionWithDestructuringInnerDefaultParameters: {
parameters: {
expected: [`{str='strDefault',bool=false,obj={ob:1,j:2},arrObj=[{o}]}`],
names: ['str', 'bool', 'obj', 'arrObj']
},
functionWithDestructuringInnerDefaultParameters: function ({ str = 'strDefault', bool = false, obj = {ob:1,j:2}, arrObj = [{o}] } = {}) {}
},
functionWithNameWithDestructuringInnerDefaultParameters: {
parameters: {
expected: [`{str='strDefault',bool=false,obj={ob:1,j:2},arrObj=[{o}]}`],
names: ['str', 'bool', 'obj', 'arrObj']
},
functionWithNameWithDestructuringInnerDefaultParameters: function someFnName({ str = 'strDefault', bool = false, obj = {ob:1,j:2}, arrObj = [{o}] } = {}) {}
},
functionsWithHardDefaultParameters: {
parameters: {
expected: ['option', 'bz', 'arr', 'arr2', 'dk', 'e', 'fn', 'fn2', '[destru,[cturi],[ng]]', 'c', '{dd,ee,ff}', '{ddd,eee:{zzz},fff}', 'g'],
names: ['destru', 'cturi', 'ng', 'ddd', 'zzz', 'fff', 'option', 'bz', 'arr', 'arr2', 'dk', 'e', 'fn', 'fn2', 'c', 'dd', 'ee', 'ff', 'g']
},
functionsWithHardDefaultParameters: function ( [destru, [cturi],[ng]]= [1], {ddd,eee: {zzz},fff}, option = 2, bz= {c:1}, arr = [], arr2=[1,2,4], dk =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s},c, {dd, ee , ff} = {dd: {b: 1, c:2, arr:[1,6]}}, g) { return (x = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return z})}
},
functionsWithNameWithHardDefaultParameters: {
parameters: {
expected: ['option', 'bz', 'arr', 'arr2', 'dk', 'e', 'fn', 'fn2', '[destru,[cturi],[ng]]', 'c', '{dd,ee,ff}', '{ddd,eee:{zzz},fff}', 'g'],
names: ['destru', 'cturi', 'ng', 'ddd', 'zzz', 'fff', 'option', 'bz', 'arr', 'arr2', 'dk', 'e', 'fn', 'fn2', 'c', 'dd', 'ee', 'ff', 'g']
},
functionsWithNameWithHardDefaultParameters: function someFnName([destru, [cturi],[ng]]= [1], {ddd,eee: {zzz},fff}, option = 2, bz= {c:1}, arr = [...z, ...k], arr2=[1,2,4, ...k], dk =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s}, c, {dd, ee , ff} = {dd: {b: 1, c:2, arr:[1,6]}}, g) { return (x = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return z})}
},
arrowWithBracesWithHardDefaultParameters: {
parameters: {
expected: ['option', 'bz', 'arr', 'arr2', 'dk', 'e', 'fn', 'fn2', '[destru,[cturi],[ng]]', 'c', '{dd,ee,ff}', '{ddd,eee:{zzz},fff}', 'g'],
names: ['destru', 'cturi', 'ng', 'ddd', 'zzz', 'fff', 'option', 'bz', 'arr', 'arr2', 'dk', 'e', 'fn', 'fn2', 'c', 'dd', 'ee', 'ff', 'g']
},
arrowWithBracesWithHardDefaultParameters: ([destru, [cturi],[ng]]= [1], {ddd,eee: {zzz},fff}, option = 2, bz= {c:1}, arr = [...z], arr2=[1,2,4,...k], dk =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s}, c, {dd, ee , ff} = {dd: {b: 1, c:2, arr:[1,6]}}, g) => { return (x = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return z})}
}
};
return functionsSchemas;
}

View File

@@ -0,0 +1,2 @@
node_modules/
_private/

View File

@@ -0,0 +1,40 @@
# MagiCLI
Automagically generates command-line interfaces (CLI), for any module.
Just `require('magicli')();` and your module is ready to be run via CLI.
The goal is to have any module prepared to be installed globally `-g` and to be run via CLI, with no efforts. Follow these 3 steps and you are done:
* `npm install magicli --save`
* Add the property `bin` to your package.json with the value `./bin/cli.js`
* Create the file `./bin/cli.js` with the following content:
```javascript
#!/usr/bin/env node
require('magicli')();
```
**That's it!** Install your module with `-g` and run it with `--help`. In the same way you can just run `node ./bin/cli.js --help` to test it quickly, without install.
## How it works
Let's suppose that `your-module` exports the function:
```javascript
module.exports = function(param1, param2) {
return param1 + param2;
}
```
When calling it via CLI, the program will be expecting the parameters names as options. It doesn't need to follow the same order as defined in the function. Example:
```bash
$ your-module --param2="K" --param1="Z"
```
It will work with any kind of function declaration, e.g.:
```javascript
// An Arrow function with Destructuring assignment and Default values
const fn = ([param1, [param2]] = ['z', ['k']], { param3 }) => {};
module.exports = fn;
```

View File

@@ -0,0 +1,80 @@
'use strict';
const inspectFunction = require('inspect-function');
const isArrayLike = p => p.match(/^\[+/) || null;
const isObjectLike = p => p.match(/^{+/) || null;
const matchObjectProperty = p => p.match(/^([^{]+):(.*)/) || null;
const unpackArrayOrObject = p => p.replace(/^[\[{]|[\]}]$/g, '');
const unpackParameter = (param, options) => {
let unpacked = getParametersArray(unpackArrayOrObject(param));
if (isArrayLike(param)) {
return unpacked.map(unpackedParam => getParameterValue(unpackedParam, options));
}
if (isObjectLike(param)) {
return unpacked.reduce((paramValue, unpackedParam) => {
let objectProperty = matchObjectProperty(unpackedParam);
if(objectProperty){
let [, key, value] = objectProperty.map(v => v.trim());
paramValue[key] = getParameterValue(value, options);
} else {
paramValue[unpackedParam] = getParameterValue(unpackedParam, options);
}
return paramValue;
}, {});
}
};
const getParameterValue = (param, options) => {
if(isArrayLike(param) || isObjectLike(param)){
return unpackParameter(param, options);
}
return options[param];
}
function getParametersArray(paramsString) {
let startIndex = 0;
let skipComma;
const paramsFound = paramsString.split('').reduce((paramsFound, chr, i, arr) => {
if (chr.match(/\[|\{|\(/)) {
skipComma = true;
}
if (chr.match(/\]|\}|\)/)) {
skipComma = false;
}
if (!skipComma && (chr === ',' || i === arr.length - 1)) {
const lastIndex = i === arr.length - 1 ? i + 1 : i;
const paramFound = paramsString.substring(startIndex, lastIndex);
startIndex = lastIndex + 1;
paramsFound.push(paramFound);
}
return paramsFound;
}, []);
return paramsFound.map(p => p.trim());
}
const optionsToParameters = (parameters, options) => {
return parameters.map(param => getParameterValue(param, options));
};
const fnParametersFromOptions = (fn, object) => {
const fnParams = inspectFunction(fn).parameters.expected;
return optionsToParameters(fnParams, object);
};
const callWithObject = (fn, object) => {
const fnParams = inspectFunction(fn).parameters.expected;
const objectParameters = optionsToParameters(fnParams, object);
return fn(...objectParameters);
};
module.exports = { callWithObject, fnParametersFromOptions };

View File

@@ -0,0 +1,152 @@
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const inspectFunction = require('inspect-function');
const pipe = require('pipe-functions');
const getStdin = require('get-stdin');
const { callWithObject } = require('./call-with-object');
const commander = require('commander');
function getFlattenedAPI(o, path = '', methods = {}) {
for (let prop in o) {
if (o[prop].constructor === Function) {
let methodCall = path ? `${path}-${prop}` : prop;
methods[methodCall] = { method: o[prop] };
let functionParams = inspectFunction(o[prop]).parameters.names;
if (functionParams) {
methods[methodCall] = {
params: functionParams,
method: o[prop]
};
}
}
if (o[prop].constructor === Object) {
methods = getFlattenedAPI(o[prop], path ? `${path}-${prop}` : prop, methods);
}
}
return methods;
}
function execPipeline(command, params, pipes = {}) {
let pipeline = [];
// Before
if (pipes.before) {
pipeline.push(pipes.before);
}
// Main Command
pipeline.push(args => commandExec(command, args));
// After
if (pipes.after) {
pipeline.push(pipes.after);
}
// Output
pipeline.push(console.log);
// Exec pipe
pipe(params, ...pipeline);
}
function commandExec(command, args) {
let methodReturn = callWithObject(command, args);
if (methodReturn && methodReturn.then) {
return methodReturn.then(data => data).catch(console.error);
} else {
return methodReturn;
}
}
function findPackageJson(currentPath) {
currentPath = currentPath.replace(/\/[^/]+$/g, '');
if (fs.existsSync(`${currentPath}/package.json`)) {
return `${currentPath}/package.json`;
}
if (currentPath.match(/\//)) {
return findPackageJson(currentPath);
}
}
function main(options = { pipes: {} }) {
process.env.NODE_CLI = true;
const packageJsonPath = options.modulePath || findPackageJson(process.argv[1]);
const packageJson = require(packageJsonPath);
const moduleEntryPoint = path.resolve(packageJsonPath.replace('package.json', packageJson.main || 'index.js'));
const moduleAPI = require(moduleEntryPoint);
const moduleVersion = packageJson.version;
commander.version(moduleVersion);
// Module is a Function :: TODO: Even being a function, it still can have properties / methods
if (moduleAPI.constructor === Function) {
commander.usage(`[options]`);
// Get function parameters names
const params = inspectFunction(moduleAPI).parameters.names;
// Create Options
params.forEach(param => commander.option(`--${param} [value]`, 'Input'));
commander.parse(process.argv);
getStdin()
.then(input => {
if (!input && params.length && !process.argv.slice(2).length) {
commander.outputHelp();
} else if (input && options.pipes.stdin) {
pipe(() => options.pipes.stdin(input, commander), args => execPipeline(moduleAPI, args, options.pipes));
} else {
execPipeline(moduleAPI, commander, options.pipes);
}
})
.catch(err => console.log('err', err));
}
// Module is a set of methods structured as a Object Literal
else if (moduleAPI.constructor === Object) {
commander.usage(`<command> [options]`);
const methods = getFlattenedAPI(moduleAPI);
Object.keys(methods).forEach(methodKey => {
let cmd = commander.command(methodKey);
// Create Options
methods[methodKey].params.forEach(param => cmd.option(`--${param} [option]`));
cmd.action(args => {
methodKey = methodKey.replace(/\./g, '-');
getStdin()
.then(input => {
if (!input && methods[methodKey].params.length && !process.argv.slice(3).length) {
cmd.help();
} else if (input && options.pipes.stdin) {
pipe(
() => options.pipes.stdin(input, args),
args => execPipeline(methods[methodKey].method, args, options.pipes[methodKey] || options.pipes)
);
} else {
return execPipeline(methods[methodKey].method, args, options.pipes[methodKey] || options.pipes);
}
})
.catch(err => console.log('err', err));
});
});
commander.parse(process.argv);
if (!process.argv.slice(2).length) {
return commander.outputHelp();
}
}
}
module.exports = main;

View File

@@ -0,0 +1,29 @@
{
"name": "magicli",
"version": "0.0.5",
"description": "Automagically generates command-line interfaces (CLI), for any module",
"main": "lib/magicli.js",
"scripts": {
"test": "mocha ./tests"
},
"author": {
"name": "Diego ZoracKy",
"email": "diego.zoracky@gmail.com",
"url": "https://github.com/DiegoZoracKy/"
},
"keywords": [
"bin",
"cli"
],
"license": "MIT",
"dependencies": {
"commander": "^2.9.0",
"get-stdin": "^5.0.1",
"inspect-function": "^0.2.1",
"pipe-functions": "^1.2.0"
},
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^3.0.2"
}
}

View File

@@ -0,0 +1,3 @@
node_modules/
_private/
npm-debug*

View File

@@ -0,0 +1,3 @@
language: node_js
node_js:
- "6"

View File

@@ -0,0 +1,69 @@
# split-skip
[![Build Status](https://api.travis-ci.org/DiegoZoracKy/split-skip.svg)](https://travis-ci.org/DiegoZoracKy/split-skip)
Splits a String into an Array of substrings with the option to skip some cases where the separator is found, based on some *truthy* condition.
**Node.js** and **Browser** ready.
## Installation
```bash
npm install split-skip
```
## Usage
```javascript
const splitSkip = require('split-skip');
//@param {String} str - Input String
const str = 'Some,String,as,an,Input';
// @param {String} separator - Specifies the character(s) to use for separating the string
const separator = ',';
// @param {Function} skipState - Function to be called on each iteration, to manage the skip state. Parameters: `(state, char, i)`
const skipState = (state, char, i) => {
/*
Some logic to define state.skip equals to some truthy value
e.g. state.skip = true, state.skip = 1
when it should skip if the current char matches the separator
*/
/*
And define state.skip equals to some falsy value
e.g. state.skip = false, state.skip = 0
when it should get back splitting if the current char matches the separator
*/
// Must alway return the state;
return state;
};
const resultArray = splitSkip(str, separator, skipState);
```
## Example
As an input we have a string representing the parameters definition of a function from where we want to get each individual parameter. One idea of doing this is to split on every comma, but skipping the commas that are present on destructuring parameters definitions.
Using splitSkip, it could be like:
```javascript
const input = `[destru,cturu,cing]=[1],param,{dd,ee,ff}={dd:{b:1,c:2,arr:[1,6]}},last`;
const result = splitSkip(input, ',', (state, char, i) => {
if ('{[('.indexOf(char) >= 0) {
state.skip += 1;
}
if ('}])'.indexOf(char) >= 0) {
state.skip -= 1;
}
return state;
});
// result === ['[destru,cturu,cing]=[1]', 'param', '{dd,ee,ff}={dd:{b:1,c:2,arr:[1,6]}}', 'last'];
```

View File

@@ -0,0 +1,41 @@
'use strict';
/**
* Splits a String into an Array of substrings with the option to skip some cases where the separator is found, based on some truthy condition.
* @param {String} str Input String
* @param {String} separator Specifies the character(s) to use for separating the string
* @param {Function} skipState Function to be called on each iteration, to manage the skip state. `(state, char, i)`
* @return {Array} An array of strings split at each point where the separator occurs in the given string while the skipState were truthy.
*/
function splitSkip(str, separator, skipState) {
const result = [];
if (!str) {
return [str];
}
let indexStart = 0;
let indexEnd = 0;
let state = {
skip: 0
};
for (let i = 0; i < str.length; i++) {
const char = separator.length === 1 ? str[i] : str.substr(i, separator.length);
state = skipState ? skipState(state, char, i) : state;
const compareSeparator = char === separator;
if ((!state.skip && compareSeparator) || i === str.length - 1) {
indexEnd = i === str.length - 1 ? i + 1 : i;
result.push(str.substring(indexStart, indexEnd));
indexStart = indexEnd + separator.length;
i = i;
}
}
return result;
}
module.exports = splitSkip;

View File

@@ -0,0 +1,23 @@
{
"name": "split-skip",
"version": "0.0.1",
"description": "Splits a String into an Array of substrings with the option to skip some cases where the separator is found, based on some truthy condition.",
"main": "lib/split-skip.js",
"author": {
"name": "Diego ZoracKy",
"email": "diego.zoracky@gmail.com",
"url": "https://github.com/DiegoZoracKy/"
},
"scripts": {
"test": "mocha ./test/main.test.js"
},
"keywords": [
"split",
"skip"
],
"license": "MIT",
"devDependencies": {
"chai": "^4.0.0",
"mocha": "^3.4.2"
}
}

View File

@@ -0,0 +1,35 @@
'use strict';
const splitSkip = require(`../`);
const assert = require(`assert`);
describe(``, function() {
it(`must skip commas found in destructuring parameters`, function() {
const test = `[destru,cturu,cing]=[1],param,{dd,ee,ff}={dd:{b:1,c:2,arr:[1,6]}},last`;
const expected = ['[destru,cturu,cing]=[1]', 'param', '{dd,ee,ff}={dd:{b:1,c:2,arr:[1,6]}}', 'last'];
const result = splitSkip(test, ',', (state, char, i) => {
if ('{[('.indexOf(char) >= 0) {
state.skip += 1;
}
if ('}])'.indexOf(char) >= 0) {
state.skip -= 1;
}
return state;
});
assert(result.every(item => expected.includes(item)));
});
it(`must not skip commas found in destructuring parameters`, function() {
const test = `[destru,cturu,cing]=[1],param,{dd,ee,ff}={dd:{b:1,c:2,arr:[1,6]}},last`;
const expected = [ '[destru', 'cturu', 'cing]=[1]', 'param', '{dd', 'ee', 'ff}={dd:{b:1', 'c:2', 'arr:[1', '6]}}', 'last' ];
const result = splitSkip(test, ',');
assert(result.every(item => expected.includes(item)));
});
});

32
node_modules/stringify-parameters/package.json generated vendored Normal file
View File

@@ -0,0 +1,32 @@
{
"name": "stringify-parameters",
"version": "0.0.4",
"description": "Stringifies function's parameters definition",
"main": "./lib/stringify-parameters.js",
"bin": "./bin/cli.js",
"scripts": {
"test": "mocha ./test/main.test.js"
},
"author": {
"name": "Diego ZoracKy",
"email": "diego.zoracky@gmail.com",
"url": "https://github.com/DiegoZoracKy/"
},
"license": "MIT",
"dependencies": {
"magicli": "0.0.5",
"unpack-string": "0.0.2"
},
"devDependencies": {
"mocha": "^3.5.0"
},
"keywords": [
"functions",
"function",
"parameters",
"parameter",
"string",
"stringify",
"stringified"
]
}

124
node_modules/stringify-parameters/test/main.test.js generated vendored Normal file
View File

@@ -0,0 +1,124 @@
#!/usr/bin/env node
'use strict';
const stringifyParameters = require('../');
const assert = require('assert');
describe('stringifyParameters', function() {
const functionsDefinitions = getTestData();
Object.keys(functionsDefinitions).forEach(key => {
describe(`${key}`, function() {
it(`Must match the expected parameters`, function() {
const parametersStringified = stringifyParameters(functionsDefinitions[key].input);
assert.equal(parametersStringified, functionsDefinitions[key].expectedResult);
});
});
});
});
function getTestData(){
const functionsDefinitions = {
arrowWithoutParenthesis: {
input: param => console.log(param),
expectedResult: 'param'
},
arrow: {
input: (paramA, paramB, c) => console.log(a, b, c),
expectedResult: 'paramA, paramB, c'
},
arrowWithBraces: {
input: (a, b, c) => {
return console.log(a, b, c)
},
expectedResult: 'a, b, c'
},
arrowWithoutParenthesisWithBraces: {
input: a => {
return console.log(a)
},
expectedResult: 'a'
},
simpleFunction: {
input: function(a, b, c){
console.log(a, b, c)
},
expectedResult: 'a, b, c'
},
functionWithName: {
input: function withName(abc) {
console.log(abc)
},
expectedResult: 'abc'
},
arrowWithBracesWithDefaultParameters: {
input: (option, a = 2, b= {c:1}, arr = ([]), arr2 = [1,2,3], e = { a: {
b: 3,
d: ([{}])}
},z) => (a = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s}),
expectedResult: `option, a = 2, b= {c:1}, arr = ([]), arr2 = [1,2,3], e = { a: {
b: 3,
d: ([{}])}
},z`
},
functionWithDefaultParameters: {
input: function (option, a = 2, b= {c:1}, arr = ([]), e = { a: {
b: 3,
d: ([{}])}
},z) {return (a = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s})},
expectedResult: `option, a = 2, b= {c:1}, arr = ([]), e = { a: {
b: 3,
d: ([{}])}
},z`
},
functionWithNameWithDestructuringInnerDefaultParameters: {
input: function someFnName({ str = 'strDefault', bool = false, obj = {ob:1,j:2}, arrObj = [{o}] } = {}) {},
expectedResult: `{ str = 'strDefault', bool = false, obj = {ob:1,j:2}, arrObj = [{o}] } = {}`
},
functionsWithComplexParameters: {
input: function ([destru, [cturi],[ng]]= [1], {ddd,eee: {zzz},fff}, option = 2, bz= {c:1}, arr = [...z, ...k], arr2=[1,2,4, ...k], dk =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s}, c, {dd, ee , ff} = {dd: {b: 1, c:2, arr:[1,6]}}, g) { return (x = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return z})},
expectedResult: `[destru, [cturi],[ng]]= [1], {ddd,eee: {zzz},fff}, option = 2, bz= {c:1}, arr = [...z, ...k], arr2=[1,2,4, ...k], dk =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s}, c, {dd, ee , ff} = {dd: {b: 1, c:2, arr:[1,6]}}, g`
},
arrowWithBracesWithHardDefaultParameters: {
input: ([destru, [cturi],[ng]]= [1], {ddd,eee: {zzz},fff}, option = 2, bz= {c:1}, arr = [...z], arr2=[1,2,4,...k], dk =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s}, c, {dd, ee , ff} = {dd: {b: 1, c:2, arr:[1,6]}}, g) => { return (x = 2, b= {c:1}, arr = [], d =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return z})},
expectedResult: `[destru, [cturi],[ng]]= [1], {ddd,eee: {zzz},fff}, option = 2, bz= {c:1}, arr = [...z], arr2=[1,2,4,...k], dk =function(z){}, e = { a: {
b: 3,
d: x => x}
}, fn = d => s, fn2 = d => {return s}, c, {dd, ee , ff} = {dd: {b: 1, c:2, arr:[1,6]}}, g`
}
};
return functionsDefinitions;
}