melperjs 3.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["xss","camelCase","capitalize","isEmpty","setCookieParser","CONSTANTS","LOWER_CASE","UPPER_CASE","HEXADECIMAL","NUMBERS","Exception","message","response","name","status","pascalCase","time","Math","floor","Date","now","sleepMs","milliseconds","Promise","resolve","setTimeout","sleep","seconds","promiseTimeout","promise","reject","timer","Error","then","value","clearTimeout","catch","reason","splitLines","text","split","filter","item","checkEmpty","map","trim","findKeyNode","key","node","pair","hasOwnProperty","index","result","str","upperCaseFirst","toUpperCase","slice","lowerCaseFirst","toLowerCase","titleString","word","join","limitString","limit","length","substring","safeString","whiteList","stripIgnoreTag","stripIgnoreTagBody","randomString","useNumbers","useUppercase","characters","i","randomIndex","random","randomHex","randomUuid","useDashes","d","uuid","replace","c","r","toString","replaceAll","randomWeighted","dict","randomFunc","totalWeight","elements","Object","keys","weights","values","reduce","sum","weight","randomNum","weightSum","cookieDict","res","decodeValues","cookies","parse","cookie","cookieHeader","entries","isIntlHttpCode","httpCode","undefined","isIntlError","e","includes"],"sources":["../src/index.js"],"sourcesContent":["import xss from \"xss\";\r\nimport camelCase from \"lodash/camelCase.js\";\r\nimport capitalize from \"lodash/capitalize.js\";\r\nimport isEmpty from \"lodash/isEmpty.js\";\r\nimport setCookieParser from \"set-cookie-parser\";\r\n\r\n\r\nexport const CONSTANTS = {\r\n LOWER_CASE: \"abcdefghijklmnopqrstuvwxyz\",\r\n UPPER_CASE: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\r\n HEXADECIMAL: \"0123456789abcdef\",\r\n NUMBERS: \"0123456789\",\r\n};\r\n\r\nexport function Exception(message, response = {}, name = null) {\r\n response.status = response.status || 400;\r\n return {\r\n name: pascalCase(name),\r\n message,\r\n response,\r\n }\r\n}\r\n\r\nexport function time() {\r\n return Math.floor(Date.now() / 1000);\r\n}\r\n\r\nexport async function sleepMs(milliseconds) {\r\n return new Promise(resolve => setTimeout(resolve, milliseconds));\r\n}\r\n\r\nexport async function sleep(seconds) {\r\n return await sleepMs(seconds * 1000);\r\n}\r\n\r\nexport function promiseTimeout(milliseconds, promise) {\r\n return new Promise((resolve, reject) => {\r\n const timer = setTimeout(() => {\r\n reject(new Error('Promise timed out after ' + milliseconds + 'ms'));\r\n }, milliseconds);\r\n\r\n promise\r\n .then(value => {\r\n clearTimeout(timer);\r\n resolve(value);\r\n })\r\n .catch(reason => {\r\n clearTimeout(timer);\r\n reject(reason);\r\n });\r\n });\r\n}\r\n\r\nexport function splitLines(text) {\r\n return text.split(/\\r?\\n/).filter(item => !checkEmpty(item)).map(item => item.trim());\r\n}\r\n\r\nexport function findKeyNode(key, node, pair = null) {\r\n if (node && node.hasOwnProperty(key) && (pair ? node[key] === pair : true)) {\r\n return node;\r\n } else if (typeof node === 'object') {\r\n for (let index in node) {\r\n const result = findKeyNode(key, node[index], pair);\r\n if (result) {\r\n return result;\r\n }\r\n }\r\n }\r\n return null;\r\n}\r\n\r\nexport function checkEmpty(value) {\r\n if (typeof value === \"number\") {\r\n return value === 0;\r\n } else {\r\n return isEmpty(value);\r\n }\r\n}\r\n\r\nexport function pascalCase(str) {\r\n return upperCaseFirst(camelCase(str));\r\n}\r\n\r\nexport function upperCaseFirst(str) {\r\n str = str || \"\";\r\n return str[0].toUpperCase() + str.slice(1);\r\n}\r\n\r\nexport function lowerCaseFirst(str) {\r\n str = str || \"\";\r\n return str[0].toLowerCase() + str.slice(1);\r\n}\r\n\r\nexport function titleString(str) {\r\n str = str || \"\";\r\n return str\r\n .split(' ')\r\n .map(word => capitalize(word))\r\n .join(' ');\r\n}\r\n\r\nexport function limitString(str, limit = 35) {\r\n str = str || \"\";\r\n if (str.length <= limit) {\r\n return str;\r\n } else {\r\n return str.substring(0, limit - 3) + \"...\";\r\n }\r\n}\r\n\r\nexport function safeString(str) {\r\n str = str || \"\";\r\n return xss(str, {\r\n whiteList: {},\r\n stripIgnoreTag: true,\r\n stripIgnoreTagBody: [\"script\"]\r\n });\r\n}\r\n\r\nexport function randomString(length, useNumbers = true, useUppercase = false) {\r\n\r\n let characters = CONSTANTS.LOWER_CASE;\r\n if (useUppercase) characters += CONSTANTS.UPPER_CASE;\r\n if (useNumbers) characters += CONSTANTS.NUMBERS;\r\n\r\n let randomString = '';\r\n for (let i = 0; i < length; i++) {\r\n const randomIndex = Math.floor(Math.random() * characters.length);\r\n randomString += characters[randomIndex];\r\n }\r\n\r\n return randomString;\r\n}\r\n\r\nexport function randomHex(length) {\r\n let result = '';\r\n for (let i = 0; i < length; i++) {\r\n const randomIndex = Math.floor(Math.random() * CONSTANTS.HEXADECIMAL.length);\r\n result += CONSTANTS.HEXADECIMAL[randomIndex];\r\n }\r\n\r\n return result;\r\n}\r\n\r\nexport function randomUuid(useDashes = true) {\r\n let d = Date.now();\r\n const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\r\n const r = (d + Math.random() * 16) % 16 | 0;\r\n d = Math.floor(d / 16);\r\n return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);\r\n });\r\n return useDashes ? uuid : uuid.replaceAll(\"-\", \"\");\r\n}\r\n\r\nexport function randomWeighted(dict, randomFunc = (totalWeight) => Math.random() * totalWeight) {\r\n let elements = Object.keys(dict);\r\n let weights = Object.values(dict);\r\n\r\n let totalWeight = weights.reduce((sum, weight) => sum + weight, 0);\r\n\r\n let randomNum = randomFunc(totalWeight);\r\n let weightSum = 0;\r\n\r\n for (let i = 0; i < elements.length; i++) {\r\n weightSum += weights[i];\r\n if (randomNum <= weightSum) {\r\n return elements[i];\r\n }\r\n }\r\n}\r\n\r\nexport function cookieDict(res, decodeValues = false) {\r\n let dict = {};\r\n const cookies = setCookieParser.parse(res, {decodeValues: decodeValues});\r\n for (let cookie of cookies) {\r\n dict[cookie.name] = cookie.value;\r\n }\r\n return dict;\r\n}\r\n\r\nexport function cookieHeader(cookieDict) {\r\n return Object.entries(cookieDict)\r\n .map(([key, value]) => `${key}=${value}`)\r\n .join(';')\r\n}\r\n\r\nexport function isIntlHttpCode(httpCode) {\r\n return (\r\n httpCode === undefined ||\r\n httpCode === null ||\r\n httpCode === 0 ||\r\n httpCode === 402 ||\r\n httpCode === 407 ||\r\n httpCode === 466 ||\r\n 500 <= httpCode\r\n );\r\n}\r\n\r\nexport function isIntlError(e) {\r\n return (\r\n e?.message?.toLowerCase?.()?.includes?.(\"timeout\") ||\r\n e?.message?.toLowerCase?.()?.includes?.(\"aborted\") ||\r\n e?.message?.toLowerCase?.()?.includes?.(\"tls connection\") ||\r\n e?.message?.toLowerCase?.()?.includes?.(\"socket hang\") ||\r\n isIntlHttpCode(e?.response?.status)\r\n )\r\n}"],"mappings":"AAAA,OAAOA,GAAG,MAAM,KAAK;AACrB,OAAOC,SAAS,MAAM,qBAAqB;AAC3C,OAAOC,UAAU,MAAM,sBAAsB;AAC7C,OAAOC,OAAO,MAAM,mBAAmB;AACvC,OAAOC,eAAe,MAAM,mBAAmB;AAG/C,OAAO,MAAMC,SAAS,GAAG;EACrBC,UAAU,EAAE,4BAA4B;EACxCC,UAAU,EAAE,4BAA4B;EACxCC,WAAW,EAAE,kBAAkB;EAC/BC,OAAO,EAAE;AACb,CAAC;AAED,OAAO,SAASC,SAASA,CAACC,OAAO,EAAEC,QAAQ,GAAG,CAAC,CAAC,EAAEC,IAAI,GAAG,IAAI,EAAE;EAC3DD,QAAQ,CAACE,MAAM,GAAGF,QAAQ,CAACE,MAAM,IAAI,GAAG;EACxC,OAAO;IACHD,IAAI,EAAEE,UAAU,CAACF,IAAI,CAAC;IACtBF,OAAO;IACPC;EACJ,CAAC;AACL;AAEA,OAAO,SAASI,IAAIA,CAAA,EAAG;EACnB,OAAOC,IAAI,CAACC,KAAK,CAACC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC;AACxC;AAE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C3B,OACIA,CAAC,EAAEtG,OAAO,EAAE+C,WAAW,GAAG,CAAC,EAAEwD,QAAQ,GAAG,SAAS,CAAC,IAClDD,CAAC,EAAEtG,OAAO,EAAE+C,WAAW,GAAG,CAAC,EAAEwD,QAAQ,GAAG,SAAS,CAAC,IAClDD,CAAC,EAAEtG,OAAO,EAAE+C,WAAW,GAAG,CAAC,EAAEwD,QAAQ,GAAG,gBAAgB,CAAC,IACzDD,CAAC,EAAEtG,OAAO,EAAE+C,WAAW,GAAG,CAAC,EAAEwD,QAAQ,GAAG,aAAa,CAAC,IACtDL,cAAc,CAACI,CAAC,EAAErG,QAAQ,EAAEE,MAAM,CAAC;AAE3C"}
package/mjs/node.js ADDED
@@ -0,0 +1,176 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import crypto from "crypto";
4
+ import { networkInterfaces } from "os";
5
+ import { execSync } from "child_process";
6
+ import bcrypt from "bcrypt";
7
+ import axios from "axios";
8
+ import { HttpsProxyAgent } from "hpagent";
9
+ import { CONSTANTS, randomWeighted, sleep } from "./index.js";
10
+ export function tokenString(length, useNumbers = true, useUppercase = false) {
11
+ const lowercaseChars = CONSTANTS.LOWER_CASE;
12
+ const uppercaseChars = CONSTANTS.UPPER_CASE;
13
+ const numbers = CONSTANTS.NUMBERS;
14
+ let characters = lowercaseChars;
15
+ if (useUppercase) characters += uppercaseChars;
16
+ if (useNumbers) characters += numbers;
17
+ let randomString = '';
18
+ while (randomString.length < length) {
19
+ const byte = crypto.randomBytes(1)[0];
20
+ const index = byte % characters.length;
21
+ if (byte < 256 - 256 % characters.length) {
22
+ randomString += characters[index];
23
+ }
24
+ }
25
+ return randomString;
26
+ }
27
+ export function tokenHex(length) {
28
+ return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
29
+ }
30
+ export function tokenUuid(useDashes = true) {
31
+ const uuid = crypto.randomUUID().toString();
32
+ return useDashes ? uuid : uuid.replaceAll("-", "");
33
+ }
34
+ export function tokenWeighted(dict) {
35
+ return randomWeighted(dict, crypto.randomInt);
36
+ }
37
+ export function serverIp() {
38
+ const interfaces = networkInterfaces();
39
+ for (const devName in interfaces) {
40
+ const interfaceValue = interfaces[devName];
41
+ for (let i = 0; i < interfaceValue.length; i++) {
42
+ const alias = interfaceValue[i];
43
+ if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.address.startsWith("192.168.") && !alias.internal) return alias.address;
44
+ }
45
+ }
46
+ return '127.0.0.1';
47
+ }
48
+ export function getVersion() {
49
+ try {
50
+ const date = new Date(execSync('git show -s --format=%ci HEAD').toString().trim());
51
+ const formatDatePart = value => value.toString().padStart(2, '0');
52
+ const year = date.getFullYear().toString().slice(-2);
53
+ const month = formatDatePart(date.getMonth() + 1);
54
+ const day = formatDatePart(date.getDate());
55
+ const hour = formatDatePart(date.getHours());
56
+ const minute = formatDatePart(date.getMinutes());
57
+ return parseFloat(`${year}${month}.${day}${hour}${minute}`);
58
+ } catch {
59
+ return 1.0;
60
+ }
61
+ }
62
+ export function createNumDir(mainDirectory) {
63
+ fs.mkdirSync(mainDirectory, {
64
+ recursive: true
65
+ });
66
+ for (let i = 0; i <= 9; i++) {
67
+ try {
68
+ fs.mkdirSync(path.join(mainDirectory, i.toString()));
69
+ } catch (e) {
70
+ console.error(`createNumDir:${i}`, e.message);
71
+ }
72
+ }
73
+ }
74
+ export function md5(data) {
75
+ return crypto.createHash('md5').update(data).digest("hex");
76
+ }
77
+ export function hashBcrypt(plainText) {
78
+ return bcrypt.hashSync(plainText, bcrypt.genSaltSync(10));
79
+ }
80
+ export function verifyBcrypt(plainText, hash) {
81
+ return bcrypt.compareSync(plainText, hash);
82
+ }
83
+ export function formatProxy(proxy, protocol = "http") {
84
+ proxy = proxy.trim();
85
+ const splitByProtocol = proxy.split("://");
86
+ if (1 < splitByProtocol.length) protocol = splitByProtocol[0];
87
+ proxy = splitByProtocol[splitByProtocol.length - 1];
88
+ if (!proxy.includes("@")) {
89
+ const proxyParts = proxy.split(":");
90
+ if (4 <= proxyParts.length) {
91
+ proxy = `${proxyParts[proxyParts.length - 2]}:${proxyParts[proxyParts.length - 1]}@`;
92
+ proxyParts.pop();
93
+ proxyParts.pop();
94
+ proxy += proxyParts.join(":");
95
+ }
96
+ }
97
+ const proxyParts = proxy.split(':');
98
+ const proxyEnd = parseInt(proxyParts[proxyParts.length - 1]);
99
+ const proxyStart = proxyParts[proxyParts.length - 2];
100
+ if (!proxyStart.includes(".")) {
101
+ proxyParts.pop();
102
+ proxyParts[proxyParts.length - 1] = crypto.randomInt(parseInt(proxyStart), proxyEnd + 1).toString();
103
+ }
104
+ return protocol + "://" + proxyParts.join(':');
105
+ }
106
+ export function proxyObject(...args) {
107
+ let proxy = formatProxy(...args);
108
+ const splitByProtocol = proxy.split('://');
109
+ const splitById = splitByProtocol[splitByProtocol.length - 1].split('@');
110
+ const splitByConn = splitById[splitById.length - 1].split(':');
111
+ proxy = {
112
+ protocol: splitByProtocol[0],
113
+ host: splitByConn[0],
114
+ port: parseInt(splitByConn[1])
115
+ };
116
+ if (1 < splitById.length) {
117
+ const splitByAuth = splitById[0].split(':');
118
+ proxy.auth = {
119
+ username: splitByAuth[0],
120
+ password: splitByAuth[1]
121
+ };
122
+ }
123
+ return proxy;
124
+ }
125
+ export async function proxify(proxyConfig, callback = formatProxy) {
126
+ proxyConfig = proxyConfig || {};
127
+ const timeout = 7000;
128
+ if (proxyConfig.mode === 1) {
129
+ return callback(proxyConfig.proxy);
130
+ } else if (proxyConfig.mode === 2) {
131
+ const proxy = callback(proxyConfig.proxy);
132
+ try {
133
+ await axios.get(proxyConfig.resetApi, {
134
+ timeout
135
+ });
136
+ } catch {
137
+ return false;
138
+ }
139
+ await sleep(5);
140
+ for (let i = 0; i < 5; i++) {
141
+ try {
142
+ const res = await axios.get("https://api64.ipify.org", {
143
+ timeout,
144
+ httpsAgent: new HttpsProxyAgent({
145
+ proxy,
146
+ timeout: 7000
147
+ })
148
+ });
149
+ if (res.status === 200) return proxy;
150
+ } catch {
151
+ await sleep(3);
152
+ }
153
+ }
154
+ } else if (proxyConfig.mode === 3) {
155
+ try {
156
+ const res = await axios.get(proxyConfig.resetApi, {
157
+ timeout
158
+ });
159
+ if (res.status === 200) return callback(proxyConfig.proxy);
160
+ } catch {
161
+ return false;
162
+ }
163
+ } else if (proxyConfig.mode === 4) {
164
+ return callback(proxyConfig.proxy).replace("{SESSION}", tokenHex(8));
165
+ } else if (proxyConfig.mode === 5) {
166
+ try {
167
+ const lines = proxyConfig.proxy.split("\n");
168
+ const line = lines[crypto.randomInt(0, lines.length)];
169
+ return callback(line);
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
174
+ return null;
175
+ }
176
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","names":["fs","path","crypto","networkInterfaces","execSync","bcrypt","axios","HttpsProxyAgent","CONSTANTS","randomWeighted","sleep","tokenString","length","useNumbers","useUppercase","lowercaseChars","LOWER_CASE","uppercaseChars","UPPER_CASE","numbers","NUMBERS","characters","randomString","byte","randomBytes","index","tokenHex","Math","ceil","toString","slice","tokenUuid","useDashes","uuid","randomUUID","replaceAll","tokenWeighted","dict","randomInt","serverIp","interfaces","devName","interfaceValue","i","alias","family","address","startsWith","internal","getVersion","date","Date","trim","formatDatePart","value","padStart","year","getFullYear","month","getMonth","day","getDate","hour","getHours","minute","getMinutes","parseFloat","createNumDir","mainDirectory","mkdirSync","recursive","join","e","console","error","message","md5","data","createHash","update","digest","hashBcrypt","plainText","hashSync","genSaltSync","verifyBcrypt","hash","compareSync","formatProxy","proxy","protocol","splitByProtocol","split","includes","proxyParts","pop","proxyEnd","parseInt","proxyStart","proxyObject","args","splitById","splitByConn","host","port","splitByAuth","auth","username","password","proxify","proxyConfig","callback","timeout","mode","get","resetApi","res","httpsAgent","status","replace","lines","line"],"sources":["../src/node.js"],"sourcesContent":["import fs from \"fs\";\r\nimport path from \"path\";\r\nimport crypto from \"crypto\";\r\nimport {networkInterfaces} from \"os\";\r\nimport {execSync} from \"child_process\";\r\n\r\nimport bcrypt from \"bcrypt\";\r\nimport axios from \"axios\";\r\nimport {HttpsProxyAgent} from \"hpagent\";\r\n\r\nimport {CONSTANTS, randomWeighted, sleep} from \"./index.js\";\r\n\r\n\r\nexport function tokenString(length, useNumbers = true, useUppercase = false) {\r\n const lowercaseChars = CONSTANTS.LOWER_CASE;\r\n const uppercaseChars = CONSTANTS.UPPER_CASE;\r\n const numbers = CONSTANTS.NUMBERS;\r\n\r\n let characters = lowercaseChars;\r\n if (useUppercase) characters += uppercaseChars;\r\n if (useNumbers) characters += numbers;\r\n\r\n let randomString = '';\r\n while (randomString.length < length) {\r\n const byte = crypto.randomBytes(1)[0];\r\n const index = byte % characters.length;\r\n if (byte < (256 - (256 % characters.length))) {\r\n randomString += characters[index];\r\n }\r\n }\r\n\r\n return randomString;\r\n}\r\n\r\nexport function tokenHex(length) {\r\n return crypto\r\n .randomBytes(Math.ceil(length / 2))\r\n .toString('hex')\r\n .slice(0, length);\r\n}\r\n\r\nexport function tokenUuid(useDashes = true) {\r\n const uuid = crypto.randomUUID().toString();\r\n return useDashes ? uuid : uuid.replaceAll(\"-\", \"\")\r\n}\r\n\r\nexport function tokenWeighted(dict) {\r\n return randomWeighted(dict, crypto.randomInt);\r\n}\r\n\r\nexport function serverIp() {\r\n const interfaces = networkInterfaces();\r\n for (const devName in interfaces) {\r\n const interfaceValue = interfaces[devName];\r\n for (let i = 0; i < interfaceValue.length; i++) {\r\n const alias = interfaceValue[i];\r\n if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.address.startsWith(\"192.168.\") && !alias.internal)\r\n return alias.address;\r\n }\r\n }\r\n return '127.0.0.1';\r\n}\r\n\r\nexport function getVersion() {\r\n try {\r\n const date = new Date(execSync('git show -s --format=%ci HEAD').toString().trim());\r\n const formatDatePart = (value) => value.toString().padStart(2, '0');\r\n const year = date.getFullYear().toString().slice(-2);\r\n const month = formatDatePart(date.getMonth() + 1);\r\n const day = formatDatePart(date.getDate());\r\n const hour = formatDatePart(date.getHours());\r\n const minute = formatDatePart(date.getMinutes());\r\n return parseFloat(`${year}${month}.${day}${hour}${minute}`);\r\n } catch {\r\n return 1.0;\r\n }\r\n}\r\n\r\nexport function createNumDir(mainDirectory) {\r\n fs.mkdirSync(mainDirectory, {recursive: true});\r\n for (let i = 0; i <= 9; i++) {\r\n try {\r\n fs.mkdirSync(path.join(mainDirectory, i.toString()));\r\n } catch (e) {\r\n console.error(`createNumDir:${i}`, e.message);\r\n }\r\n }\r\n}\r\n\r\nexport function md5(data) {\r\n return crypto.createHash('md5').update(data).digest(\"hex\");\r\n}\r\n\r\nexport function hashBcrypt(plainText) {\r\n return bcrypt.hashSync(plainText, bcrypt.genSaltSync(10));\r\n}\r\n\r\nexport function verifyBcrypt(plainText, hash) {\r\n return bcrypt.compareSync(plainText, hash);\r\n}\r\n\r\nexport function formatProxy(proxy, protocol = \"http\") {\r\n proxy = proxy.trim();\r\n const splitByProtocol = proxy.split(\"://\");\r\n if (1 < splitByProtocol.length)\r\n protocol = splitByProtocol[0];\r\n proxy = splitByProtocol[splitByProtocol.length - 1];\r\n if (!proxy.includes(\"@\")) {\r\n const proxyParts = proxy.split(\":\");\r\n if (4 <= proxyParts.length) {\r\n proxy = `${proxyParts[proxyParts.length - 2]}:${proxyParts[proxyParts.length - 1]}@`;\r\n proxyParts.pop();\r\n proxyParts.pop();\r\n proxy += proxyParts.join(\":\");\r\n }\r\n }\r\n const proxyParts = proxy.split(':');\r\n const proxyEnd = parseInt(proxyParts[proxyParts.length - 1]);\r\n const proxyStart = proxyParts[proxyParts.length - 2];\r\n if (!proxyStart.includes(\".\")) {\r\n proxyParts.pop();\r\n proxyParts[proxyParts.length - 1] = crypto.randomInt(parseInt(proxyStart), proxyEnd + 1).toString();\r\n }\r\n return protocol + \"://\" + proxyParts.join(':');\r\n}\r\n\r\nexport function proxyObject(...args) {\r\n let proxy = formatProxy(...args);\r\n const splitByProtocol = proxy.split('://');\r\n const splitById = splitByProtocol[splitByProtocol.length - 1].split('@');\r\n const splitByConn = splitById[splitById.length - 1].split(':');\r\n proxy = {\r\n protocol: splitByProtocol[0],\r\n host: splitByConn[0],\r\n port: parseInt(splitByConn[1]),\r\n };\r\n if (1 < splitById.length) {\r\n const splitByAuth = splitById[0].split(':');\r\n proxy.auth = {\r\n username: splitByAuth[0],\r\n password: splitByAuth[1]\r\n };\r\n }\r\n return proxy;\r\n}\r\n\r\nexport async function proxify(proxyConfig, callback = formatProxy) {\r\n proxyConfig = proxyConfig || {};\r\n const timeout = 7000;\r\n if (proxyConfig.mode === 1) {\r\n return callback(proxyConfig.proxy);\r\n } else if (proxyConfig.mode === 2) {\r\n const proxy = callback(proxyConfig.proxy);\r\n try {\r\n await axios.get(proxyConfig.resetApi, {timeout});\r\n } catch {\r\n return false;\r\n }\r\n await sleep(5);\r\n for (let i = 0; i < 5; i++) {\r\n try {\r\n const res = await axios.get(\"https://api64.ipify.org\", {\r\n timeout,\r\n httpsAgent: new HttpsProxyAgent({proxy, timeout: 7000})\r\n });\r\n if (res.status === 200)\r\n return proxy;\r\n } catch {\r\n await sleep(3);\r\n }\r\n }\r\n } else if (proxyConfig.mode === 3) {\r\n try {\r\n const res = await axios.get(proxyConfig.resetApi, {timeout});\r\n if (res.status === 200)\r\n return callback(proxyConfig.proxy);\r\n } catch {\r\n return false;\r\n }\r\n } else if (proxyConfig.mode === 4) {\r\n return callback(proxyConfig.proxy).replace(\"{SESSION}\", tokenHex(8));\r\n } else if (proxyConfig.mode === 5) {\r\n try {\r\n const lines = proxyConfig.proxy.split(\"\\n\");\r\n const line = lines[crypto.randomInt(0, lines.length)];\r\n return callback(line);\r\n } catch {\r\n return false;\r\n }\r\n }\r\n\r\n return null;\r\n}"],"mappings":"AAAA,OAAOA,EAAE,MAAM,IAAI;AACnB,OAAOC,IAAI,MAAM,MAAM;AACvB,OAAOC,MAAM,MAAM,QAAQ;AAC3B,SAAQC,iBAAiB,QAAO,IAAI;AACpC,S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AAM,KAAK,GAAG,EAClB,OAAOP,QAAQ,CAACD,WAAW,CAACrB,KAAK,CAAC;IAC1C,CAAC,CAAC,MAAM;MACJ,OAAO,KAAK;IAChB;EACJ,CAAC,MAAM,IAAIqB,WAAW,CAACG,IAAI,KAAK,CAAC,EAAE;IAC/B,OAAOF,QAAQ,CAACD,WAAW,CAACrB,KAAK,CAAC,CAAC8B,OAAO,CAAC,WAAW,EAAE7F,QAAQ,CAAC,CAAC,CAAC,CAAC;EACxE,CAAC,MAAM,IAAIoF,WAAW,CAACG,IAAI,KAAK,CAAC,EAAE;IAC/B,IAAI;MACA,MAAMO,KAAK,GAAGV,WAAW,CAACrB,KAAK,CAACG,KAAK,CAAC,IAAI,CAAC;MAC3C,MAAM6B,IAAI,GAAGD,KAAK,CAACtH,MAAM,CAACoC,SAAS,CAAC,CAAC,EAAEkF,KAAK,CAAC5G,MAAM,CAAC,CAAC;MACrD,OAAOmG,QAAQ,CAACU,IAAI,CAAC;IACzB,CAAC,CAAC,MAAM;MACJ,OAAO,KAAK;IAChB;EACJ;EAEA,OAAO,IAAI;AACf"}
package/package.json CHANGED
@@ -1,43 +1,51 @@
1
- {
2
- "name": "melperjs",
3
- "version": "3.0.0",
4
- "description": "Nodejs module to use predefined common functions and utilities",
5
- "keywords": [
6
- "helper",
7
- "mixins",
8
- "lodash",
9
- "common functions",
10
- "javascript helper"
11
- ],
12
- "repository": {
13
- "type": "git",
14
- "url": "https://github.com/mahelbir/melperjs.git"
15
- },
16
- "author": "Mahmuthan Elbir",
17
- "license": "MIT",
18
- "exports": {
19
- ".": "./lib/index.js",
20
- "./node": "./lib/node.js"
21
- },
22
- "scripts": {
23
- "build": "babel src --out-dir lib",
24
- "test": "node test/script.js"
25
- },
26
- "dependencies": {
27
- "axios": "^1.6.2",
28
- "bcrypt": "^5.1.1",
29
- "hpagent": "^1.2.0",
30
- "lodash": "^4.17.21",
31
- "set-cookie-parser": "^2.6.0",
32
- "xss": "^1.0.14"
33
- },
34
- "devDependencies": {
35
- "@babel/cli": "^7.23.4",
36
- "@babel/core": "^7.23.3",
37
- "@babel/preset-env": "^7.23.3",
38
- "babel-loader": "^9.1.3",
39
- "terser-webpack-plugin": "^5.3.9",
40
- "webpack": "^5.89.0",
41
- "webpack-cli": "^5.1.4"
42
- }
43
- }
1
+ {
2
+ "name": "melperjs",
3
+ "version": "5.0.0",
4
+ "description": "Javascript module to use predefined common functions and utilities",
5
+ "keywords": [
6
+ "helper",
7
+ "mixins",
8
+ "common functions",
9
+ "javascript helper",
10
+ "nodejs helper"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/mahelbir/melperjs.git"
15
+ },
16
+ "author": "Mahmuthan Elbir",
17
+ "license": "MIT",
18
+ "type": "module",
19
+ "exports": {
20
+ ".": {
21
+ "import": "./mjs/index.js",
22
+ "require": "./cjs/index.js"
23
+ },
24
+ "./node": {
25
+ "import": "./mjs/node.js",
26
+ "require": "./cjs/node.js"
27
+ }
28
+ },
29
+ "scripts": {
30
+ "build-node": "babel ./src --out-dir ./cjs",
31
+ "build-module": "cross-env BABEL_ENV=module babel ./src --out-dir ./mjs",
32
+ "build-browser": "cross-env BABEL_ENV=browser babel ./src --out-dir ./lib",
33
+ "build": "npm run build-node && npm run build-module && npm run build-browser",
34
+ "test": "node test/script.js"
35
+ },
36
+ "dependencies": {
37
+ "axios": "^1.6.2",
38
+ "bcrypt": "^5.1.1",
39
+ "hpagent": "^1.2.0",
40
+ "lodash": "^4.17.21",
41
+ "set-cookie-parser": "^2.6.0",
42
+ "xss": "^1.0.14"
43
+ },
44
+ "devDependencies": {
45
+ "@babel/cli": "^7.23.4",
46
+ "@babel/core": "^7.23.3",
47
+ "@babel/preset-env": "^7.23.3",
48
+ "babel-preset-env": "^1.7.0",
49
+ "cross-env": "^7.0.3"
50
+ }
51
+ }
package/src/index.js CHANGED
@@ -1,8 +1,17 @@
1
- import * as _ from "lodash";
2
1
  import xss from "xss";
