This commit is contained in:
Leifer Mendez
2022-10-29 13:18:20 +02:00
parent e00aacfe3e
commit 7593d6e564
10 changed files with 507 additions and 33 deletions

328
lib/cli/bundle.cjs Normal file
View File

@@ -0,0 +1,328 @@
'use strict';
var require$$0$3 = require('prompts');
var require$$0 = require('kleur');
var require$$0$1 = require('fs');
var require$$1$1 = require('path');
var require$$1 = require('cross-spawn');
var require$$0$2 = require('rimraf');
const { red: red$2 } = require$$0;
const spawn = require$$1;
// const { detect } = require('detect-package-manager')
const PKG_OPTION = {
npm: 'install',
yarn: 'add',
pnpm: 'add',
};
const getPkgManage$1 = async () => {
// const pkg = await detect()
// return pkg
return 'npm'
};
const installDeps$1 = (pkgManager, packageList) => {
const errorMessage = `Ocurrio un error instalando ${packageList}`;
let childProcess = [];
const installSingle = (pkgInstall) => () => {
new Promise((resolve) => {
try {
childProcess = spawn(
pkgManager,
[PKG_OPTION[pkgManager], pkgInstall],
{
stdio: 'inherit',
}
);
childProcess.on('error', (e) => {
console.error(e);
console.error(red$2(errorMessage));
resolve();
});
childProcess.on('close', (code) => {
if (code === 0) {
resolve();
} else {
console.error(code);
console.error(red$2(errorMessage));
}
});
resolve();
} catch (e) {
console.error(e);
console.error(red$2(errorMessage));
}
});
};
if (typeof packageList === 'string') {
childProcess.push(installSingle(packageList));
} else {
for (const pkg of packageList) {
childProcess.push(installSingle(pkg));
}
}
const runInstall = () => {
return Promise.all(childProcess.map((i) => i()))
};
return { runInstall }
};
var tool = { getPkgManage: getPkgManage$1, installDeps: installDeps$1 };
const { readFileSync, existsSync } = require$$0$1;
const { join: join$2 } = require$$1$1;
const { installDeps, getPkgManage } = tool;
const PATHS_DIR = [
join$2(__dirname, 'pkg-to-update.json'),
join$2(__dirname, '..', 'pkg-to-update.json'),
];
const PKG_TO_UPDATE = () => {
const PATH_INDEX = PATHS_DIR.findIndex((a) => existsSync(a));
const data = readFileSync(PATHS_DIR[PATH_INDEX], 'utf-8');
const dataParse = JSON.parse(data);
const pkg = Object.keys(dataParse).map((n) => `${n}@${dataParse[n]}`);
return pkg
};
const installAll$1 = async () => {
const pkg = await getPkgManage();
installDeps(pkg, PKG_TO_UPDATE()).runInstall();
};
var install = { installAll: installAll$1 };
const rimraf = require$$0$2;
const { yellow: yellow$2 } = require$$0;
const { join: join$1 } = require$$1$1;
const PATH_WW = [
join$1(process.cwd(), '.wwebjs_auth'),
join$1(process.cwd(), 'session.json'),
];
const cleanSession$1 = () => {
const queue = [];
for (const PATH of PATH_WW) {
console.log(yellow$2(`😬 Eliminando: ${PATH}`));
queue.push(rimraf(PATH, () => Promise.resolve()));
}
return Promise.all(queue)
};
var clean = { cleanSession: cleanSession$1 };
const { red: red$1, yellow: yellow$1, green, bgCyan } = require$$0;
const checkNodeVersion$1 = () => {
console.log(bgCyan('🚀 Revisando tu Node.js'));
const version = process.version;
const majorVersion = parseInt(version.replace('v', '').split('.').shift());
if (majorVersion < 16) {
console.error(
red$1(
`🔴 Se require Node.js 16 o superior. Actualmente esta ejecutando Node.js ${version}`
)
);
process.exit(1);
}
console.log(green(`Node.js combatible ${version}`));
console.log(``);
};
const checkOs$1 = () => {
console.log(bgCyan('🙂 Revisando tu Sistema Operativo'));
const os = process.platform;
if (!os.includes('win32')) {
const messages = [
`El sistema operativo actual (${os}) posiblemente requiera`,
`una confiuración adicional referente al puppeter`,
``,
`Recuerda pasar por el WIKI`,
`🔗 https://github.com/leifermendez/bot-whatsapp/wiki/Instalaci%C3%B3n`,
``,
];
console.log(yellow$1(messages.join(' \n')));
}
console.log(``);
};
var check = { checkNodeVersion: checkNodeVersion$1, checkOs: checkOs$1 };
const { writeFile } = require$$0$1.promises;
const { join } = require$$1$1;
/**
* JSON_TEMPLATE = {[key:string]{...pros}}
*/
const JSON_TEMPLATE = {
provider: {
vendor: '',
},
database: {
host: '',
password: '',
port: '',
username: '',
db: '',
},
io: {
vendor: '',
},
};
const PATH_CONFIG = join(process.cwd(), 'config.json');
const jsonConfig$1 = () => {
return writeFile(
PATH_CONFIG,
JSON.stringify(JSON_TEMPLATE, null, 2),
'utf-8'
)
};
var configuration = { jsonConfig: jsonConfig$1 };
const prompts = require$$0$3;
const { yellow, red } = require$$0;
const { installAll } = install;
const { cleanSession } = clean;
const { checkNodeVersion, checkOs } = check;
const { jsonConfig } = configuration;
const startInteractive$1 = async () => {
const questions = [
{
type: 'text',
name: 'dependencies',
message:
'Quieres actualizar las librerias "whatsapp-web.js"? (Y/n)',
},
{
type: 'text',
name: 'cleanTmp',
message: 'Quieres limpiar la session del bot? (Y/n)',
},
{
type: 'multiselect',
name: 'providerWs',
message: 'Proveedor de Whatsapp',
choices: [
{ title: 'whatsapp-web.js', value: 'whatsapp-web.js' },
{ title: 'API Oficial (Meta)', value: 'meta', disabled: true },
{ title: 'Twilio', value: 'twilio', disabled: true },
],
max: 1,
hint: 'Espacio para selecionar',
instructions: '↑/↓',
},
{
type: 'multiselect',
name: 'providerDb',
message: 'Cual base de datos quieres usar',
choices: [
{ title: 'JSONFile', value: 'json' },
{ title: 'MySQL', value: 'mysql', disabled: true },
{ title: 'Mongo', value: 'mongo', disabled: true },
],
max: 1,
hint: 'Espacio para selecionar',
instructions: '↑/↓',
},
];
console.clear();
checkNodeVersion();
checkOs();
const onCancel = () => {
console.log('Proceso cancelado!');
return true
};
const response = await prompts(questions, { onCancel });
const {
dependencies = '',
cleanTmp = '',
providerDb = [],
providerWs = [],
} = response;
/**
* Question #1
* @returns
*/
const installOrUdpateDep = async () => {
const answer = dependencies.toLowerCase() || 'n';
if (answer.includes('n')) return true
if (answer.includes('y')) {
await installAll();
return true
}
};
/**
* Question #2
* @returns
*/
const cleanAllSession = async () => {
const answer = cleanTmp.toLowerCase() || 'n';
if (answer.includes('n')) return true
if (answer.includes('y')) {
await cleanSession();
return true
}
};
const vendorProvider = async () => {
if (!providerWs.length) {
console.log(
red(
`Debes de seleccionar una WS Provider. Tecla [Space] para seleccionar`
)
);
process.exit(1);
}
console.log(yellow(`'Deberia crer una carpeta en root/provider'`));
return true
};
const dbProvider = async () => {
const answer = providerDb;
if (!providerDb.length) {
console.log(
red(
`Debes de seleccionar una DB Provider. Tecla [Space] para seleccionar`
)
);
process.exit(1);
}
if (answer === 'json') {
console.log('Deberia crer una carpeta en root/data');
return 1
}
};
await installOrUdpateDep();
await cleanAllSession();
await vendorProvider();
await dbProvider();
await jsonConfig();
};
var interactive = { startInteractive: startInteractive$1 };
const { startInteractive } = interactive;
if (process.env.NODE_ENV === 'dev') startInteractive();
var cli = { startInteractive };
module.exports = cli;

