melperjs 3.0.0 → 4.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.
package/package.json CHANGED
@@ -1,43 +1,43 @@
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": "4.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
+ ],
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/mahelbir/melperjs.git"
14
+ },
15
+ "author": "Mahmuthan Elbir",
16
+ "license": "MIT",
17
+ "type": "module",
18
+ "exports": {
19
+ ".": {
20
+ "import": "./mjs/index.js",
21
+ "require": "./cjs/index.js"
22
+ }
23
+ },
24
+ "scripts": {
25
+ "build-module": "cross-env BABEL_ENV=module babel ./src --out-dir ./mjs",
26
+ "build-node": "babel ./src --out-dir ./cjs",
27
+ "build": "npm run build-module && npm run build-node",
28
+ "test": "node test/script.js"
29
+ },
30
+ "dependencies": {
31
+ "lodash": "^4.17.21",
32
+ "set-cookie-parser": "^2.6.0",
33
+ "xss": "^1.0.14"
34
+ },
35
+ "devDependencies": {
36
+ "@babel/cli": "^7.23.4",
37
+ "@babel/core": "^7.23.3",
38
+ "@babel/preset-env": "^7.23.3",
39
+ "babel-preset-env": "^1.7.0",
40
+ "cross-env": "^7.0.3",
41
+ "axios": "^1.6.2"
42
+ }
43
+ }
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/).filter(item => !checkEmpty(item)).map(item => item.trim());
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
-
112
- let characters = lowercaseChars;
113
- if (useUppercase) characters += uppercaseChars;
114
- if (useNumbers) characters += numbers;
121
+
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/test/script.js CHANGED
@@ -1,21 +1,36 @@
1
- import * as helper from "../src/index.js"
2
- import * as nodeHelper from "../src/node.js"
3
1
  import axios from "axios"
2
+ import {
3
+ checkEmpty, cookieDict, cookieHeader,
4
+ Exception,
5
+ findKeyNode, isIntlError, isIntlHttpCode, limitString, lowerCaseFirst,
6
+ promiseTimeout, randomHex, randomString, randomUuid, randomWeighted, safeString,
7
+ sleep,
8
+ sleepMs,
9
+ splitLines,
10
+ time, titleString,
11
+ upperCaseFirst
12
+ } from "../src/index.js";
4
13
 
5
14
 