3
- import bcrypt from "bcrypt";
2
+ import camelCase from "lodash/camelCase.js";
3
+ import capitalize from "lodash/capitalize.js";
4
+ import isEmpty from "lodash/isEmpty.js";
4
5
  import setCookieParser from "set-cookie-parser";
5
6
 
7
+
8
+ export const CONSTANTS = {
9
+ LOWER_CASE: "abcdefghijklmnopqrstuvwxyz",
10
+ UPPER_CASE: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
11
+ HEXADECIMAL: "0123456789abcdef",
12
+ NUMBERS: "0123456789",
13
+ };
14
+
6
15
  export function Exception(message, response = {}, name = null) {
7
16
  response.status = response.status || 400;
8
17
  return {
@@ -42,6 +51,10 @@ export function promiseTimeout(milliseconds, promise) {
42
51
  });
43
52
  }
44
53
 
54
+ export function splitLines(text) {
55
+ return text.split(/\r?\n/).map(item => item.trim()).filter(item => !isEmpty(item));
56
+ }
57
+
45
58
  export function findKeyNode(key, node, pair = null) {
46
59
  if (node && node.hasOwnProperty(key) && (pair ? node[key] === pair : true)) {
47
60
  return node;
@@ -60,29 +73,29 @@ export function checkEmpty(value) {
60
73
  if (typeof value === "number") {
61
74
  return value === 0;
62
75
  } else {
63
- return _.isEmpty(value);
76
+ return isEmpty(value);
64
77
  }
65
78
  }
66
79
 
67
- export function pascalCase(str){
68
- return upperCaseFirst(_.camelCase(str));
80
+ export function pascalCase(str) {
81
+ return upperCaseFirst(camelCase(str));
69
82
  }
70
83
 
71
84
  export function upperCaseFirst(str) {
72
85
  str = str || "";
73
- return _.upperCase(str[0]) + str.slice(1);
86
+ return str[0].toUpperCase() + str.slice(1);
74
87
  }
75
88
 
76
89
  export function lowerCaseFirst(str) {
77
90
  str = str || "";
78
- return _.lowerCase(str[0]) + str.slice(1);
91
+ return str[0].toLowerCase() + str.slice(1);
79
92
  }
80
93
 
81
94
  export function titleString(str) {
82
95
  str = str || "";
83
96
  return str
84
97
  .split(' ')
85
- .map(word => _.capitalize(word))
98
+ .map(word => capitalize(word))
86
99
  .join(' ');
87
100
  }
88
101
 
@@ -105,13 +118,10 @@ export function safeString(str) {
105
118
  }
106
119
 
107
120
  export function randomString(length, useNumbers = true, useUppercase = false) {
108
- const lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';
109
- const uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
110
- const numbers = '0123456789';
111
121
 
112
- let characters = lowercaseChars;
113
- if (useUppercase) characters += uppercaseChars;
114
- if (useNumbers) characters += numbers;
122
+ let characters = CONSTANTS.LOWER_CASE;
123
+ if (useUppercase) characters += CONSTANTS.UPPER_CASE;
124
+ if (useNumbers) characters += CONSTANTS.NUMBERS;
115
125
 
116
126
  let randomString = '';
117
127
  for (let i = 0; i < length; i++) {
@@ -124,11 +134,9 @@ export function randomString(length, useNumbers = true, useUppercase = false) {
124
134
 
125
135
  export function randomHex(length) {
126
136
  let result = '';
127
- const characters = '0123456789abcdef';
128
-
129
137
  for (let i = 0; i < length; i++) {
130
- const randomIndex = Math.floor(Math.random() * characters.length);
131
- result += characters[randomIndex];
138
+ const randomIndex = Math.floor(Math.random() * CONSTANTS.HEXADECIMAL.length);
139
+ result += CONSTANTS.HEXADECIMAL[randomIndex];
132
140
  }
133
141
 
134
142
  return result;
@@ -161,14 +169,6 @@ export function randomWeighted(dict, randomFunc = (totalWeight) => Math.random()
161
169
  }
162
170
  }
163
171
 
164
- export function hashBcrypt(plainText) {
165
- return bcrypt.hashSync(plainText, bcrypt.genSaltSync(10));
166
- }
167
-
168
- export function verifyBcrypt(plainText, hash) {
169
- return bcrypt.compareSync(plainText, hash);
170
- }
171
-
172
172
  export function cookieDict(res, decodeValues = false) {
173
173
  let dict = {};
174
174
  const cookies = setCookieParser.parse(res, {decodeValues: decodeValues});
@@ -184,7 +184,7 @@ export function cookieHeader(cookieDict) {
184
184
  .join(';')
185
185
  }
186
186
 
187
- export function foreignHttpError(httpCode) {
187
+ export function isIntlHttpCode(httpCode) {
188
188
  return (
189
189
  httpCode === undefined ||
190
190
  httpCode === null ||
@@ -194,4 +194,14 @@ export function foreignHttpError(httpCode) {
194
194
  httpCode === 466 ||
195
195
  500 <= httpCode
196
196
  );
197
+ }
198
+
199
+ export function isIntlError(e) {
200
+ return (
201
+ e?.message?.toLowerCase?.()?.includes?.("timeout") ||
202
+ e?.message?.toLowerCase?.()?.includes?.("aborted") ||
203
+ e?.message?.toLowerCase?.()?.includes?.("tls connection") ||
204
+ e?.message?.toLowerCase?.()?.includes?.("socket hang") ||
205
+ isIntlHttpCode(e?.response?.status)
206
+ )
197
207
  }
package/src/node.js CHANGED
@@ -4,16 +4,17 @@ import crypto from "crypto";
4
4
  import {networkInterfaces} from "os";
5
5
  import {execSync} from "child_process";
6
6
 
7
+ import bcrypt from "bcrypt";
7
8
  import axios from "axios";
8
9
  import {HttpsProxyAgent} from "hpagent";
9
10
 
10
- import {randomWeighted, sleep} from "./index.js";
11
+ import {CONSTANTS, randomWeighted, sleep} from "./index.js";
11
12
 
12
13
 
13
14
  export function tokenString(length, useNumbers = true, useUppercase = false) {
14
- const lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';
15
- const uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
16
- const numbers = '0123456789';
15
+ const lowercaseChars = CONSTANTS.LOWER_CASE;
16
+ const uppercaseChars = CONSTANTS.UPPER_CASE;
17
+ const numbers = CONSTANTS.NUMBERS;
17
18
 
18
19
  let characters = lowercaseChars;
19
20
  if (useUppercase) characters += uppercaseChars;
@@ -75,19 +76,11 @@ export function getVersion() {
75
76
  }
76
77
  }
77
78
 
78
- export function createDir(directory) {
79
- if (!fs.existsSync(directory)) {
80
- fs.mkdirSync(directory, {recursive: true});
81
- return true;
82
- }
83
- return false;
84
- }
85
-
86
79
  export function createNumDir(mainDirectory) {
87
- createDir(mainDirectory);
80
+ fs.mkdirSync(mainDirectory, {recursive: true});
88
81
  for (let i = 0; i <= 9; i++) {
89
82
  try {
90
- createDir(path.join(mainDirectory, i.toString()));
83
+ fs.mkdirSync(path.join(mainDirectory, i.toString()));
91
84
  } catch (e) {
92
85
  console.error(`createNumDir:${i}`, e.message);
93
86
  }
@@ -98,6 +91,14 @@ export function md5(data) {
98
91
  return crypto.createHash('md5').update(data).digest("hex");
99
92
  }
100
93
 
94
+ export function hashBcrypt(plainText) {
95
+ return bcrypt.hashSync(plainText, bcrypt.genSaltSync(10));
96
+ }
97
+
98
+ export function verifyBcrypt(plainText, hash) {
99
+ return bcrypt.compareSync(plainText, hash);
100
+ }
101
+
101
102
  export function formatProxy(proxy, protocol = "http") {
102
103
  proxy = proxy.trim();
103
104
  const splitByProtocol = proxy.split("://");
package/test/script.js CHANGED
@@ -1,10 +1,11 @@
1
- import * as helper from "../src/index.js"
2
- import * as nodeHelper from "../src/node.js"
3
1
  import axios from "axios"
2
+ import * as helper from "../src/index.js";
3
+ import * as nodeHelper from "../src/node.js";
4
4
 
5
5
 
6
6
  (async () => {
7
- console.log(helper.Exception("something went wrong", {status: 500}, "axios error"));
7
+ console.log(helper.CONSTANTS);
8
+ console.log(helper.Exception("something went wrong", {status: 400}, "bad request error"));
8
9
  console.log(helper.time());
9
10
  await helper.sleepMs(1000);
10
11
  console.log(helper.time());
@@ -14,7 +15,13 @@ import axios from "axios"
14
15
  await helper.promiseTimeout(1000, helper.sleepMs(2000));
15
16
  } catch (e) {
16
17
  console.error(e.message);
18
+ console.log("Timeout, Internal Error ?", helper.isIntlError(e));
17
19
  }
20
+ console.log(helper.splitLines(`
21
+ 2.satır
22
+
23
+ 4.satır
24
+ `))
18
25
  console.log(helper.findKeyNode("c", {
19
26
  a: {
20
27
  b: {
@@ -26,9 +33,11 @@ import axios from "axios"
26
33
  }
27
34
  }
28
35
  }));
29
- console.log("str empty", helper.checkEmpty(""));
30
- console.log("1 empty", helper.checkEmpty(1));
31
- console.log("[] empty", helper.checkEmpty([]));
36
+ console.log("'' empty ?", helper.checkEmpty(''));
37
+ console.log("1 empty ?", helper.checkEmpty(1));
38
+ console.log("0 empty ?", helper.checkEmpty(1));
39
+ console.log("[] empty ?", helper.checkEmpty([]));
40
+ console.log(helper.pascalCase("pascal case"));
32
41
  console.log(helper.upperCaseFirst("first letter upper"));
33
42
  console.log(helper.lowerCaseFirst("First Letter Lower"));
34
43
  console.log(helper.titleString("THIS mUsT be Title"));
@@ -43,9 +52,9 @@ import axios from "axios"
43
52
  console.log(nodeHelper.tokenUuid(true));
44
53
  console.log(nodeHelper.tokenWeighted({strongProbability: 1000, lowProbability: 1}));
45
54
  console.log(nodeHelper.md5("data"));
46
- const password = helper.hashBcrypt("plain");
55
+ const password = nodeHelper.hashBcrypt("plain");
47
56
  console.log(password)
48
- console.log("passwordHash", helper.verifyBcrypt("plain", password));
57
+ console.log("passwordHash verified ?", nodeHelper.verifyBcrypt("plain", password));
49
58
  const cookies = helper.cookieDict(await axios.get("https://google.com"));
50
59
  console.log(cookies);
51
60
  console.log(helper.cookieHeader(cookies));
@@ -54,9 +63,8 @@ import axios from "axios"
54
63
  console.log(nodeHelper.proxyObject(proxy));
55
64
  console.log(await nodeHelper.proxify({mode: 4, proxy}));
56
65
  console.log(nodeHelper.serverIp());
57
- console.log("HTTP CODE: 401 FOREIGN", helper.foreignHttpError(401));
58
- console.log("HTTP CODE: 407 FOREIGN (Failed Proxy Auth)", helper.foreignHttpError(407));
66
+ console.log("HTTP CODE: 400 (Bad Request) ?", helper.isIntlHttpCode(401));
67
+ console.log("HTTP CODE: 407 (Failed Proxy Auth) ?", helper.isIntlHttpCode(407));
59
68
  nodeHelper.createNumDir("test");
60
- nodeHelper.createDir("test");
61
69
  console.log("VERSIONED BY .GIT", "v" + nodeHelper.getVersion());
62
70
  })();