82
lib/io/bundle.cjs Normal file
View File

@@ -0,0 +1,82 @@
'use strict';
var require$$0 = require('crypto');
const crypto = require$$0;
const generateRef$3 = () => {
return crypto.randomUUID()
};
var hash = { generateRef: generateRef$3 };
const { generateRef: generateRef$2 } = hash;
var utils = { generateRef: generateRef$2 };
const { generateRef: generateRef$1 } = utils;
const addAnswer$3 = (inCtx) => (message, options) => {
const lastCtx = inCtx.hasOwnProperty('ctx') ? inCtx.ctx : inCtx;
const ctxAnswer = () => {
const ref = generateRef$1();
/**
* Se guarda en db
*/
return { ...lastCtx, ref, message }
};
const ctx = ctxAnswer();
return {
ctx,
ref: ctx.ref,
addAnswer: addAnswer$3(ctx),
}
};
var addAnswer_1 = { addAnswer: addAnswer$3 };
const { generateRef } = utils;
const { addAnswer: addAnswer$2 } = addAnswer_1;
/**
* addKeyword:
* Es necesario que genere id|hash
*/
/**
*
* @param {*} message `string | string[]`
* @param {*} options {sensitivy:boolean} defaulta false
*/
const addKeyword$2 = (message, options) => {
const ctxAddKeyword = () => {
const ref = generateRef();
/**
* Se guarda en db
*/
return { ref, keyword: message }
};
const ctx = ctxAddKeyword();
return {
ctx,
ref: ctx.ref,
addAnswer: addAnswer$2(ctx),
}
};
var addKeyword_1 = { addKeyword: addKeyword$2 };
const { addAnswer: addAnswer$1 } = addAnswer_1;
const { addKeyword: addKeyword$1 } = addKeyword_1;
var methods = { addAnswer: addAnswer$1, addKeyword: addKeyword$1 };
const { addKeyword, addAnswer } = methods;
var io = { addKeyword, addAnswer };
module.exports = io;