6
15
  (async () => {
7
- console.log(helper.Exception("something went wrong", {status: 500}, "axios error"));
8
- console.log(helper.time());
9
- await helper.sleepMs(1000);
10
- console.log(helper.time());
11
- await helper.sleep(1);
12
- console.log(helper.time());
16
+ console.log(Exception("something went wrong", {status: 500}, "axios error"));
17
+ console.log(time());
18
+ await sleepMs(1000);
19
+ console.log(time());
20
+ await sleep(1);
21
+ console.log(time());
13
22
  try {
14
- await helper.promiseTimeout(1000, helper.sleepMs(2000));
23
+ await promiseTimeout(1000, sleepMs(2000));
15
24
  } catch (e) {
16
25
  console.error(e.message);
26
+ console.log("Internal Error", isIntlError(e));
17
27
  }
18
- console.log(helper.findKeyNode("c", {
28
+ console.log(splitLines(`1.satır
29
+
30
+ 3.satır
31
+ 4.satır
32
+ `))
33
+ console.log(findKeyNode("c", {
19
34
  a: {
20
35
  b: {
21
36
  x: 1,
@@ -26,37 +41,21 @@ import axios from "axios"
26
41
  }
27
42
  }
28
43
  }));
29
- console.log("str empty", helper.checkEmpty(""));
30
- console.log("1 empty", helper.checkEmpty(1));
31
- console.log("[] empty", helper.checkEmpty([]));
32
- console.log(helper.upperCaseFirst("first letter upper"));
33
- console.log(helper.lowerCaseFirst("First Letter Lower"));
34
- console.log(helper.titleString("THIS mUsT be Title"));
35
- console.log(helper.limitString("LONG TEXT", 7));
36
- console.log(helper.safeString("<strong>SAFE TEXT</strong>"));
37
- console.log(helper.randomString(32, true, true));
38
- console.log(helper.randomHex(8));
39
- console.log(helper.randomUuid(true));
40
- console.log(helper.randomWeighted({strongProbability: 1000, lowProbability: 1}));
41
- console.log(nodeHelper.tokenString(32, true, true));
42
- console.log(nodeHelper.tokenHex(8));
43
- console.log(nodeHelper.tokenUuid(true));
44
- console.log(nodeHelper.tokenWeighted({strongProbability: 1000, lowProbability: 1}));
45
- console.log(nodeHelper.md5("data"));
46
- const password = helper.hashBcrypt("plain");
47
- console.log(password)
48
- console.log("passwordHash", helper.verifyBcrypt("plain", password));
49
- const cookies = helper.cookieDict(await axios.get("https://google.com"));
44
+ console.log("str empty", checkEmpty(""));
45
+ console.log("1 empty", checkEmpty(1));
46
+ console.log("[] empty", checkEmpty([]));
47
+ console.log(upperCaseFirst("first letter upper"));
48
+ console.log(lowerCaseFirst("First Letter Lower"));
49
+ console.log(titleString("THIS mUsT be Title"));
50
+ console.log(limitString("LONG TEXT", 7));
51
+ console.log(safeString("<strong>SAFE TEXT</strong>"));
52
+ console.log(randomString(32, true, true));
53
+ console.log(randomHex(8));
54
+ console.log(randomUuid(true));
55
+ console.log(randomWeighted({strongProbability: 1000, lowProbability: 1}));
56
+ const cookies = cookieDict(await axios.get("https://google.com"));
50
57
  console.log(cookies);
51
- console.log(helper.cookieHeader(cookies));
52
- const proxy = nodeHelper.formatProxy("127.0.0.1:8080:id:pw-{SESSION}");
53
- console.log(proxy);
54
- console.log(nodeHelper.proxyObject(proxy));
55
- console.log(await nodeHelper.proxify({mode: 4, proxy}));
56
- 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));
59
- nodeHelper.createNumDir("test");
60
- nodeHelper.createDir("test");
61
- console.log("VERSIONED BY .GIT", "v" + nodeHelper.getVersion());
58
+ console.log(cookieHeader(cookies));
59
+ console.log("HTTP CODE: 400 (Bad Request)", isIntlHttpCode(400));
60
+ console.log("HTTP CODE: 407 (Failed Proxy Auth)", isIntlHttpCode(407));
62
61
  })();
package/lib/node.js DELETED
@@ -1,193 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.createDir = createDir;
7
- exports.createNumDir = createNumDir;
8
- exports.formatProxy = formatProxy;
9
- exports.getVersion = getVersion;
10
- exports.md5 = md5;
11
- exports.proxify = proxify;
12
- exports.proxyObject = proxyObject;
13
- exports.serverIp = serverIp;
14
- exports.tokenHex = tokenHex;
15
- exports.tokenString = tokenString;
16
- exports.tokenUuid = tokenUuid;
17
- exports.tokenWeighted = tokenWeighted;
18
- var _fs = _interopRequireDefault(require("fs"));
19
- var _path = _interopRequireDefault(require("path"));
20
- var _crypto = _interopRequireDefault(require("crypto"));
21
- var _os = require("os");
22
- var _child_process = require("child_process");
23
- var _axios = _interopRequireDefault(require("axios"));
24
- var _hpagent = require("hpagent");
25
- var _index = require("./index.js");
26
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
27
- function tokenString(length, useNumbers = true, useUppercase = false) {
28
- const lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';
29
- const uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
30
- const numbers = '0123456789';
31
- let characters = lowercaseChars;
32
- if (useUppercase) characters += uppercaseChars;
33
- if (useNumbers) characters += numbers;
34
- let randomString = '';
35
- while (randomString.length < length) {
36
- const byte = _crypto.default.randomBytes(1)[0];
37
- const index = byte % characters.length;
38
- if (byte < 256 - 256 % characters.length) {
39
- randomString += characters[index];
40
- }
41
- }
42
- return randomString;
43
- }
44
- function tokenHex(length) {
45
- return _crypto.default.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
46
- }
47
- function tokenUuid(useDashes = true) {
48
- const uuid = _crypto.default.randomUUID().toString();
49
- return useDashes ? uuid : uuid.replaceAll("-", "");
50
- }
51
- function tokenWeighted(dict) {
52
- return (0, _index.randomWeighted)(dict, _crypto.default.randomInt);
53
- }
54
- function serverIp() {
55
- const interfaces = (0, _os.networkInterfaces)();
56
- for (const devName in interfaces) {
57
- const interfaceValue = interfaces[devName];
58
- for (let i = 0; i < interfaceValue.length; i++) {
59
- const alias = interfaceValue[i];
60
- if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.address.startsWith("192.168.") && !alias.internal) return alias.address;
61
- }
62
- }
63
- return '127.0.0.1';
64
- }
65
- function getVersion() {
66
- try {
67
- const date = new Date((0, _child_process.execSync)('git show -s --format=%ci HEAD').toString().trim());
68
- const formatDatePart = value => value.toString().padStart(2, '0');
69
- const year = date.getFullYear().toString().slice(-2);
70
- const month = formatDatePart(date.getMonth() + 1);
71
- const day = formatDatePart(date.getDate());
72
- const hour = formatDatePart(date.getHours());
73
- const minute = formatDatePart(date.getMinutes());
74
- return parseFloat(`${year}${month}.${day}${hour}${minute}`);
75
- } catch {
76
- return 1.0;
77
- }
78
- }
79
- function createDir(directory) {
80
- if (!_fs.default.existsSync(directory)) {
81
- _fs.default.mkdirSync(directory, {
82
- recursive: true
83
- });
84
- return true;
85
- }
86
- return false;
87
- }
88
- function createNumDir(mainDirectory) {
89
- createDir(mainDirectory);
90
- for (let i = 0; i <= 9; i++) {
91
- try {
92
- createDir(_path.default.join(mainDirectory, i.toString()));
93
- } catch (e) {
94
- console.error(`createNumDir:${i}`, e.message);
95
- }
96
- }
97
- }
98
- function md5(data) {
99
- return _crypto.default.createHash('md5').update(data).digest("hex");
100
- }
101
- function formatProxy(proxy, protocol = "http") {
102
- proxy = proxy.trim();
103
- const splitByProtocol = proxy.split("://");
104
- if (1 < splitByProtocol.length) protocol = splitByProtocol[0];
105
- proxy = splitByProtocol[splitByProtocol.length - 1];
106
- if (!proxy.includes("@")) {
107
- const proxyParts = proxy.split(":");
108
- if (4 <= proxyParts.length) {
109
- proxy = `${proxyParts[proxyParts.length - 2]}:${proxyParts[proxyParts.length - 1]}@`;
110
- proxyParts.pop();
111
- proxyParts.pop();
112
- proxy += proxyParts.join(":");
113
- }
114
- }
115
- const proxyParts = proxy.split(':');
116
- const proxyEnd = parseInt(proxyParts[proxyParts.length - 1]);
117
- const proxyStart = proxyParts[proxyParts.length - 2];
118
- if (!proxyStart.includes(".")) {
119
- proxyParts.pop();
120
- proxyParts[proxyParts.length - 1] = _crypto.default.randomInt(parseInt(proxyStart), proxyEnd + 1).toString();
121
- }
122
- return protocol + "://" + proxyParts.join(':');
123
- }
124
- function proxyObject(...args) {
125
- let proxy = formatProxy(...args);
126
- const splitByProtocol = proxy.split('://');
127
- const splitById = splitByProtocol[splitByProtocol.length - 1].split('@');
128
- const splitByConn = splitById[splitById.length - 1].split(':');
129
- proxy = {
130
- protocol: splitByProtocol[0],
131
- host: splitByConn[0],
132
- port: parseInt(splitByConn[1])
133
- };
134
- if (1 < splitById.length) {
135
- const splitByAuth = splitById[0].split(':');
136
- proxy.auth = {
137
- username: splitByAuth[0],
138
- password: splitByAuth[1]
139
- };
140
- }
141
- return proxy;
142
- }
143
- async function proxify(proxyConfig, callback = formatProxy) {
144
- proxyConfig = proxyConfig || {};
145
- const timeout = 7000;
146
- if (proxyConfig.mode === 1) {
147
- return callback(proxyConfig.proxy);
148
- } else if (proxyConfig.mode === 2) {
149
- const proxy = callback(proxyConfig.proxy);
150
- try {
151
- await _axios.default.get(proxyConfig.resetApi, {
152
- timeout
153
- });
154
- } catch {
155
- return false;
156
- }
157
- await (0, _index.sleep)(5);
158
- for (let i = 0; i < 5; i++) {
159
- try {
160
- const res = await _axios.default.get("https://api64.ipify.org", {
161
- timeout,
162
- httpsAgent: new _hpagent.HttpsProxyAgent({
163
- proxy,
164
- timeout: 7000
165
- })
166
- });
167
- if (res.status === 200) return proxy;
168
- } catch {
169
- await (0, _index.sleep)(3);
170
- }
171
- }
172
- } else if (proxyConfig.mode === 3) {
173
- try {
174
- const res = await _axios.default.get(proxyConfig.resetApi, {
175
- timeout
176
- });
177
- if (res.status === 200) return callback(proxyConfig.proxy);
178
- } catch {
179
- return false;
180
- }
181
- } else if (proxyConfig.mode === 4) {
182
- return callback(proxyConfig.proxy).replace("{SESSION}", tokenHex(8));
183
- } else if (proxyConfig.mode === 5) {
184
- try {
185
- const lines = proxyConfig.proxy.split("\n");
186
- const line = lines[_crypto.default.randomInt(0, lines.length)];
187
- return callback(line);
188
- } catch {
189
- return false;
190
- }
191
- }
192
- return null;
193
- }