39
package-lock.json generated
View File

@@ -1247,6 +1247,12 @@
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="
},
"dequal": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
"integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
"dev": true
},
"destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
@@ -1266,6 +1272,12 @@
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.981744.tgz",
"integrity": "sha512-0cuGS8+jhR67Fy7qG3i3Pc7Aw494sb9yG9QgpG97SFVWwolgYjlhJg7n+UaHxOQT30d1TYu/EYe9k01ivLErIg=="
},
"diff": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/diff/-/diff-5.1.0.tgz",
"integrity": "sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw==",
"dev": true
},
"doctrine": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",
@@ -3000,6 +3012,12 @@
"resolved": "https://registry.npmjs.org/moment/-/moment-2.29.4.tgz",
"integrity": "sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w=="
},
"mri": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
"integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==",
"dev": true
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
@@ -4012,6 +4030,15 @@
"integrity": "sha512-Arc4hUN896vjkqCYrUXquBFtRZdv1PfLbTYP71efP6butxyQ0kWpiNJyAgsxscmQg1cqvHY32/UCBzXedTpU2g==",
"dev": true
},
"sade": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz",
"integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==",
"dev": true,
"requires": {
"mri": "^1.1.0"
}
},
"safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@@ -4601,6 +4628,18 @@
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
},
"uvu": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/uvu/-/uvu-0.5.6.tgz",
"integrity": "sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA==",
"dev": true,
"requires": {
"dequal": "^2.0.0",
"diff": "^5.0.0",
"kleur": "^4.0.3",
"sade": "^1.7.3"
}
},
"vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",

View File

@@ -4,9 +4,9 @@
"description": "Bot de wahtsapp open source para MVP o pequeños negocios",
"main": "app.js",
"scripts": {
"start": "node ./app.js",
"cli": "node ./packages/cli/bin/cli.js",
"preinstall": ""
"cli:rollup": "rollup ./packages/cli/index.js --config ./packages/cli/rollup-cli.config.js",
"io:rollup": "rollup ./packages/io/index.js --config ./packages/io/rollup-cli.config.js"
},
"workspaces": [
"packages/cli",
@@ -64,7 +64,8 @@
"prettier": "^2.7.1",
"prompts": "^2.4.2",
"rimraf": "^3.0.2",
"rollup": "^3.2.3"
"rollup": "^3.2.3",
"uvu": "^0.5.6"
},
"engines": {
"node": "16.x"

View File

@@ -3,7 +3,7 @@ const commonjs = require('@rollup/plugin-commonjs')
module.exports = {
input: 'index.js',
output: {
file: 'lib/bundle.cjs',
file: 'lib/cli/bundle.cjs',
format: 'cjs',
},
plugins: [commonjs()],

View File

@@ -8,8 +8,10 @@
> `sensitivy` false _default_
- [ ] addKeyword
- [ ] addAnswer
- [x] addKeyword
- [x] addAnswer
- [ ] addKeyword: Opciones
- [ ] addAnswer: Opciones
- [ ] Si ha contactado previamente. Seguir continuida
```js

View File

@@ -1,32 +1,32 @@
const { addKeyword, addAnswer } = require('./methods')
module.exports = { addKeyword, addAnswer }
// const test = async () => {
// const cxtA = addKeyword('hola')
// console.log({ cxtA: cxtA.ctx.keyword, ref: cxtA.ref })
// const cxtB = addAnswer(cxtA)('b')
// console.log({ cxtB: cxtB.ctx.message, ref: cxtB.ref })
// const cxtC = addAnswer(cxtB)('c')
// console.log({ cxtC: cxtC.ctx.keyword, ref: cxtC.ref })
// }
const test = async () => {
const cxtA = addKeyword('hola')
console.log({ cxtA: cxtA.ctx.keyword, ref: cxtA.ref })
const cxtB = addAnswer(cxtA)('b')
console.log({ cxtB: cxtB.ctx.message, ref: cxtB.ref })
const cxtC = addAnswer(cxtB)('c')
console.log({ cxtC: cxtC.ctx.keyword, ref: cxtC.ref })
}
// const test1 = async () => {
// const cxtAB = addKeyword('hola').addAnswer('b').addAnswer('c')
const test1 = async () => {
const cxtAB = addKeyword('hola').addAnswer('b').addAnswer('c')
// console.log({
// keyword: cxtAB.ctx.keyword,
// anwser: cxtAB.ctx.message,
// })
// }
console.log({
keyword: cxtAB.ctx.keyword,
anwser: cxtAB.ctx.message,
})
}
// const test2 = async () => {
// const cxtABB = addKeyword('hola')
// .addAnswer('Bienvenido a tu tienda 🥲')
// .addAnswer('escribe *catalogo* o *ofertas*')
const test2 = async () => {
const cxtABB = addKeyword('hola')
.addAnswer('Bienvenido a tu tienda 🥲')
.addAnswer('escribe *catalogo* o *ofertas*')
// console.log({
// pregunta: cxtABB.ctx.keyword,
// ultimasrespuesta: cxtABB.ctx.message,
// })
// }
console.log({
pregunta: cxtABB.ctx.keyword,
ultimasrespuesta: cxtABB.ctx.message,
})
}
test2().then()
// test2().then()

View File

@@ -6,7 +6,7 @@
"private": true,
"scripts": {
"io:dev": "node ./index.js",
"io:rollup": "rollup index.js --config ./rollup-cli.config.js",
"io:rollup": "node ../../node_modules/.bin/rollup index.js --config ./rollup-cli.config.js",
"format:check": "prettier --check .",
"format:write": "prettier --write .",
"lint:check": "eslint .",

View File

@@ -0,0 +1,10 @@
const commonjs = require('@rollup/plugin-commonjs')
module.exports = {
input: 'index.js',
output: {
file: 'lib/io/bundle.cjs',
format: 'cjs',
},
plugins: [commonjs()],
}

View File

@@ -0,0 +1,12 @@
const { test, suite } = require('uvu')
const { snapshot } = require('uvu/assert')
const botTest = suite('bot-function')
test(``, async () => {
})
botTest.run()