diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 7ba883a..3b10d33 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -1,10 +1,11 @@ module.exports = { parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint'], + plugins: ['@typescript-eslint','prettier'], extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', + 'prettier', ], parserOptions: { ecmaVersion: 2020, diff --git a/package-lock.json b/package-lock.json index 2515e5b..b374d16 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,7 +36,7 @@ "@rollup/plugin-node-resolve": "15.2.3", "@rollup/plugin-replace": "5.0.5", "@rollup/plugin-terser": "0.4.4", - "@rollup/plugin-typescript": "11.1.5", + "@rollup/plugin-typescript": "11.1.6", "@types/asciify": "1.3.33", "@types/chai": "4.3.11", "@types/cli-color": "2.0.6", @@ -44,19 +44,22 @@ "@types/lodash": "4.14.202", "@types/mime-types": "2.1.4", "@types/mocha": "10.0.6", - "@types/node": "20.10.7", + "@types/node": "20.10.8", "@types/shelljs": "0.8.15", "@types/twig": "1.12.16", "@types/uuid": "9.0.7", - "@typescript-eslint/eslint-plugin": "6.18.0", - "@typescript-eslint/parser": "6.18.0", + "@typescript-eslint/eslint-plugin": "6.18.1", + "@typescript-eslint/parser": "6.18.1", "chai": "4.3.10", "eslint": "8.56.0", + "eslint-config-prettier": "9.1.0", + "eslint-plugin-prettier": "5.1.3", "jsdom": "23.2.0", "mkdirp": "3.0.1", "mocha": "10.2.0", "mocha-jsdom": "2.0.0", "npm-run-all2": "6.1.1", + "prettier": "3.1.1", "rimraf": "5.0.5", "rollup": "4.9.4", "rollup-plugin-copy": "3.5.0", @@ -286,9 +289,9 @@ } }, "node_modules/@babel/runtime": { - "version": "7.23.7", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.7.tgz", - "integrity": "sha512-w06OXVOFso7LcbzMiDGt+3X7Rh7Ho8MmgPoWU3rarH+8upf+wSU/grlGbWzQyr3DkdN6ZeuMFjpdwW0Q+HxobA==", + "version": "7.23.8", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.8.tgz", + "integrity": "sha512-Y7KbAP984rn1VGMbGqKmBLio9V7y5Je9GvU4rQPCPinCyNfUcToxIXl06d59URp/F3LwinvODxab5N/G6qggkw==", "dependencies": { "regenerator-runtime": "^0.14.0" }, @@ -834,6 +837,18 @@ "node": ">=14" } }, + "node_modules/@pkgr/core": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.1.0.tgz", + "integrity": "sha512-Zwq5OCzuwJC2jwqmpEQt7Ds1DTi6BWSwoGkbb1n9pO3hzb35BoJELx7c0T23iDkBGkh2e7tvOtjF3tr3OaQHDQ==", + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" + } + }, "node_modules/@rollup/plugin-commonjs": { "version": "25.0.7", "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-25.0.7.tgz", @@ -948,12 +963,12 @@ } }, "node_modules/@rollup/plugin-typescript": { - "version": "11.1.5", - "resolved": "https://registry.npmjs.org/@rollup/plugin-typescript/-/plugin-typescript-11.1.5.tgz", - "integrity": "sha512-rnMHrGBB0IUEv69Q8/JGRD/n4/n6b3nfpufUu26axhUcboUzv/twfZU8fIBbTOphRAe0v8EyxzeDpKXqGHfyDA==", + "version": "11.1.6", + "resolved": "https://registry.npmjs.org/@rollup/plugin-typescript/-/plugin-typescript-11.1.6.tgz", + "integrity": "sha512-R92yOmIACgYdJ7dJ97p4K69I8gg6IEHt8M7dUBxN3W6nrO8uUxX5ixl0yU/N3aZTi8WhPuICvOHXQvF6FaykAA==", "dev": true, "dependencies": { - "@rollup/pluginutils": "^5.0.1", + "@rollup/pluginutils": "^5.1.0", "resolve": "^1.22.1" }, "engines": { @@ -1300,9 +1315,9 @@ } }, "node_modules/@types/node": { - "version": "20.10.7", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.10.7.tgz", - "integrity": "sha512-fRbIKb8C/Y2lXxB5eVMj4IU7xpdox0Lh8bUPEdtLysaylsml1hOOx1+STloRs/B9nf7C6kPRmmg/V7aQW7usNg==", + "version": "20.10.8", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.10.8.tgz", + "integrity": "sha512-f8nQs3cLxbAFc00vEU59yf9UyGUftkPaLGfvbVOIDdx2i1b8epBqj2aNGyP19fiyXWvlmZ7qC1XLjAzw/OKIeA==", "dependencies": { "undici-types": "~5.26.4" } @@ -1353,16 +1368,16 @@ "integrity": "sha512-ltIpx+kM7g/MLRZfkbL7EsCEjfzCcScLpkg37eXEtx5kmrAKBkTJwd1GIAjDSL8wTpM6Hzn5YO4pSb91BEwu1g==" }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.18.0.tgz", - "integrity": "sha512-3lqEvQUdCozi6d1mddWqd+kf8KxmGq2Plzx36BlkjuQe3rSTm/O98cLf0A4uDO+a5N1KD2SeEEl6fW97YHY+6w==", + "version": "6.18.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.18.1.tgz", + "integrity": "sha512-nISDRYnnIpk7VCFrGcu1rnZfM1Dh9LRHnfgdkjcbi/l7g16VYRri3TjXi9Ir4lOZSw5N/gnV/3H7jIPQ8Q4daA==", "dev": true, "dependencies": { "@eslint-community/regexpp": "^4.5.1", - "@typescript-eslint/scope-manager": "6.18.0", - "@typescript-eslint/type-utils": "6.18.0", - "@typescript-eslint/utils": "6.18.0", - "@typescript-eslint/visitor-keys": "6.18.0", + "@typescript-eslint/scope-manager": "6.18.1", + "@typescript-eslint/type-utils": "6.18.1", + "@typescript-eslint/utils": "6.18.1", + "@typescript-eslint/visitor-keys": "6.18.1", "debug": "^4.3.4", "graphemer": "^1.4.0", "ignore": "^5.2.4", @@ -1388,15 +1403,15 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.18.0.tgz", - "integrity": "sha512-v6uR68SFvqhNQT41frCMCQpsP+5vySy6IdgjlzUWoo7ALCnpaWYcz/Ij2k4L8cEsL0wkvOviCMpjmtRtHNOKzA==", + "version": "6.18.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.18.1.tgz", + "integrity": "sha512-zct/MdJnVaRRNy9e84XnVtRv9Vf91/qqe+hZJtKanjojud4wAVy/7lXxJmMyX6X6J+xc6c//YEWvpeif8cAhWA==", "dev": true, "dependencies": { - "@typescript-eslint/scope-manager": "6.18.0", - "@typescript-eslint/types": "6.18.0", - "@typescript-eslint/typescript-estree": "6.18.0", - "@typescript-eslint/visitor-keys": "6.18.0", + "@typescript-eslint/scope-manager": "6.18.1", + "@typescript-eslint/types": "6.18.1", + "@typescript-eslint/typescript-estree": "6.18.1", + "@typescript-eslint/visitor-keys": "6.18.1", "debug": "^4.3.4" }, "engines": { @@ -1416,13 +1431,13 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.18.0.tgz", - "integrity": "sha512-o/UoDT2NgOJ2VfHpfr+KBY2ErWvCySNUIX/X7O9g8Zzt/tXdpfEU43qbNk8LVuWUT2E0ptzTWXh79i74PP0twA==", + "version": "6.18.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.18.1.tgz", + "integrity": "sha512-BgdBwXPFmZzaZUuw6wKiHKIovms97a7eTImjkXCZE04TGHysG+0hDQPmygyvgtkoB/aOQwSM/nWv3LzrOIQOBw==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.18.0", - "@typescript-eslint/visitor-keys": "6.18.0" + "@typescript-eslint/types": "6.18.1", + "@typescript-eslint/visitor-keys": "6.18.1" }, "engines": { "node": "^16.0.0 || >=18.0.0" @@ -1433,13 +1448,13 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.18.0.tgz", - "integrity": "sha512-ZeMtrXnGmTcHciJN1+u2CigWEEXgy1ufoxtWcHORt5kGvpjjIlK9MUhzHm4RM8iVy6dqSaZA/6PVkX6+r+ChjQ==", + "version": "6.18.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.18.1.tgz", + "integrity": "sha512-wyOSKhuzHeU/5pcRDP2G2Ndci+4g653V43gXTpt4nbyoIOAASkGDA9JIAgbQCdCkcr1MvpSYWzxTz0olCn8+/Q==", "dev": true, "dependencies": { - "@typescript-eslint/typescript-estree": "6.18.0", - "@typescript-eslint/utils": "6.18.0", + "@typescript-eslint/typescript-estree": "6.18.1", + "@typescript-eslint/utils": "6.18.1", "debug": "^4.3.4", "ts-api-utils": "^1.0.1" }, @@ -1460,9 +1475,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.18.0.tgz", - "integrity": "sha512-/RFVIccwkwSdW/1zeMx3hADShWbgBxBnV/qSrex6607isYjj05t36P6LyONgqdUrNLl5TYU8NIKdHUYpFvExkA==", + "version": "6.18.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.18.1.tgz", + "integrity": "sha512-4TuMAe+tc5oA7wwfqMtB0Y5OrREPF1GeJBAjqwgZh1lEMH5PJQgWgHGfYufVB51LtjD+peZylmeyxUXPfENLCw==", "dev": true, "engines": { "node": "^16.0.0 || >=18.0.0" @@ -1473,13 +1488,13 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.18.0.tgz", - "integrity": "sha512-klNvl+Ql4NsBNGB4W9TZ2Od03lm7aGvTbs0wYaFYsplVPhr+oeXjlPZCDI4U9jgJIDK38W1FKhacCFzCC+nbIg==", + "version": "6.18.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.18.1.tgz", + "integrity": "sha512-fv9B94UAhywPRhUeeV/v+3SBDvcPiLxRZJw/xZeeGgRLQZ6rLMG+8krrJUyIf6s1ecWTzlsbp0rlw7n9sjufHA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.18.0", - "@typescript-eslint/visitor-keys": "6.18.0", + "@typescript-eslint/types": "6.18.1", + "@typescript-eslint/visitor-keys": "6.18.1", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -1501,17 +1516,17 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.18.0.tgz", - "integrity": "sha512-wiKKCbUeDPGaYEYQh1S580dGxJ/V9HI7K5sbGAVklyf+o5g3O+adnS4UNJajplF4e7z2q0uVBaTdT/yLb4XAVA==", + "version": "6.18.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.18.1.tgz", + "integrity": "sha512-zZmTuVZvD1wpoceHvoQpOiewmWu3uP9FuTWo8vqpy2ffsmfCE8mklRPi+vmnIYAIk9t/4kOThri2QCDgor+OpQ==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", "@types/json-schema": "^7.0.12", "@types/semver": "^7.5.0", - "@typescript-eslint/scope-manager": "6.18.0", - "@typescript-eslint/types": "6.18.0", - "@typescript-eslint/typescript-estree": "6.18.0", + "@typescript-eslint/scope-manager": "6.18.1", + "@typescript-eslint/types": "6.18.1", + "@typescript-eslint/typescript-estree": "6.18.1", "semver": "^7.5.4" }, "engines": { @@ -1526,12 +1541,12 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.18.0.tgz", - "integrity": "sha512-1wetAlSZpewRDb2h9p/Q8kRjdGuqdTAQbkJIOUMLug2LBLG+QOjiWoSj6/3B/hA9/tVTFFdtiKvAYoYnSRW/RA==", + "version": "6.18.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.18.1.tgz", + "integrity": "sha512-/kvt0C5lRqGoCfsbmm7/CwMqoSkY3zzHLIjdhHZQW3VFrnz7ATecOHR7nb7V+xn4286MBxfnQfQhAmCI0u+bJA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.18.0", + "@typescript-eslint/types": "6.18.1", "eslint-visitor-keys": "^3.4.1" }, "engines": { @@ -2787,6 +2802,48 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint-config-prettier": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz", + "integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==", + "dev": true, + "bin": { + "eslint-config-prettier": "bin/cli.js" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } + }, + "node_modules/eslint-plugin-prettier": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.1.3.tgz", + "integrity": "sha512-C9GCVAs4Eq7ZC/XFQHITLiHJxQngdtraXaM+LoUFoFp/lHNl2Zn8f3WQbe9HvTBBQ9YnKFB0/2Ajdqwo5D1EAw==", + "dev": true, + "dependencies": { + "prettier-linter-helpers": "^1.0.0", + "synckit": "^0.8.6" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-plugin-prettier" + }, + "peerDependencies": { + "@types/eslint": ">=8.0.0", + "eslint": ">=8.0.0", + "eslint-config-prettier": "*", + "prettier": ">=3.0.0" + }, + "peerDependenciesMeta": { + "@types/eslint": { + "optional": true + }, + "eslint-config-prettier": { + "optional": true + } + } + }, "node_modules/eslint-scope": { "version": "7.2.2", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", @@ -2971,6 +3028,12 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true }, + "node_modules/fast-diff": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz", + "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", + "dev": true + }, "node_modules/fast-glob": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", @@ -5021,6 +5084,33 @@ "node": ">= 0.8.0" } }, + "node_modules/prettier": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.1.1.tgz", + "integrity": "sha512-22UbSzg8luF4UuZtzgiUOfcGM8s4tjBv6dJRT7j275NXsy2jb4aJa4NNveul5x4eqlF1wuhuR2RElK71RvmVaw==", + "dev": true, + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prettier-linter-helpers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", + "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", + "dev": true, + "dependencies": { + "fast-diff": "^1.1.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/promise": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", @@ -5695,9 +5785,9 @@ } }, "node_modules/serialize-javascript": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.1.tgz", - "integrity": "sha512-owoXEFjWRllis8/M1Q+Cw5k8ZH40e3zhp/ovX+Xr/vi1qj6QesbyXXViFbpNvWvPNAD62SutwEXavefrLJWj7w==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", "dev": true, "dependencies": { "randombytes": "^2.1.0" @@ -6035,6 +6125,22 @@ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, + "node_modules/synckit": { + "version": "0.8.8", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.8.8.tgz", + "integrity": "sha512-HwOKAP7Wc5aRGYdKH+dw0PRRpbO841v2DENBtjnR5HFWoiNByAl7vrx3p0G/rCyYXQsrxqtX48TImFtPcIHSpQ==", + "dev": true, + "dependencies": { + "@pkgr/core": "^0.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" + } + }, "node_modules/terser": { "version": "5.26.0", "resolved": "https://registry.npmjs.org/terser/-/terser-5.26.0.tgz", diff --git a/package.json b/package.json index 3d83470..6b0360b 100644 --- a/package.json +++ b/package.json @@ -47,9 +47,9 @@ "build": " npm run rollup", "rollup": "rollup --config rollup.config.ts --configPlugin typescript", "start": "node ./bin/nodefony", - "test": "npm run build && run-s test:ts test:transpiled", + "test": "run-s test:ts test:transpiled", "test:ts": "ts-mocha -p src/tests/mocha-ts/tsconfig.test.json src/tests/**/*.test.ts src/tests/*.test.ts", - "test:transpiled": " mocha dist/tests/tests/*.js dist/tests/tests/**/*.js", + "test:transpiled": "npm run build && mocha dist/tests/tests/*.js dist/tests/tests/**/*.js", "lint": "npm run eslint-src && npm run eslint-test", "eslint-src": "eslint --ignore-pattern 'node_modules' --ignore-pattern 'src/tests' 'src/**/*.ts'", "eslint-types": "eslint --ignore-pattern 'node_modules' '**/*.d.ts'", @@ -84,7 +84,7 @@ "@rollup/plugin-node-resolve": "15.2.3", "@rollup/plugin-replace": "5.0.5", "@rollup/plugin-terser": "0.4.4", - "@rollup/plugin-typescript": "11.1.5", + "@rollup/plugin-typescript": "11.1.6", "@types/asciify": "1.3.33", "@types/chai": "4.3.11", "@types/cli-color": "2.0.6", @@ -92,19 +92,22 @@ "@types/lodash": "4.14.202", "@types/mime-types": "2.1.4", "@types/mocha": "10.0.6", - "@types/node": "20.10.7", + "@types/node": "20.10.8", "@types/shelljs": "0.8.15", "@types/twig": "1.12.16", "@types/uuid": "9.0.7", - "@typescript-eslint/eslint-plugin": "6.18.0", - "@typescript-eslint/parser": "6.18.0", + "@typescript-eslint/eslint-plugin": "6.18.1", + "@typescript-eslint/parser": "6.18.1", "chai": "4.3.10", "eslint": "8.56.0", + "eslint-config-prettier": "9.1.0", + "eslint-plugin-prettier": "5.1.3", "jsdom": "23.2.0", "mkdirp": "3.0.1", "mocha": "10.2.0", "mocha-jsdom": "2.0.0", "npm-run-all2": "6.1.1", + "prettier": "3.1.1", "rimraf": "5.0.5", "rollup": "4.9.4", "rollup-plugin-copy": "3.5.0", @@ -127,4 +130,4 @@ ], "author": "Christophe CAMENSULI ", "readmeFilename": "README.md" -} \ No newline at end of file +} diff --git a/rollup.config.ts b/rollup.config.ts index e16362a..c2e24cb 100644 --- a/rollup.config.ts +++ b/rollup.config.ts @@ -1,114 +1,114 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { defineConfig, Plugin, RollupOptions } from 'rollup' -import nodeResolve from '@rollup/plugin-node-resolve' -import typescript from '@rollup/plugin-typescript' -import commonjs from '@rollup/plugin-commonjs' -import json from '@rollup/plugin-json' -import copy from 'rollup-plugin-copy' -import replace from '@rollup/plugin-replace'; -import glob from 'glob'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url' +import { defineConfig, Plugin, RollupOptions } from "rollup"; +import nodeResolve from "@rollup/plugin-node-resolve"; +import typescript from "@rollup/plugin-typescript"; +import commonjs from "@rollup/plugin-commonjs"; +import json from "@rollup/plugin-json"; +import copy from "rollup-plugin-copy"; +import replace from "@rollup/plugin-replace"; +import glob from "glob"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; ////import lib from './package.json' -const externalCjs :string[]= [ +const externalCjs: string[] = [ "asciify", - "cli-color", - "cli-table3", - "clui", - "commander", - //"inquirer", - "lodash", - "mime-types", - "moment", - "node-emoji", - "rxjs", - "semver", + "cli-color", + "cli-table3", + "clui", + "commander", + //"inquirer", + "lodash", + "mime-types", + "moment", + "node-emoji", + "rxjs", + "semver", "shelljs", - "uuid" -] + "uuid", +]; -const external :string[]= [ +const external: string[] = [ "asciify", - "cli-color", - "cli-table3", - "clui", - "commander", - "inquirer", - "lodash", - "mime-types", - "moment", - "node-emoji", - "rxjs", - "semver", + "cli-color", + "cli-table3", + "clui", + "commander", + "inquirer", + "lodash", + "mime-types", + "moment", + "node-emoji", + "rxjs", + "semver", "shelljs", - "uuid" -] + "uuid", +]; const sharedNodeOptions = defineConfig({ treeshake: { - moduleSideEffects: 'no-external', + moduleSideEffects: "no-external", propertyReadSideEffects: false, tryCatchDeoptimization: false, }, output: { - dir: './dist', + dir: "./dist", entryFileNames: `node/[name].js`, - chunkFileNames: 'node/chunks/dep-[hash].js', - exports: 'auto', - format: 'esm', + chunkFileNames: "node/chunks/dep-[hash].js", + exports: "auto", + format: "esm", externalLiveBindings: false, freeze: false, }, onwarn(warning, warn) { - if (warning.message.includes('Circular dependency')) { - return + if (warning.message.includes("Circular dependency")) { + return; } - warn(warning) + warn(warning); }, -}) +}); const sharedTestOptions = defineConfig({ - treeshake: { - moduleSideEffects: 'no-external', + treeshake: { + moduleSideEffects: "no-external", propertyReadSideEffects: false, tryCatchDeoptimization: false, - }, - output: { - dir: './dist', + }, + output: { + dir: "./dist", entryFileNames: `tests/[name].js`, - chunkFileNames: 'tests/chunks/dep-[hash].js', - exports: 'auto', - format: 'esm', + chunkFileNames: "tests/chunks/dep-[hash].js", + exports: "auto", + format: "esm", externalLiveBindings: false, freeze: false, }, - onwarn(warning, warn) { - if (warning.message.includes('Circular dependency')) { - return + onwarn(warning, warn) { + if (warning.message.includes("Circular dependency")) { + return; } - if (warning.code === 'EVAL' ) { + if (warning.code === "EVAL") { return; } - warn(warning) + warn(warning); }, -}) +}); function createNodePlugins( isProduction: boolean, sourceMap: boolean, - declarationDir: string | false, -): (Plugin)[] { + declarationDir: string | false +): Plugin[] { return [ nodeResolve({ preferBuiltins: true }), typescript({ - tsconfig: path.resolve( 'tsconfig.json'), + tsconfig: path.resolve("tsconfig.json"), sourceMap, declaration: declarationDir !== false, declarationDir: declarationDir !== false ? declarationDir : undefined, }), commonjs({ - extensions: ['.js'], + extensions: [".js"], //ignoreDynamicRequires: true dynamicRequireTargets: [ //"node_modules/shelljs/src/*", @@ -120,125 +120,131 @@ function createNodePlugins( //"node_modules/shelljs/src/chmod.js", //"node_modules/shelljs/src/cp.js", //"node_modules/shelljs/src/dirs.js" - ] + ], }), json(), copy({ targets: [ - // { src: 'node_modules/asciify/lib/figlet-js/fonts/standard.flf', dest: 'dist/node-cjs/fonts/standard.flf' }, + // { src: 'node_modules/asciify/lib/figlet-js/fonts/standard.flf', dest: 'dist/node-cjs/fonts/standard.flf' }, //{ src: 'assets/images/**/*', dest: 'dist/public/images' } - ] - }) - ] + ], + }), + ]; } function createTstPlugins( isProduction: boolean, sourceMap: boolean, - declarationDir: string | false, -): (Plugin)[] { - return [ + declarationDir: string | false +): Plugin[] { + return [ nodeResolve({ preferBuiltins: true }), typescript({ - tsconfig: path.resolve( 'src','tests','tsconfig.test.json'), + tsconfig: path.resolve("src", "tests", "tsconfig.test.json"), sourceMap, declaration: declarationDir !== false, declarationDir: declarationDir !== false ? declarationDir : undefined, }), commonjs({ - extensions: ['.js'], + extensions: [".js"], //ignoreDynamicRequires: true - dynamicRequireTargets: [] + dynamicRequireTargets: [], }), json(), replace({ - preventAssignment:true, - 'navigator.userAgent': JSON.stringify('Mozilla/5.0 (compatible; Node.js)'), - 'window.navigator.userAgent': JSON.stringify('Mozilla/5.0 (compatible; Node.js)'), - "document._defaultView.navigator.userAgent": JSON.stringify('Mozilla/5.0 (compatible; Node.js)') + preventAssignment: true, + "navigator.userAgent": JSON.stringify( + "Mozilla/5.0 (compatible; Node.js)" + ), + "window.navigator.userAgent": JSON.stringify( + "Mozilla/5.0 (compatible; Node.js)" + ), + "document._defaultView.navigator.userAgent": JSON.stringify( + "Mozilla/5.0 (compatible; Node.js)" + ), }), - ] + ]; } -const inputTest = function input(){ - const myGlob = glob.sync('./src/tests/**/*.ts').map(file => { - if (/src\/.*.test.ts/.test(file)){ +const inputTest = (function input() { + const myGlob = glob + .sync("./src/tests/**/*.ts") + .map((file) => { + if (/src\/.*.test.ts/.test(file)) { return [ path.relative( - 'src', + "src", file.slice(0, file.length - path.extname(file).length) ), // eslint-disable-next-line no-undef - fileURLToPath(new URL(file, import.meta.url)) - ] + fileURLToPath(new URL(file, import.meta.url)), + ]; } - }).filter((ele)=>{ - if( ele){ - return ele - } - }) - return Object.fromEntries( myGlob as Iterable ) -}() - + }) + .filter((ele) => { + if (ele) { + return ele; + } + }); + return Object.fromEntries(myGlob as Iterable); +})(); -function createNodeConfig(isProduction: boolean) : RollupOptions { +function createNodeConfig(isProduction: boolean): RollupOptions { return defineConfig({ //input, input: "src/index.ts", - ...sharedNodeOptions, + ...sharedNodeOptions, output: { - preserveModulesRoot:"src", + preserveModulesRoot: "src", ...sharedNodeOptions.output, sourcemap: !isProduction, }, external, - plugins: createNodePlugins(isProduction, true, "dist/types") - }) + plugins: createNodePlugins(isProduction, true, "dist/types"), + }); } function createCjsConfig(isProduction: boolean) { return defineConfig({ ...sharedNodeOptions, - input:"src/index.ts", + input: "src/index.ts", output: { - dir: './dist', + dir: "./dist", entryFileNames: `node-cjs/[name].cjs`, - chunkFileNames: 'node-cjs/chunks/dep-[hash].js', - exports: 'named', - format: 'cjs', + chunkFileNames: "node-cjs/chunks/dep-[hash].js", + exports: "named", + format: "cjs", externalLiveBindings: false, freeze: false, sourcemap: false, }, external: externalCjs, - plugins: [...createNodePlugins(isProduction, true, false)] - }) + plugins: [...createNodePlugins(isProduction, true, false)], + }); } - -function createTestConfig(isProduction: boolean) : RollupOptions { +function createTestConfig(isProduction: boolean): RollupOptions { return defineConfig({ //input, input: inputTest, - ...sharedTestOptions, + ...sharedTestOptions, output: { ...sharedTestOptions.output, sourcemap: !isProduction, }, external, - plugins: createTstPlugins(isProduction, true, false) - }) + plugins: createTstPlugins(isProduction, true, false), + }); } - export default (commandLineArgs: any): RollupOptions[] => { - const isDev = commandLineArgs.watch - const isProduction = !isDev + const isDev = commandLineArgs.watch; + const isProduction = !isDev; return defineConfig([ //envConfig, //clientConfig, createNodeConfig(isProduction), createCjsConfig(isProduction), - createTestConfig(isProduction) - ]) -} \ No newline at end of file + createTestConfig(isProduction), + ]); +}; diff --git a/src/Cli.ts b/src/Cli.ts index c50fda2..02b8794 100644 --- a/src/Cli.ts +++ b/src/Cli.ts @@ -2,68 +2,65 @@ /* eslint-disable no-async-promise-executor */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable max-lines-per-function */ -import path from "node:path" -import fs from "node:fs" -import commander , { program } from "commander"; +import path from "node:path"; +import fs from "node:fs"; +import commander, { program } from "commander"; //import commander, { program } from '@commander-js/extra-typings'; -import { - spawn, - spawnSync, - SpawnSyncReturns, - SpawnSyncOptionsWithStringEncoding, - SpawnOptions -} - from "node:child_process"; +import { + spawn, + spawnSync, + SpawnSyncReturns, + SpawnSyncOptionsWithStringEncoding, + SpawnOptions, +} from "node:child_process"; import moment from "moment"; import semver from "semver"; import asciify from "asciify"; -import Table from "cli-table3" -import {get, random} from "node-emoji" -import clc from "cli-color" -import Service, {DefaultOptions} from "./Service"; -import {extend} from "./Tools" +import Table from "cli-table3"; +import { get, random } from "node-emoji"; +import clc from "cli-color"; +import Service, { DefaultOptionsService } from "./Service"; +import { extend } from "./Tools"; import Container from "./Container"; import FileClass from "./FileClass"; -import Event from "./Event" +import Event from "./Event"; //import { FSWatcher } from "node:fs"; -import {DebugType, EnvironmentType} from './Nodefony' +import { DebugType, EnvironmentType } from "./Nodefony"; import bare from "cli-color/bare"; -import clui from "clui" +import clui from "clui"; import Syslog from "./syslog/Syslog"; //import Rx from 'rxjs' -import Rx from 'rxjs' +import Rx from "rxjs"; //import {rm, ls, cd ,mkdir, ln, cp ,chmod, ShellString, ShellArray } from 'shelljs' -import shelljs from 'shelljs' - - - -interface CliDefaultOptions extends DefaultOptions{ - processName?: string - autostart?: boolean - asciify?: boolean - clear?: boolean - color?: bare.Format - prompt?: string - commander?: boolean - signals?: boolean - autoLogger?: boolean - resize?: boolean - version?: string - warning?: boolean - pid?: boolean - promiseRejection?: boolean - font?:string +import shelljs from "shelljs"; + +interface CliDefaultOptions extends DefaultOptionsService { + processName?: string; + autostart?: boolean; + asciify?: boolean; + clear?: boolean; + color?: bare.Format; + prompt?: string; + commander?: boolean; + signals?: boolean; + autoLogger?: boolean; + resize?: boolean; + version?: string; + warning?: boolean; + pid?: boolean; + promiseRejection?: boolean; + font?: string; } // const red = clc.red.bold; // const cyan = clc.cyan.bold; const blue = clc.blueBright.bold; -const {green} = clc; +const { green } = clc; // const yellow = clc.yellow.bold; const magenta = clc.magenta.bold; -const {reset} = clc; // '\x1b[0m'; +const { reset } = clc; // '\x1b[0m'; -let processName: string| null = null; +let processName: string | null = null; if (process.argv && process.argv[1]) { processName = path.basename(process.argv[1]); } else { @@ -73,8 +70,8 @@ if (process.argv && process.argv[1]) { const defaultTableCli = { style: { head: ["cyan"], - border: ["grey"] - } + border: ["grey"], + }, }; const defaultOptions = { @@ -91,49 +88,69 @@ const defaultOptions = { version: "1.0.0", warning: false, pid: false, - promiseRejection: true + promiseRejection: true, }; class Cli extends Service { - public override options : CliDefaultOptions = extend({}, defaultOptions) - public debug : DebugType = false - public environment : EnvironmentType | string = "production" - public commander : typeof program | null = null - public pid : number | null = null - public interactive : boolean = false - public prompt :Rx.Subject| any | null = null + public override options: CliDefaultOptions = extend({}, defaultOptions); + public debug: DebugType = false; + public environment: EnvironmentType | string = "production"; + public commander: typeof program | null = null; + public pid: number | null = null; + public interactive: boolean = false; + public prompt: Rx.Subject | any | null = null; public unhandledRejections: Map, string> = new Map(); public response: Record = {}; public timers: Record = {}; - public wrapperLog : (...data: any[]) => void = console.log - public version : string = "" - public clui: typeof clui = clui - public clc :typeof clc = clc - public spinner : clui.Spinner | null = null - public blankLine : (() => void ) = ()=>{} - public columns : number = 0 - public rows : number = 0 + public wrapperLog: (...data: any[]) => void = console.log; + public version: string = ""; + public clui: typeof clui = clui; + public clc: typeof clc = clc; + public spinner: clui.Spinner | null = null; + public blankLine: () => void = () => {}; + public columns: number = 0; + public rows: number = 0; constructor(name?: string); constructor(name: string, options: CliDefaultOptions); - constructor(name: string, container: Container | null | undefined, options: CliDefaultOptions); - constructor(name: string, container: Container | null | undefined, notificationsCenter: Event | false | undefined, options: CliDefaultOptions); + constructor( + name: string, + container: Container | null | undefined, + options: CliDefaultOptions + ); + constructor( + name: string, + container: Container | null | undefined, + notificationsCenter: Event | false | undefined, + options: CliDefaultOptions + ); constructor(name?: string, ...args: any[]) { - const container : Container | undefined | null = args[0] instanceof Container ? args[0] : undefined; - const notificationsCenter: Event | undefined | false = (args[1] instanceof Event) ? args[1] : (args[1] === false) ? false: undefined; - const last = args[args.length - 1] - let options = null - if( last instanceof Container || last instanceof Event || last === false){ - options = extend({}, defaultOptions) ; - }else{ - options = extend({}, defaultOptions, last || {}) ; - } - super(name || options.processName, container, notificationsCenter, options); + const container: Container | undefined | null = + args[0] instanceof Container ? args[0] : undefined; + const notificationsCenter: Event | undefined | false = + args[1] instanceof Event + ? args[1] + : args[1] === false + ? false + : undefined; + const last = args[args.length - 1]; + let options = null; + if (last instanceof Container || last instanceof Event || last === false) { + options = extend({}, defaultOptions); + } else { + options = extend({}, defaultOptions, last || {}); + } + super( + name || options.processName, + container, + notificationsCenter, + options + ); this.options = options; - if ( process.env.NODE_ENV ){ - this.environment = process.env.NODE_ENV - }else{ - this.environment = "production"; + if (process.env.NODE_ENV) { + this.environment = process.env.NODE_ENV; + } else { + this.environment = "production"; } this.setProcessTitle(); this.pid = this.options.pid ? this.setPid() : null; @@ -175,10 +192,10 @@ class Cli extends Service { .catch((e) => this.log(e, "ERROR")); } else if (this.options.autostart) { try { - const func = async function(this: Cli){ + const func = async function (this: Cli) { await this.fireAsync("onStart", this); - } - func.call(this) + }; + func.call(this); } catch (e) { this.log(e, "ERROR"); } @@ -188,7 +205,7 @@ class Cli extends Service { //Méthode privée pour gérer les signaux private handleSignals(): void { const signalHandler = (signal: string) => { - if( this.blankLine){ + if (this.blankLine) { this.blankLine(); } this.wrapperLog = console.log; @@ -212,7 +229,7 @@ class Cli extends Service { }); } - start () : Promise{ + start(): Promise { return new Promise(async (resolve, reject) => { try { if (this.options.autostart) { @@ -237,7 +254,7 @@ class Cli extends Service { }); } - idle () { + idle() { let resolve = null; let reject = null; const promise = new Promise((res, rej) => { @@ -248,13 +265,13 @@ class Cli extends Service { return { resolve, promise, - reject + reject, }; - }()); + })(); // return this.idleId = setInterval(() => {}, 0); } - checkVersion (version : string | semver.SemVer | null | undefined = null) { + checkVersion(version: string | semver.SemVer | null | undefined = null) { if (!version) { version = this.version; } @@ -265,12 +282,12 @@ class Cli extends Service { throw new Error(`Not valid version : ${version} check http://semver.org `); } - async showAsciify (name: string | null = null) { + async showAsciify(name: string | null = null) { if (!name) { name = this.name; } return await this.asciify(` ${name}`, { - font: this.options.font || "standard" + font: this.options.font || "standard", }) .then((data: string) => { this.fire("onAsciify", data); @@ -287,53 +304,68 @@ class Cli extends Service { }); } - showBanner () { - const version = this.commander ? this.commander.version() : this.options.version || "1.0.0"; + showBanner() { + const version = this.commander + ? this.commander.version() + : this.options.version || "1.0.0"; let banner = null; if (this.options.version) { - banner = ` Version : ${blue(version)} Platform : ${green(process.platform)} Process : ${green(process.title)} Pid : ${process.pid}`; - if( this.blankLine){ - this.blankLine(); + banner = ` Version : ${blue(version)} Platform : ${green( + process.platform + )} Process : ${green(process.title)} Pid : ${process.pid}`; + if (this.blankLine) { + this.blankLine(); } console.log(banner); } return banner; } - listenRejection () { + listenRejection() { process.on("rejectionHandled", (promise) => { this.log("PROMISE REJECTION EVENT ", "CRITIC", "rejectionHandled"); this.unhandledRejections.delete(promise); }); - process.on("unhandledRejection", (reason: string, promise: Promise) => { - this.log(`WARNING !!! PROMISE CHAIN BREAKING : ${reason}`, "WARNING", "unhandledRejection"); - console.trace(promise); - this.unhandledRejections.set(promise, reason); - }); + process.on( + "unhandledRejection", + (reason: string, promise: Promise) => { + this.log( + `WARNING !!! PROMISE CHAIN BREAKING : ${reason}`, + "WARNING", + "unhandledRejection" + ); + console.trace(promise); + this.unhandledRejections.set(promise, reason); + } + ); } - setPid () : number { - return this.pid = process.pid; + setPid(): number { + return (this.pid = process.pid); } - setProcessTitle (name?: string) { + setProcessTitle(name?: string) { if (name) { process.title = name.replace(new RegExp("\\s", "gi"), "").toLowerCase(); } else { - process.title = this.name.replace(new RegExp("\\s", "gi"), "").toLowerCase(); + process.title = this.name + .replace(new RegExp("\\s", "gi"), "") + .toLowerCase(); } return process.title; } - logEnv () { - return `${blue(` \x1b ${this.name}`)} Nodefony Environment : ${magenta(this.environment)}`; + logEnv() { + return `${blue(` \x1b ${this.name}`)} Nodefony Environment : ${magenta( + this.environment + )}`; } - initCommander () { + initCommander() { if (this.options.commander) { this.commander = program; - this.commander.option('-i, --interactive', 'Interaction mode') - this.commander.option('-d, --debug', 'Debug mode') + this.commander.option("-i, --interactive", "Interaction mode"); + this.commander.option("-d, --debug", "Debug mode"); if (this.options.version) { this.setCommandVersion(this.options.version); } @@ -342,92 +374,124 @@ class Cli extends Service { return null; } - initUi () : void{ - this.blankLine = function (this: Cli): () => void { - if( this.clui){ - const myLine = new this.clui.Line().fill(); - return () => { + initUi(): void { + this.blankLine = function (this: Cli): () => void { + if (this.clui) { + const myLine = new this.clui.Line().fill(); + return () => { myLine.output(); }; } return () => { - console.log() - } + console.log(); + }; }.call(this); if (this.options.resize) { this.resize(); } } - getFonts () : void { + getFonts(): void { asciify.getFonts((err, fonts) => { - fonts.forEach((ele)=>{ - this.log(ele) + fonts.forEach((ele) => { + this.log(ele); }); }); } - async asciify (txt: string, options?: object , callback?: (error:Error, data:string) => void ): Promise { + async asciify( + txt: string, + options?: object, + callback?: (error: Error, data: string) => void + ): Promise { return new Promise((resolve, reject) => { - asciify(txt, extend({ - font: "standard" - }, options), (error, data) => { - if (callback && typeof callback === "function") { - return callback(error, data); - } - if (error) { - return reject(error); + asciify( + txt, + extend( + { + font: "standard", + }, + options + ), + (error, data) => { + if (callback && typeof callback === "function") { + return callback(error, data); + } + if (error) { + return reject(error); + } + return resolve(data); } - return resolve(data); - }); + ); }); } - async parseCommand (argv: readonly string[] | undefined) : Promise{ - if (! this.commander){ - throw new Error(`commander not found`) + public parse( + argv?: string[], + options?: commander.ParseOptions + ): commander.Command { + if (this.commander) { + return this.commander?.parse(argv, options); } - const parser = await this.commander.parse(argv || process.argv); - const {debug} = this.commander.opts(); - if (debug) { - this.debug = debug; - } else { - this.debug = false; + throw new Error(`Commander not found`); + } + + public clearCommand(): void { + this.commander?.setOptionValue("interactive", false); + this.commander?.setOptionValue("debug", false); + while (process.argv.length > 2) { + process.argv.pop(); } - const {interactive} = this.commander.opts(); - if (interactive) { - this.interactive = interactive; - } else { - this.interactive = false; + } + + runCommand(cmd: string, args: any[] = []) { + // this.log(`Commnand : ${cmd} Arguments : ${args}`, "DEBUG", "COMMAND"); + this.clearCommand(); + if (cmd) { + process.argv.push(cmd); } - return Promise.resolve(parser); + this.parse(process.argv.concat(args)); } - setOption (flags: string, description?: string , defaultValue?: string | boolean | string[] | undefined) : commander.Command { - if (this.commander){ + setCommandOption( + flags: string, + description?: string, + defaultValue?: string | boolean | string[] | undefined + ): commander.Command { + if (this.commander) { return this.commander.option(flags, description, defaultValue); } - throw new Error(`Commender not found`) + throw new Error(`Commender not found`); } - - setCommandVersion (version: string) : commander.Command { + setCommandVersion(version: string): commander.Command { if (this.commander && typeof this.commander.version === "function") { - return this.commander.version(version, "-v, --version", "Nodefony Current Version"); + return this.commander.version( + version, + "-v, --version", + "Nodefony Current Version" + ); } - throw new Error(`Commender not found`) + throw new Error(`Commender not found`); } - setCommand (nameAndArgs: string, description:string , options?: commander.ExecutableCommandOptions | undefined): commander.Command { + setCommand( + nameAndArgs: string, + description: string, + options?: commander.ExecutableCommandOptions | undefined + ): commander.Command { if (this.commander) { return this.commander.command(nameAndArgs, description, options); } - throw new Error(`Commender not found`) + throw new Error(`Commender not found`); } - showHelp (quit: boolean , context: commander.HelpContext | undefined ) : void | never{ - if( ! this.commander ){ - throw new Error(`Commender not found`) + showHelp( + quit: boolean, + context: commander.HelpContext | undefined + ): void | never { + if (!this.commander) { + throw new Error(`Commender not found`); } if (quit) { return this.commander.help(context); @@ -435,11 +499,11 @@ class Cli extends Service { return this.commander.outputHelp(context); } - createProgress (size: number) { + createProgress(size: number) { return new this.clui.Progress(size); } - createSparkline (values: number[] , suffix: string) : string{ + createSparkline(values: number[], suffix: string): string { if (values) { try { return this.clui.Sparkline(values, suffix || ""); @@ -448,14 +512,14 @@ class Cli extends Service { throw e; } } - throw new Error(`Bad vlue : ${values}`) + throw new Error(`Bad vlue : ${values}`); } - getSpinner (message: string, design?: string[]) { - return new this.clui.Spinner(message, design ); + getSpinner(message: string, design?: string[]) { + return new this.clui.Spinner(message, design); } - startSpinner (message: string, design?: string[]) : clui.Spinner | null { + startSpinner(message: string, design?: string[]): clui.Spinner | null { try { this.spinner = this.getSpinner(message, design); this.wrapperLog = this.spinner.message; @@ -467,7 +531,7 @@ class Cli extends Service { } } - stopSpinner (/* message, options*/) { + stopSpinner(/* message, options*/) { if (this.spinner) { this.spinner.stop(); this.wrapperLog = console.log; @@ -478,7 +542,11 @@ class Cli extends Service { return false; } - displayTable (datas : any[], options = defaultTableCli, syslog : Syslog | null = null) { + displayTable( + datas: any[], + options = defaultTableCli, + syslog: Syslog | null = null + ) { if (!datas || !datas.length) { return new Table(extend({}, defaultTableCli, options)); } @@ -496,8 +564,18 @@ class Cli extends Service { return table; } - static niceBytes (x: string | number) { - const units :string[] = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] + static niceBytes(x: string | number) { + const units: string[] = [ + "bytes", + "KB", + "MB", + "GB", + "TB", + "PB", + "EB", + "ZB", + "YB", + ]; let n = parseInt(x, 10) || 0, l = 0; while (n >= 1024) { @@ -507,29 +585,29 @@ class Cli extends Service { return `${n.toFixed(n >= 10 || l < 1 ? 0 : 1)} ${units[l]}`; } - static niceUptime (date: moment.MomentInput, suffix: boolean | undefined) { + static niceUptime(date: moment.MomentInput, suffix: boolean | undefined) { return moment(date).fromNow(suffix || false); } - static niceDate (date: moment.MomentInput, format: string | undefined) { + static niceDate(date: moment.MomentInput, format: string | undefined) { return moment(date).format(format); } - getEmoji (name: string) { + getEmoji(name: string) { if (name) { return get(name); } return random().emoji; } - clear () { - console.clear() + clear() { + console.clear(); } - reset () { + reset() { process.stdout.write(reset); } - resize () { + resize() { process.stdout.on("resize", () => { this.columns = process.stdout.columns; this.rows = process.stdout.rows; @@ -537,31 +615,39 @@ class Cli extends Service { }); } - rm (...files: string[] ) : shelljs.ShellString { - return shelljs.rm(...files ); + rm(...files: string[]): shelljs.ShellString { + return shelljs.rm(...files); } - cp (options: string, source: string | string[], dest: string) : shelljs.ShellString { - return shelljs.cp(options, source, dest ); + cp( + options: string, + source: string | string[], + dest: string + ): shelljs.ShellString { + return shelljs.cp(options, source, dest); } - cd (dir?: string | undefined) : shelljs.ShellString { - return shelljs.cd( dir); + cd(dir?: string | undefined): shelljs.ShellString { + return shelljs.cd(dir); } - ln (options: string, source: string, dest: string): shelljs.ShellString { - return shelljs.ln(options, source, dest ); + ln(options: string, source: string, dest: string): shelljs.ShellString { + return shelljs.ln(options, source, dest); } - mkdir (...dir: string[]): shelljs.ShellString { - return shelljs.mkdir(...dir ); + mkdir(...dir: string[]): shelljs.ShellString { + return shelljs.mkdir(...dir); } // chmod(options: string, mode: string | number, file: string): shelljs.ShellString { // return shelljs.chmod(options, mode, file); // } - chmod(options: string, mode: string | number, file: string): shelljs.ShellString; + chmod( + options: string, + mode: string | number, + file: string + ): shelljs.ShellString; chmod(mode: string | number, file: string): shelljs.ShellString; chmod(...args: any[]): shelljs.ShellString { if (args.length === 3) { @@ -570,45 +656,18 @@ class Cli extends Service { return shelljs.chmod(args[0], args[1]); } else { // Gérer l'erreur ou lancer une exception si nécessaire - throw new Error('Nombre d\'arguments invalide pour la méthode chmod.'); + throw new Error("Nombre d'arguments invalide pour la méthode chmod."); } } - ls (...paths: string[]): shelljs.ShellArray{ + ls(...paths: string[]): shelljs.ShellArray { return shelljs.ls(...paths); } - // async createDirectory ( - // myPath: fs.PathLike , - // mode ?: fs.MakeDirectoryOptions | fs.Mode | null , - // force: boolean = false - // ) : Promise { - // return new Promise((resolve, reject) => { - // try { - // console.log("pass", myPath) - // const file = fs.mkdirSync(myPath, mode) - // console.log(file) - // return resolve( new FileClass( myPath ) ); - // } catch (e: any) { - // switch (e.code) { - // case "EEXIST": - // if (force) { - // return resolve(new FileClass(myPath)); - // } - // break; - // } - // return reject(e); - // } - // }) - // .catch((e) => { - // throw e; - // }); - // } - async createDirectory( - myPath: fs.PathLike, - mode?: fs.MakeDirectoryOptions | fs.Mode | null, - force: boolean = false + myPath: fs.PathLike, + mode?: fs.MakeDirectoryOptions | fs.Mode | null, + force: boolean = false ): Promise { try { await fs.promises.mkdir(myPath, mode); @@ -621,18 +680,22 @@ class Cli extends Service { } break; } - throw e + throw e; } } - existsSync (myPath: fs.PathLike) { + existsSync(myPath: fs.PathLike) { if (!myPath) { throw new Error("existsSync no path found"); } return fs.existsSync(myPath); } - exists (myPath: fs.PathLike, mode?: number | undefined, callback?: fs.NoParamCallback) { + exists( + myPath: fs.PathLike, + mode?: number | undefined, + callback?: fs.NoParamCallback + ) { if (!myPath) { throw new Error("exists no path found"); } @@ -645,7 +708,7 @@ class Cli extends Service { return fs.existsSync(myPath); } - terminate (code: number= 0, quiet?: boolean) { + terminate(code: number = 0, quiet?: boolean) { if (quiet) { return code; } @@ -655,14 +718,14 @@ class Cli extends Service { process.exit(code); } - static quit (code: number) { + static quit(code: number) { if (code === 0) { process.exitCode = code; } process.exit(code); } - startTimer (name: string) { + startTimer(name: string) { if (name in this.timers) { throw new Error(`Timer : ${name} already exist !! stopTimer to clear`); } @@ -678,7 +741,7 @@ class Cli extends Service { } } - stopTimer (name: string) { + stopTimer(name: string) { if (!name) { for (const timer in this.timers) { this.stopTimer(this.timers[timer]); @@ -699,79 +762,97 @@ class Cli extends Service { } } - getCommandManager (manager: string) { + getCommandManager(manager: string) { if (process.platform === "win32") { switch (manager) { - case "npm": - return "npm.cmd"; - case "yarn": - return "yarn.cmd"; - case "pnpm": - return "pnpm.cmd"; - default: - throw new Error(`bad manager : ${manager}`); + case "npm": + return "npm.cmd"; + case "yarn": + return "yarn.cmd"; + case "pnpm": + return "pnpm.cmd"; + default: + throw new Error(`bad manager : ${manager}`); } } else { switch (manager) { - case "npm": - return "npm"; - case "yarn": - return "yarn"; - case "pnpm": - return "pnpm"; - default: - throw new Error(`bad manager : ${manager}`); + case "npm": + return "npm"; + case "yarn": + return "yarn"; + case "pnpm": + return "pnpm"; + default: + throw new Error(`bad manager : ${manager}`); } } } - runPackageManager (argv : string[]= [], cwd :string= path.resolve("."), env: EnvironmentType , manager: string) { + runPackageManager( + argv: string[] = [], + cwd: string = path.resolve("."), + env: EnvironmentType, + manager: string + ) { const currentenv = process.env.NODE_ENV; switch (env) { - case "dev": - case "development": - switch (manager) { - case "npm": - case "yarn": - case "pnpm": - break; - } - process.env.NODE_ENV = "development"; - break; - case "prod": - case "production": - switch (manager) { - case "npm": - argv.push("--omit=dev"); - break; - case "yarn": - argv.push("--production"); + case "dev": + case "development": + switch (manager) { + case "npm": + case "yarn": + case "pnpm": + break; + } + process.env.NODE_ENV = "development"; break; - case "pnpm": - argv.push("--prod"); + case "prod": + case "production": + switch (manager) { + case "npm": + argv.push("--omit=dev"); + break; + case "yarn": + argv.push("--production"); + break; + case "pnpm": + argv.push("--prod"); + break; + } + process.env.NODE_ENV = "production"; break; - } - process.env.NODE_ENV = "production"; - break; - default: - process.env.NODE_ENV = this.environment; + default: + process.env.NODE_ENV = this.environment; } return new Promise((resolve, reject) => { try { - this.debug = this.commander ? this.commander.opts().debug || false : false; + this.debug = this.commander + ? this.commander.opts().debug || false + : false; this.log(`Command : ${manager} ${argv.join(" ")} in cwd : ${cwd}`); const exe = this.getCommandManager(manager); - this.spawn(exe, argv, { - cwd, - env: process.env, - stdio: "inherit" - }, (code: number) => { - process.env.NODE_ENV = currentenv; - if (code === 0) { - return resolve(code); + this.spawn( + exe, + argv, + { + cwd, + env: process.env, + stdio: "inherit", + }, + (code: number) => { + process.env.NODE_ENV = currentenv; + if (code === 0) { + return resolve(code); + } + return resolve( + new Error( + `Command : ${manager} ${argv.join( + " " + )} cwd : ${cwd} Error Code : ${code}` + ) + ); } - return resolve(new Error(`Command : ${manager} ${argv.join(" ")} cwd : ${cwd} Error Code : ${code}`)); - }); + ); } catch (e) { process.env.NODE_ENV = currentenv; this.log(e, "ERROR"); @@ -780,24 +861,29 @@ class Cli extends Service { }); } - async npm (argv = [], cwd = path.resolve("."), env : EnvironmentType= "dev") { + async npm(argv = [], cwd = path.resolve("."), env: EnvironmentType = "dev") { return this.runPackageManager(argv, cwd, env, "npm"); } - async yarn (argv = [], cwd = path.resolve("."), env : EnvironmentType= "dev") { + async yarn(argv = [], cwd = path.resolve("."), env: EnvironmentType = "dev") { return this.runPackageManager(argv, cwd, env, "yarn"); } - async pnpm (argv = [], cwd = path.resolve("."), env : EnvironmentType= "dev") { + async pnpm(argv = [], cwd = path.resolve("."), env: EnvironmentType = "dev") { return this.runPackageManager(argv, cwd, env, "pnpm"); } - spawn (command: string, args: readonly string[] | undefined, options : SpawnOptions | undefined , close : ((code:number) =>void) | null= null) { + spawn( + command: string, + args: readonly string[] | undefined, + options: SpawnOptions | undefined, + close: ((code: number) => void) | null = null + ) { return new Promise((resolve, reject) => { let cmd = null; try { - if (!args ){ - args=[] + if (!args) { + args = []; } this.log(`Spawn : ${command} ${args.join(" ")}`, "INFO"); cmd = spawn(command, args, options || {}); @@ -831,10 +917,13 @@ class Cli extends Service { close(code); } if (code !== 0) { - if (!args){ - args =[] + if (!args) { + args = []; } - this.log(`Spawn : ${command} ${args.join(" ")} Error Code : ${code}`, "ERROR"); + this.log( + `Spawn : ${command} ${args.join(" ")} Error Code : ${code}`, + "ERROR" + ); } return resolve(code); }); @@ -852,7 +941,11 @@ class Cli extends Service { }); } - spawnSync (command: string, args: readonly string[], options: SpawnSyncOptionsWithStringEncoding) : SpawnSyncReturns { + spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding + ): SpawnSyncReturns { let cmd = null; try { cmd = spawnSync(command, args, options); @@ -874,6 +967,4 @@ class Cli extends Service { } export default Cli; -export{ - CliDefaultOptions -} \ No newline at end of file +export { CliDefaultOptions }; diff --git a/src/Container.ts b/src/Container.ts index 732aef1..dfc8a9f 100644 --- a/src/Container.ts +++ b/src/Container.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { v4 as uuidv4 } from 'uuid'; -import {extend, isPlainObject} from './Tools' +import { v4 as uuidv4 } from "uuid"; +import { extend, isPlainObject } from "./Tools"; const generateId = function (): string { return uuidv4(); @@ -13,11 +13,15 @@ const ISDefined = function (ele: any): boolean { return false; }; -const parseParameterString = function (this: Container['parameters'] | ProtoParametersPrototype, str: string, value?: any): DynamicParam | null { +const parseParameterString = function ( + this: Container["parameters"] | ProtoParametersPrototype, + str: string, + value?: any +): DynamicParam | null { if (!this) { throw new Error(`Bad call`); } - const parts = str.split('.'); + const parts = str.split("."); const currentPart = parts.shift(); if (currentPart !== undefined) { if (!this[currentPart] && parts.length > 0) { @@ -33,33 +37,39 @@ const parseParameterString = function (this: Container['parameters'] | ProtoPara } return this[currentPart]; } else { - if( this[currentPart] ){ - return parseParameterString.call(this[currentPart], parts.join('.'), value); + if (this[currentPart]) { + return parseParameterString.call( + this[currentPart], + parts.join("."), + value + ); } - return null + return null; } } return this; }; // Déclaration d'un objet hétérogène -interface DynamicService { +interface DynamicService { [cleDynamic: string]: any; // Propriétés dynamiques de tout type } -interface DynamicParam { +interface DynamicParam { [cleDynamic: string]: any; // Propriétés dynamiques de tout type } interface Scopes { [nameScope: string]: { - [idContainer: string] : Container; + [idContainer: string]: Container; }; } type ProtoService = { (): void; [key: string]: any }; type ProtoParameters = { (): void; [key: string]: any }; -type ProtoParametersPrototype = ReturnType; +type ProtoParametersPrototype = ReturnType< + typeof Container.prototype.protoParameters.prototype +>; /* * @@ -67,21 +77,18 @@ type ProtoParametersPrototype = ReturnType(name: string, ele: T): DynamicParam | null { - if (typeof name !== "string") { - throw new Error("setParameters : container parameter name must be a string") + if (typeof name !== "string") { + throw new Error( + "setParameters : container parameter name must be a string" + ); } - if (ele === undefined) { - throw new Error(`setParameters : ${name} container parameter value must be define`); + if (ele === undefined) { + throw new Error( + `setParameters : ${name} container parameter value must be define` + ); } //parseParameterString.call(this.protoParameters.prototype, name, ele) - return parseParameterString.call(this.parameters, name, ele) + return parseParameterString.call(this.parameters, name, ele); } - public getParameters(name: string): DynamicParam | null{ + public getParameters(name: string): DynamicParam | null { //console.log(`main getParameters : ${name}`) - if(name){ + if (name) { const res = parseParameterString.call(this.parameters, name); //console.log(`main After getParameters : `, res) - return res + return res; } - throw new Error(`Bad name : ${name}`) + throw new Error(`Bad name : ${name}`); } - public clean() : void { - this.services = null; + public clean(): void { + this.services = null; this.parameters = null; } } @@ -232,26 +242,27 @@ class Scope extends Container { this.parameters = Object.create(this.parent.protoParameters.prototype); } - public override getParameters(name: string, merge: boolean = true, deep: boolean = true) : DynamicParam | null{ - const res = parseParameterString.call(this.parameters, name) - const obj = this.parent.getParameters(name) - if(ISDefined(res)) { - if( merge && isPlainObject(obj) && isPlainObject(res) ){ - return extend(deep, obj, res) + public override getParameters( + name: string, + merge: boolean = true, + deep: boolean = true + ): DynamicParam | null { + const res = parseParameterString.call(this.parameters, name); + const obj = this.parent.getParameters(name); + if (ISDefined(res)) { + if (merge && isPlainObject(obj) && isPlainObject(res)) { + return extend(deep, obj, res); } - return res + return res; } - return obj + return obj; } - - public override clean() : void{ + + public override clean(): void { this.parent = null; return super.clean(); } } -export default Container -export{ - DynamicParam -} - +export default Container; +export { DynamicParam }; diff --git a/src/Error.ts b/src/Error.ts index 6ac618d..e091991 100644 --- a/src/Error.ts +++ b/src/Error.ts @@ -1,31 +1,31 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import assert from "node:assert"; -import nodefony , { kernel} from "./Nodefony" +import nodefony, { kernel } from "./Nodefony"; import { STATUS_CODES } from "node:http"; -import {inspect} from "node:util"; -import clc from "cli-color" +import { inspect } from "node:util"; +import clc from "cli-color"; declare global { interface Error { errno?: string; bytesParsed?: number; - errors: any[] - parent:Error - sql: any - actual: any - expected: any - operator: any - syscall: any - address:any - port:any - rawPacket:any - fields:any - code:any - index: any - value: any - table:any - constraint:any + errors: any[]; + parent: Error; + sql: any; + actual: any; + expected: any; + operator: any; + syscall: any; + address: any; + port: any; + rawPacket: any; + fields: any; + code: any; + index: any; + value: any; + table: any; + constraint: any; } } @@ -51,17 +51,16 @@ const json: JsonDescriptor = { Object.defineProperty(Error.prototype, "toJSON", json); - const exclude = { context: true, resolver: true, container: true, - secure: true + secure: true, }; -const jsonNodefony : JsonDescriptor = { +const jsonNodefony: JsonDescriptor = { configurable: true, writable: true, - value () { + value() { const alt: Record = {}; const storeKey = function (this: Record, key: string) { if (key in exclude) { @@ -71,10 +70,9 @@ const jsonNodefony : JsonDescriptor = { }; Object.getOwnPropertyNames(this).forEach(storeKey, this); return alt; - } + }, }; - const isSequelizeError = function (error: Error) { try { return nodefony.sequelize.isError(error); @@ -92,21 +90,19 @@ const isMongooseError = function (error: Error) { }; class nodefonyError extends Error { - - public override code : number | null - public error? : Error - public errorType: string + public override code: number | null; + public error?: Error; + public errorType: string; //public actual : string [key: string]: any; - constructor (message: string | Error, code?: number) { - - if( message instanceof Error){ + constructor(message: string | Error, code?: number) { + if (message instanceof Error) { super(message.message); - }else { + } else { super(message); } - + this.name = this.constructor.name; this.code = null; this.errorType = this.name; @@ -118,96 +114,96 @@ class nodefonyError extends Error { } } - static isError (error: Error) { + static isError(error: Error) { switch (true) { - case error instanceof ReferenceError: - return "ReferenceError"; - case error instanceof TypeError: - return "TypeError"; - case error instanceof SyntaxError: - return "SyntaxError"; - case error instanceof assert.AssertionError: - return "AssertionError"; - case isSequelizeError(error): - return "SequelizeError"; - case isMongooseError(error): - return "MongooseError"; - case error instanceof Error: - if (error.errno) { - return "SystemError"; - } - if (error.bytesParsed) { - return "ClientError"; - } - try { - return error.constructor.name || "Error"; - } catch (e) { - return "Error"; - } + case error instanceof ReferenceError: + return "ReferenceError"; + case error instanceof TypeError: + return "TypeError"; + case error instanceof SyntaxError: + return "SyntaxError"; + case error instanceof assert.AssertionError: + return "AssertionError"; + case isSequelizeError(error): + return "SequelizeError"; + case isMongooseError(error): + return "MongooseError"; + case error instanceof Error: + if (error.errno) { + return "SystemError"; + } + if (error.bytesParsed) { + return "ClientError"; + } + try { + return error.constructor.name || "Error"; + } catch (e) { + return "Error"; + } } return false; } - getType (error :Error) { + getType(error: Error) { const errorType = nodefonyError.isError(error); if (errorType) { switch (errorType) { - case "TypeError": - case "ReferenceError": - case "SyntaxError": - return errorType; - case "AssertionError": - this.actual = error.actual; - this.expected = error.expected; - this.operator = error.operator; - return errorType; - case "SystemError": - this.errno = error.errno; - this.syscall = error.syscall; - this.address = error.address; - this.port = error.port; - this.stack = error.stack; - return errorType; - case "ClientError": - this.bytesParsed = error.bytesParsed; - this.rawPacket = error.rawPacket; - return errorType; - case "SequelizeError": - this.name = error.name; - this.message = error.message; - if (error.errors) { - this.errors = error.errors || []; - } - if (error.fields) { - this.fields = error.fields; - } - if (error.parent) { - this.parent = error.parent; - if (this.parent.errno) { - this.errno = this.parent.errno; + case "TypeError": + case "ReferenceError": + case "SyntaxError": + return errorType; + case "AssertionError": + this.actual = error.actual; + this.expected = error.expected; + this.operator = error.operator; + return errorType; + case "SystemError": + this.errno = error.errno; + this.syscall = error.syscall; + this.address = error.address; + this.port = error.port; + this.stack = error.stack; + return errorType; + case "ClientError": + this.bytesParsed = error.bytesParsed; + this.rawPacket = error.rawPacket; + return errorType; + case "SequelizeError": + this.name = error.name; + this.message = error.message; + if (error.errors) { + this.errors = error.errors || []; } - if (this.parent.code) { - this.code = this.parent.code; + if (error.fields) { + this.fields = error.fields; } - } - if (error.sql) { - this.sql = error.sql; - } - if (error.index) { - this.index = error.index; - } - if (error.value) { - this.value = error.value; - } - if (error.table) { - this.table = error.table; - } - if (error.constraint) { - this.constraint = error.constraint; - } - return errorType; - default: - return error.constructor.name; + if (error.parent) { + this.parent = error.parent; + if (this.parent.errno) { + this.errno = this.parent.errno; + } + if (this.parent.code) { + this.code = this.parent.code; + } + } + if (error.sql) { + this.sql = error.sql; + } + if (error.index) { + this.index = error.index; + } + if (error.value) { + this.value = error.value; + } + if (error.table) { + this.table = error.table; + } + if (error.constraint) { + this.constraint = error.constraint; + } + return errorType; + default: + return error.constructor.name; } } if (error && error.constructor) { @@ -216,65 +212,73 @@ class nodefonyError extends Error { return "Error"; } - override toString () { + override toString() { let err = ""; switch (this.errorType) { - case "Error": - if (kernel && kernel.environment === "prod") { - return err; - } - err = `${clc.blue("Name :")} ${this.name} + case "Error": + if (kernel && kernel.environment === "prod") { + return err; + } + err = `${clc.blue("Name :")} ${this.name} ${clc.blue("Type :")} ${this.errorType} ${clc.red("Code :")} ${this.code} ${clc.red("Message :")} ${this.message}`; - break; - case "SystemError": - if (kernel && kernel.environment === "prod") { - return ` ${clc.blue("Type :")} ${this.errorType} ${clc.red(this.message)}`; - } - err = `${clc.blue("Name :")} ${this.name} + break; + case "SystemError": + if (kernel && kernel.environment === "prod") { + return ` ${clc.blue("Type :")} ${this.errorType} ${clc.red( + this.message + )}`; + } + err = `${clc.blue("Name :")} ${this.name} ${clc.blue("Type :")} ${this.errorType} ${clc.red("Message :")} ${this.message} ${clc.red("Ernno :")} ${this.errno} ${clc.blue("Syscall :")} ${this.syscall} ${clc.blue("Address :")} ${this.address} ${clc.blue("Port :")} ${this.port}`; - break; - case "AssertionError": - if (kernel && kernel.environment === "prod") { - return ` ${clc.blue("Type :")} ${this.errorType} ${clc.red(this.message)}`; - } - err = `${clc.blue("Name :")} ${this.name} + break; + case "AssertionError": + if (kernel && kernel.environment === "prod") { + return ` ${clc.blue("Type :")} ${this.errorType} ${clc.red( + this.message + )}`; + } + err = `${clc.blue("Name :")} ${this.name} ${clc.blue("Type :")} ${this.errorType} ${clc.red("Code :")} ${this.code} ${clc.red("Message :")} ${this.message} ${clc.white("Actual :")} ${this.actual} ${clc.white("Expected :")} ${this.expected} ${clc.white("Operator :")} ${this.operator}`; - break; - case "ClientError": - if (kernel && kernel.environment === "prod") { - return ` ${clc.blue("Type :")} ${this.errorType} ${clc.red(this.message)}`; - } - err = `${clc.blue("Name :")} ${this.name} + break; + case "ClientError": + if (kernel && kernel.environment === "prod") { + return ` ${clc.blue("Type :")} ${this.errorType} ${clc.red( + this.message + )}`; + } + err = `${clc.blue("Name :")} ${this.name} ${clc.blue("Type :")} ${this.errorType} ${clc.red("Code :")} ${this.code} ${clc.red("Message :")} ${this.message} ${clc.white("BytesParsed :")} ${this.bytesParsed} ${clc.white("RawPacket :")} ${this.rawPacket}`; - break; - case "SequelizeError": - return nodefony.sequelize.errorToString(this); - case "MongooseError": - return nodefony.mongoose.errorToString(this); - default: - if (kernel && kernel.environment === "prod") { - return ` ${clc.blue("Type :")} ${this.errorType} ${clc.red(this.message)}`; - } - err = `${clc.blue("Name :")} ${this.name} + break; + case "SequelizeError": + return nodefony.sequelize.errorToString(this); + case "MongooseError": + return nodefony.mongoose.errorToString(this); + default: + if (kernel && kernel.environment === "prod") { + return ` ${clc.blue("Type :")} ${this.errorType} ${clc.red( + this.message + )}`; + } + err = `${clc.blue("Name :")} ${this.name} ${clc.blue("Type :")} ${this.errorType} ${clc.red("Message :")} ${this.message}`; - break; + break; } if (kernel.debug) { err += ` @@ -283,45 +287,45 @@ class nodefonyError extends Error { return err; } - parseMessage (message: any) { + parseMessage(message: any) { this.errorType = this.getType(message); switch (nodefony.typeOf(message)) { - case "Error": - if (this.errorType === "SequelizeError") { + case "Error": + if (this.errorType === "SequelizeError") { + break; + } + this.message = message.message; + if (message.code) { + this.code = message.code; + } + this.stack = message.stack; break; - } - this.message = message.message; - if (message.code) { - this.code = message.code; - } - this.stack = message.stack; - break; - case "object": - // Capturing stack trace, excluding constructor call from it. - Error.captureStackTrace(message, this.constructor); - if (message.status) { - this.code = message.status; - } - if (message.code) { - this.code = message.code; - } - try { - if (message.message) { - this.message = message.message; - } else { - // this.message = JSON.stringify(message); - this.message = inspect(message, {depth: 0}); + case "object": + // Capturing stack trace, excluding constructor call from it. + Error.captureStackTrace(message, this.constructor); + if (message.status) { + this.code = message.status; } - } catch (e: any) { - this.error = e; - } - break; - default: - this.getDefaultMessage(); + if (message.code) { + this.code = message.code; + } + try { + if (message.message) { + this.message = message.message; + } else { + // this.message = JSON.stringify(message); + this.message = inspect(message, { depth: 0 }); + } + } catch (e: any) { + this.error = e; + } + break; + default: + this.getDefaultMessage(); } } - getDefaultMessage () { + getDefaultMessage() { if (!this.message && this.code) { const str = this.code.toString(); if (str in STATUS_CODES) { @@ -330,11 +334,11 @@ class nodefonyError extends Error { } } - logger () { + logger() { return console.log(this.toString()); } } Object.defineProperty(nodefonyError.prototype, "toJSON", jsonNodefony); -export default nodefonyError; +export default nodefonyError; diff --git a/src/Event.ts b/src/Event.ts index 95045a5..ea34814 100644 --- a/src/Event.ts +++ b/src/Event.ts @@ -1,13 +1,20 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import {EventEmitter} from "node:events"; -import _ from 'lodash' -const {isEmpty , get, isFunction} = _ +import { EventEmitter } from "node:events"; +import _ from "lodash"; +const { isEmpty, get, isFunction } = _; -declare module 'events' { +declare module "events" { interface EventEmitter { _events: Record; - settingsToListen(localSettings: EventDefaultInterface, context: ContextType): void; - listen(context: ContextType, eventName: string | symbol, listener: (...args: any[]) => void): (...args: any[]) => boolean; + settingsToListen( + localSettings: EventDefaultInterface, + context: ContextType + ): void; + listen( + context: ContextType, + eventName: string | symbol, + listener: (...args: any[]) => void + ): (...args: any[]) => boolean; fire(eventName: string | symbol, ...args: any[]): boolean; emitAsync(type: string | symbol, ...args: any[]): Promise; fireAsync(type: string | symbol, ...args: any[]): Promise; @@ -15,11 +22,11 @@ declare module 'events' { } interface EventDefaultInterface { - [key: string]: any; + [key: string]: any; } interface EventOptionInterface { - nbListeners?: number + nbListeners?: number; [key: string]: any; } @@ -29,8 +36,11 @@ const regListenOn = /^on(.*)$/; const defaultNbListeners = 20; class Event extends EventEmitter { - - constructor (settings?: EventDefaultInterface, context? : ContextType, options?: EventOptionInterface ) { + constructor( + settings?: EventDefaultInterface, + context?: ContextType, + options?: EventOptionInterface + ) { super(); if (options && options.nbListeners) { this.setMaxListeners(options.nbListeners || defaultNbListeners); @@ -40,7 +50,10 @@ class Event extends EventEmitter { } } - override settingsToListen (localSettings: EventDefaultInterface, context?: ContextType ) { + override settingsToListen( + localSettings: EventDefaultInterface, + context?: ContextType + ) { for (const i in localSettings) { const res = regListenOn.exec(i); if (!res) { @@ -54,24 +67,31 @@ class Event extends EventEmitter { } } - override listen(context: ContextType, eventName: string | symbol, listener: (...args: any[]) => void): (...args: any[]) => boolean { + override listen( + context: ContextType, + eventName: string | symbol, + listener: (...args: any[]) => void + ): (...args: any[]) => boolean { const event = eventName; // eslint-disable-next-line @typescript-eslint/no-this-alias const contextClosure = this; - if (typeof listener === 'function') { + if (typeof listener === "function") { this.addListener(eventName, listener.bind(context)); } - return function (this: EventEmitter , ...args: any[]): boolean { + return function (this: EventEmitter, ...args: any[]): boolean { args.unshift(event); return contextClosure.emit(eventName, ...args); }; } override fire(eventName: string | symbol, ...args: any[]): boolean { - return super.emit(eventName, ...args); + return super.emit(eventName, ...args); } - override async emitAsync (eventName: string | symbol, ...args: any[]): Promise { + override async emitAsync( + eventName: string | symbol, + ...args: any[] + ): Promise { const handler = get(this._events, eventName); if (isEmpty(handler) && !isFunction(handler)) { return false; @@ -97,19 +117,19 @@ class Event extends EventEmitter { return tab; } - override async fireAsync (eventName: string | symbol, ...args: any[]) { + override async fireAsync(eventName: string | symbol, ...args: any[]) { return this.emitAsync(eventName, ...args); } } -const create = (settings?: EventDefaultInterface, context? : ContextType, options?: EventOptionInterface) :Event =>{ - return new Event(settings, context, options); -} -const notification = Event +const create = ( + settings?: EventDefaultInterface, + context?: ContextType, + options?: EventOptionInterface +): Event => { + return new Event(settings, context, options); +}; +const notification = Event; -export default Event -export { - notification, - create, - EventDefaultInterface -} \ No newline at end of file +export default Event; +export { notification, create, EventDefaultInterface }; diff --git a/src/FileClass.ts b/src/FileClass.ts index 08065d3..c1843d9 100644 --- a/src/FileClass.ts +++ b/src/FileClass.ts @@ -1,27 +1,26 @@ -import mime from 'mime-types'; +import mime from "mime-types"; import crypto from "node:crypto"; -import path from "node:path" -import fs from 'node:fs' -import {extend} from './Tools' +import path from "node:path"; +import fs from "node:fs"; +import { extend } from "./Tools"; interface FileClassInterface { - path: fs.PathOrFileDescriptor - name: string - ext: string - shortName: string - type: string | undefined - stats: fs.Stats - dirName: string - parse: path.ParsedPath - encoding?: string - mimeType? : string | false - extention? : string | false + path: fs.PathOrFileDescriptor; + name: string; + ext: string; + shortName: string; + type: string | undefined; + stats: fs.Stats; + dirName: string; + parse: path.ParsedPath; + encoding?: string; + mimeType?: string | false; + extention?: string | false; } - const checkPath = function (myPath: string | fs.PathOrFileDescriptor): string { if (!myPath) { - throw new Error(`Bad path`) ; + throw new Error(`Bad path`); } const abs = path.isAbsolute(myPath); if (abs) { @@ -33,14 +32,14 @@ const checkPath = function (myPath: string | fs.PathOrFileDescriptor): string { const regHidden: RegExp = /^\./; const defautWriteOption = { flags: "w", - defaultEncoding: "utf8" + defaultEncoding: "utf8", // mode: 0o666 }; const defaultEncoding = { - encoding:"utf8", - flag: "w", -} + encoding: "utf8", + flag: "w", +}; /* * @@ -49,21 +48,20 @@ const defaultEncoding = { * */ class FileClass { - public stats : fs.Stats - public type : string | undefined - public path : fs.PathOrFileDescriptor - public parse : path.ParsedPath - public name : string - public shortName : string - public ext: string - public mimeType : string | false = false - public encoding : string = "UTF-8" - public extention : string | false = false - public dirName : string - public match : RegExpExecArray | null = null + public stats: fs.Stats; + public type: string | undefined; + public path: fs.PathOrFileDescriptor; + public parse: path.ParsedPath; + public name: string; + public shortName: string; + public ext: string; + public mimeType: string | false = false; + public encoding: string = "UTF-8"; + public extention: string | false = false; + public dirName: string; + public match: RegExpExecArray | null = null; - - constructor (Path: string | fs.PathOrFileDescriptor) { + constructor(Path: string | fs.PathOrFileDescriptor) { if (Path) { Path = checkPath(Path); this.stats = fs.lstatSync(Path); @@ -88,14 +86,14 @@ class FileClass { } else { throw new Error(`error fileClass Path : ${Path}`); } - } + } - toString () { + toString() { return JSON.stringify(this.toJson(), null, "\n"); } - toJson () : FileClassInterface { - const obj : FileClassInterface= { + toJson(): FileClassInterface { + const obj: FileClassInterface = { path: this.path, name: this.name, ext: this.ext, @@ -103,7 +101,7 @@ class FileClass { type: this.type, stats: this.stats, dirName: this.dirName, - parse: this.parse + parse: this.parse, }; if (this.type === "File") { obj.encoding = this.encoding; @@ -113,7 +111,7 @@ class FileClass { return obj; } - checkType () : string | undefined{ + checkType(): string | undefined { if (this.stats.isDirectory()) { return "Directory"; } @@ -137,34 +135,36 @@ class FileClass { } } - getType () : string | undefined{ + getType(): string | undefined { return this.checkType(); } - checkSum (type: string, hasOption?:crypto.HashOptions ) : string{ + checkSum(type: string, hasOption?: crypto.HashOptions): string { if (!type) { type = "md5"; } - return crypto.createHash(type, hasOption).update(this.content()) + return crypto + .createHash(type, hasOption) + .update(this.content()) .digest("hex"); } - getMimeType (name: string) : string | false{ + getMimeType(name: string): string | false { return mime.lookup(name || this.name); } - getExtension (mimeType: string | false) : string | false{ - if( mimeType){ - return mime.extension(mimeType); + getExtension(mimeType: string | false): string | false { + if (mimeType) { + return mime.extension(mimeType); } return mime.extension(this.mimeType); } - getRealpath (Path: string, options: fs.EncodingOption= {}) { + getRealpath(Path: string, options: fs.EncodingOption = {}) { return fs.realpathSync(Path, options); } - matchName (ele: RegExp | string): boolean | RegExpExecArray | null{ + matchName(ele: RegExp | string): boolean | RegExpExecArray | null { if (ele instanceof RegExp) { this.match = ele.exec(this.name); return this.match; @@ -175,37 +175,41 @@ class FileClass { return false; } - matchType (type: string) : boolean{ + matchType(type: string): boolean { return type === this.type; } - isFile () : boolean{ + isFile(): boolean { return this.type === "File"; } - isDirectory () : boolean{ + isDirectory(): boolean { return this.type === "Directory"; } - isSymbolicLink () : boolean{ + isSymbolicLink(): boolean { return this.type === "symbolicLink"; } - dirname () { + dirname() { return path.dirname(this.path); } - isHidden () : boolean{ + isHidden(): boolean { return regHidden.test(this.name); } - content (encoding?: string) : string | Buffer{ - const encode : fs.ObjectEncodingOptions = extend({}, defaultEncoding, {encoding}) + content(encoding?: string): string | Buffer { + const encode: fs.ObjectEncodingOptions = extend({}, defaultEncoding, { + encoding, + }); return fs.readFileSync(this.path, encode); } - read (encoding?: string): string | Buffer { - const encode : fs.ObjectEncodingOptions = extend({}, defaultEncoding, {encoding}) + read(encoding?: string): string | Buffer { + const encode: fs.ObjectEncodingOptions = extend({}, defaultEncoding, { + encoding, + }); if (this.type === "symbolicLink") { const Path = fs.readlinkSync(this.path, encode); return fs.readFileSync(Path, encode); @@ -213,35 +217,42 @@ class FileClass { return fs.readFileSync(this.path, encode); } - readAsync (encoding?: string) : Promise{ - const encode : fs.ObjectEncodingOptions = extend({}, defaultEncoding, {encoding}) + readAsync(encoding?: string): Promise { + const encode: fs.ObjectEncodingOptions = extend({}, defaultEncoding, { + encoding, + }); if (this.type === "symbolicLink") { return new Promise((resolve, reject) => { const Path = fs.readlinkSync(this.path, encode); - try{ - return resolve (fs.readFileSync(Path, encode)) - }catch(e){ + try { + return resolve(fs.readFileSync(Path, encode)); + } catch (e) { return reject(e); } }); } - return new Promise((resolve, reject) =>{ - fs.readFile(this.path, (err: NodeJS.ErrnoException| null , data:Buffer): void=>{ - if (err) { - return reject(err) + return new Promise((resolve, reject) => { + fs.readFile( + this.path, + (err: NodeJS.ErrnoException | null, data: Buffer): void => { + if (err) { + return reject(err); + } + return resolve(data); } - return resolve(data) - }) - }) + ); + }); } - readByLine (callback: (line: string, n: number) => void, encoding: string) { + readByLine(callback: (line: string, n: number) => void, encoding: string) { return new Promise((resolve, reject) => { let res = null; try { res = this.content(encoding); let nb = 0; - res.toString().split("\n") + res + .toString() + .split("\n") .forEach((line: string) => { callback(line, ++nb); }); @@ -252,19 +263,22 @@ class FileClass { }); } - write (data: string | NodeJS.ArrayBufferView, options:fs.WriteFileOptions) :void { + write( + data: string | NodeJS.ArrayBufferView, + options: fs.WriteFileOptions + ): void { fs.writeFileSync(this.path, data, extend({}, defautWriteOption, options)); } - move (target: fs.PathLike) : FileClass { + move(target: fs.PathLike): FileClass { fs.renameSync(this.path, target); return new FileClass(target); } - unlink () : void{ + unlink(): void { fs.unlinkSync(this.path); } } -export default FileClass -export {FileClassInterface} +export default FileClass; +export { FileClassInterface }; diff --git a/src/Kernel.ts b/src/Kernel.ts index a246604..c9d193a 100644 --- a/src/Kernel.ts +++ b/src/Kernel.ts @@ -1,38 +1,35 @@ //import Syslog from "./syslog/Syslog" //import nodefony from "./Nodefony" -import Service from './Service' +import Service from "./Service"; -enum environment { +enum environment { "dev", "development", "prod", "production", - "stage" + "stage", } -enum type{ +enum type { "cli", - "server" + "server", } -type DebugType = boolean | string | string[] -type environmentType = keyof typeof environment -type typeType = keyof typeof type - -class Kernel extends Service{ - type: typeType = "server" - console: boolean = this.isCli() - environment: environmentType = "production" - debug : DebugType = false - - constructor(){ - super("KERNEL") +type DebugType = boolean | string | string[]; +type environmentType = keyof typeof environment; +type typeType = keyof typeof type; + +class Kernel extends Service { + type: typeType = "server"; + console: boolean = this.isCli(); + environment: environmentType = "production"; + debug: DebugType = false; + + constructor() { + super("KERNEL"); } isCli() { return this.type === "cli"; } - } - - -export default Kernel \ No newline at end of file +export default Kernel; diff --git a/src/Nodefony.ts b/src/Nodefony.ts index f4a4f9a..f027891 100644 --- a/src/Nodefony.ts +++ b/src/Nodefony.ts @@ -1,13 +1,13 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ // Nodefony.ts -import Kernel from './Kernel'; -import Container from './Container'; -import Syslog from './syslog/Syslog'; -import Error from './Error' -import Service from './Service' -import Command from './command/Command' -import Cli from './Cli' -import Event from './Event' +import Kernel from "./Kernel"; +import Container from "./Container"; +import Syslog from "./syslog/Syslog"; +import Error from "./Error"; +import Service from "./Service"; +import Command from "./command/Command"; +import Cli from "./Cli"; +import Event from "./Event"; import { extend, isEmptyObject, @@ -18,93 +18,88 @@ import { typeOf, isFunction, isArray, - isPromise } from './Tools' -import {version} from '../package.json'; + isPromise, +} from "./Tools"; +import { version } from "../package.json"; //import { createRequire } from "module"; //const require = createRequire(import.meta.url); //const {version} = require("../package.json"); -enum Environment { +enum Environment { "dev", "development", "prod", "production", - "stage" + "stage", } -type EnvironmentType = keyof typeof Environment -type DebugType = boolean | string | string[] - +type EnvironmentType = keyof typeof Environment; +type DebugType = boolean | string | string[]; class Nodefony { - private static instance: Nodefony ; + private static instance: Nodefony; version: string; static Container = Container; - public Container: typeof Container = Container; + public Container: typeof Container = Container; static Command = Command; - public Command: typeof Command = Command; + public Command: typeof Command = Command; public static Kernel = Kernel; - public Kernel: typeof Kernel = Kernel; - public static kernel: Kernel ; - public kernel: Kernel | null = Nodefony.kernel; + public Kernel: typeof Kernel = Kernel; + public static kernel: Kernel; + public kernel: Kernel | null = Nodefony.kernel; static Error = Error; - public Error: typeof Error = Error; + public Error: typeof Error = Error; static Syslog = Syslog; - public Syslog: typeof Syslog = Syslog; + public Syslog: typeof Syslog = Syslog; static Service = Service; - public Service: typeof Service = Service; + public Service: typeof Service = Service; static Event = Event; public Event: typeof Event = Event; static Cli = Cli; - public Cli: typeof Cli = Cli; - - public extend : typeof extend = extend; - public isEmptyObject : typeof isEmptyObject = isEmptyObject; - public isPlainObject : typeof isPlainObject = isPlainObject; - public isUndefined : typeof isUndefined = isUndefined; - public isRegExp : typeof isRegExp = isRegExp; - public isContainer : typeof isContainer = isContainer; - public typeOf : typeof typeOf = typeOf; - public isFunction : typeof isFunction = isFunction; - public isArray : typeof isArray = isArray; - public isPromise : typeof isPromise = isPromise; - - public sequelize : any = null - public mongoose : any = null + public Cli: typeof Cli = Cli; + + public extend: typeof extend = extend; + public isEmptyObject: typeof isEmptyObject = isEmptyObject; + public isPlainObject: typeof isPlainObject = isPlainObject; + public isUndefined: typeof isUndefined = isUndefined; + public isRegExp: typeof isRegExp = isRegExp; + public isContainer: typeof isContainer = isContainer; + public typeOf: typeof typeOf = typeOf; + public isFunction: typeof isFunction = isFunction; + public isArray: typeof isArray = isArray; + public isPromise: typeof isPromise = isPromise; + + public sequelize: any = null; + public mongoose: any = null; private constructor() { - this.version = version + this.version = version; } - public static getInstance(): Nodefony { + public static getInstance(): Nodefony { if (!Nodefony.instance) { - Nodefony.instance = new Nodefony() + Nodefony.instance = new Nodefony(); } return Nodefony.instance; } - public static getKernel(): Kernel { + public static getKernel(): Kernel { if (!Nodefony.kernel) { - Nodefony.kernel = new Kernel() + Nodefony.kernel = new Kernel(); } return Nodefony.kernel; } } -const nodefony = Nodefony.getInstance() -const kernel = Nodefony.getKernel() - -export default nodefony -export { - kernel, - EnvironmentType, - DebugType -} +const nodefony = Nodefony.getInstance(); +const kernel = Nodefony.getKernel(); +export default nodefony; +export { kernel, EnvironmentType, DebugType }; diff --git a/src/Service.ts b/src/Service.ts index bebb783..a90c626 100644 --- a/src/Service.ts +++ b/src/Service.ts @@ -1,47 +1,63 @@ /* eslint-disable @typescript-eslint/ban-types */ /* eslint-disable @typescript-eslint/no-explicit-any */ -import Container, {DynamicParam} from "./Container" -import Event , {EventDefaultInterface} from "./Event" -import Pdu, {Severity, Msgid, Message, } from './syslog/Pdu' -import Syslog ,{SyslogDefaultSettings, conditionsInterface } from "./syslog/Syslog"; -import {EnvironmentType, DebugType} from './Nodefony' - -export interface DefaultOptions extends EventDefaultInterface{ +import Container, { DynamicParam } from "./Container"; +import Event, { EventDefaultInterface } from "./Event"; +import Pdu, { Severity, Msgid, Message } from "./syslog/Pdu"; +import Syslog, { + SyslogDefaultSettings, + conditionsInterface, +} from "./syslog/Syslog"; +import { EnvironmentType, DebugType } from "./Nodefony"; + +interface DefaultOptionsService extends EventDefaultInterface { events?: { nbListeners: number; - } - syslog? :SyslogDefaultSettings + }; + syslog?: SyslogDefaultSettings; } -const defaultOptions: DefaultOptions = { +const defaultOptions = { events: { - nbListeners: 20 - } + nbListeners: 20, + }, }; -const settingsSyslog : SyslogDefaultSettings = { +const settingsSyslog: SyslogDefaultSettings = { moduleName: "SERVICE ", - defaultSeverity: "INFO" + defaultSeverity: "INFO", }; class Service { public name: string; - public options: DefaultOptions; + public options: DefaultOptionsService; public container: Container | null | undefined; private kernel: any; // Remplacez ce type par le type réel de kernel si possible private syslog: Syslog | null; private settingsSyslog: SyslogDefaultSettings | null; - public notificationsCenter: Event | undefined | boolean ; - - constructor(name: string, container?: Container, notificationsCenter?: Event | false, options: DefaultOptions = {}) { + public notificationsCenter: Event | undefined | boolean; + + constructor( + name: string, + container?: Container, + notificationsCenter?: Event | false, + options: DefaultOptionsService = {} + ) { this.name = name; - this.container = container instanceof Container ? container : new Container(); - this.options = notificationsCenter === false ? { ...options } : { ...defaultOptions, ...options }; + this.container = + container instanceof Container ? container : new Container(); + this.options = + notificationsCenter === false + ? { ...options } + : { ...defaultOptions, ...options }; this.kernel = this.container.get("kernel"); this.syslog = this.container.get("syslog") || null; if (!this.syslog) { - this.settingsSyslog = { ...settingsSyslog, moduleName: this.name, ...(this.options.syslog || {}) }; + this.settingsSyslog = { + ...settingsSyslog, + moduleName: this.name, + ...(this.options.syslog || {}), + }; this.syslog = new Syslog(this.settingsSyslog); this.container.set("syslog", this.syslog); } else { @@ -58,7 +74,9 @@ class Service { } } else { if (notificationsCenter) { - throw new Error("Service nodefony notificationsCenter not valid, must be an instance of nodefony.Events"); + throw new Error( + "Service nodefony notificationsCenter not valid, must be an instance of nodefony.Events" + ); } if (notificationsCenter !== false) { this.notificationsCenter = new Event(this.options, this, this.options); @@ -72,11 +90,14 @@ class Service { } } } - delete this.options.events; } - initSyslog(environment: EnvironmentType = "production", debug: DebugType= false, options?: conditionsInterface ) { + initSyslog( + environment: EnvironmentType = "production", + debug: DebugType = false, + options?: conditionsInterface + ) { return this.syslog ? this.syslog.init(environment, debug, options) : null; } @@ -93,7 +114,7 @@ class Service { this.kernel = null; } - log(pci: any, severity?: Severity, msgid?: Msgid , msg?: Message ) : Pdu { + log(pci: any, severity?: Severity, msgid?: Msgid, msg?: Message): Pdu { try { if (!msgid) { msgid = this.name; @@ -101,164 +122,215 @@ class Service { if (this.syslog) { return this.syslog.log(pci, severity, msgid, msg); } - return new Pdu(pci, severity, msg) + return new Pdu(pci, severity, msg); } catch (e) { console.log(severity, msgid, msg, " : ", pci); console.warn(e); - return new Pdu(e, 'ERROR', msgid, msg) + return new Pdu(e, "ERROR", msgid, msg); } } logger(pci: any, ...args: any[]) { - return console.debug(Syslog.wrapper(this.log(pci, "DEBUG")).text, pci, ...args); + return console.debug( + Syslog.wrapper(this.log(pci, "DEBUG")).text, + pci, + ...args + ); } trace(pci: any, ...args: any[]) { - return console.trace(Syslog.wrapper(this.log(pci, "DEBUG")).text, pci, ...args); + return console.trace( + Syslog.wrapper(this.log(pci, "DEBUG")).text, + pci, + ...args + ); } spinlog(message: string) { return this.log(message, "SPINNER"); } - eventNames() : (string | symbol)[] { - if( this.notificationsCenter){ - return (this.notificationsCenter).eventNames(); + eventNames(): (string | symbol)[] { + if (this.notificationsCenter) { + return (this.notificationsCenter).eventNames(); } - throw new Error(`notificationsCenter not initialized`) + throw new Error(`notificationsCenter not initialized`); } - fire( eventName: string | symbol, ...args: any[]) : boolean{ - if( this.notificationsCenter){ - return (this.notificationsCenter).emit(eventName, ...args); - } - throw new Error(`notificationsCenter not initialized`) + fire(eventName: string | symbol, ...args: any[]): boolean { + if (this.notificationsCenter) { + return (this.notificationsCenter).emit(eventName, ...args); + } + throw new Error(`notificationsCenter not initialized`); } - fireAsync(eventName: string | symbol, ...args: any[]) : Promise { - if( this.notificationsCenter){ - return (this.notificationsCenter).emitAsync(eventName, ...args); + fireAsync(eventName: string | symbol, ...args: any[]): Promise { + if (this.notificationsCenter) { + return (this.notificationsCenter).emitAsync(eventName, ...args); } - throw new Error(`notificationsCenter not initialized`) + throw new Error(`notificationsCenter not initialized`); } - emit(eventName: string | symbol, ...args: any[]) : boolean { - if( this.notificationsCenter){ - return (this.notificationsCenter).emit(eventName, ...args); - } - throw new Error(`notificationsCenter not initialized`) + emit(eventName: string | symbol, ...args: any[]): boolean { + if (this.notificationsCenter) { + return (this.notificationsCenter).emit(eventName, ...args); + } + throw new Error(`notificationsCenter not initialized`); } - emitAsync(eventName: string | symbol, ...args: any[]) : Promise { - if( this.notificationsCenter){ - return (this.notificationsCenter).emitAsync(eventName, ...args); - } - throw new Error(`notificationsCenter not initialized`) + emitAsync(eventName: string | symbol, ...args: any[]): Promise { + if (this.notificationsCenter) { + return (this.notificationsCenter).emitAsync(eventName, ...args); + } + throw new Error(`notificationsCenter not initialized`); } - addListener(eventName: string | symbol , listener: (...args: any[]) => void) : NodeJS.EventEmitter { - if( this.notificationsCenter){ + addListener( + eventName: string | symbol, + listener: (...args: any[]) => void + ): NodeJS.EventEmitter { + if (this.notificationsCenter) { return (this.notificationsCenter).addListener(eventName, listener); - } - throw new Error(`notificationsCenter not initialized`) + } + throw new Error(`notificationsCenter not initialized`); } - listen(eventName: string | symbol , listener: (...args: any[]) => void) { - if( this.notificationsCenter){ - return (this.notificationsCenter).listen(this, eventName, listener); - } - throw new Error(`notificationsCenter not initialized`) + listen(eventName: string | symbol, listener: (...args: any[]) => void) { + if (this.notificationsCenter) { + return (this.notificationsCenter).listen( + this, + eventName, + listener + ); + } + throw new Error(`notificationsCenter not initialized`); } - on(eventName: string | symbol , listener: (...args: any[]) => void) : NodeJS.EventEmitter{ - if( this.notificationsCenter){ + on( + eventName: string | symbol, + listener: (...args: any[]) => void + ): NodeJS.EventEmitter { + if (this.notificationsCenter) { return (this.notificationsCenter).on(eventName, listener); - } - throw new Error(`notificationsCenter not initialized`) + } + throw new Error(`notificationsCenter not initialized`); } - once(eventName: string | symbol , listener: (...args: any[]) => void) : NodeJS.EventEmitter { - if( this.notificationsCenter){ + once( + eventName: string | symbol, + listener: (...args: any[]) => void + ): NodeJS.EventEmitter { + if (this.notificationsCenter) { return (this.notificationsCenter).once(eventName, listener); - } - throw new Error(`notificationsCenter not initialized`) + } + throw new Error(`notificationsCenter not initialized`); } - off(eventName: string | symbol , listener: (...args: any[]) => void) : NodeJS.EventEmitter { - if( this.notificationsCenter){ + off( + eventName: string | symbol, + listener: (...args: any[]) => void + ): NodeJS.EventEmitter { + if (this.notificationsCenter) { return (this.notificationsCenter).off(eventName, listener); - } - throw new Error(`notificationsCenter not initialized`) + } + throw new Error(`notificationsCenter not initialized`); } settingsToListen(localSettings: EventDefaultInterface, context: any) { - if( this.notificationsCenter){ - return (this.notificationsCenter).settingsToListen(localSettings, context); - } - throw new Error(`notificationsCenter not initialized`) + if (this.notificationsCenter) { + return (this.notificationsCenter).settingsToListen( + localSettings, + context + ); + } + throw new Error(`notificationsCenter not initialized`); } setMaxListeners(n: number) { - if( this.notificationsCenter){ - return (this.notificationsCenter).setMaxListeners(n); - } - throw new Error(`notificationsCenter not initialized`) - } - - removeListener(eventName: string | symbol, listener: (...args: any[]) => void) : NodeJS.EventEmitter{ - if( this.notificationsCenter){ - return (this.notificationsCenter).removeListener(eventName,listener); - } - throw new Error(`notificationsCenter not initialized`) + if (this.notificationsCenter) { + return (this.notificationsCenter).setMaxListeners(n); + } + throw new Error(`notificationsCenter not initialized`); + } + + removeListener( + eventName: string | symbol, + listener: (...args: any[]) => void + ): NodeJS.EventEmitter { + if (this.notificationsCenter) { + return (this.notificationsCenter).removeListener( + eventName, + listener + ); + } + throw new Error(`notificationsCenter not initialized`); } removeAllListeners(eventName?: string | symbol) { - if( this.notificationsCenter){ - return (this.notificationsCenter).removeAllListeners(eventName); - } - throw new Error(`notificationsCenter not initialized`) - } - - prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): NodeJS.EventEmitter { - if( this.notificationsCenter){ - return (this.notificationsCenter).prependOnceListener(eventName,listener ); - } - throw new Error(`notificationsCenter not initialized`) - } - - prependListener(eventName: string | symbol, listener: (...args: any[]) => void) : NodeJS.EventEmitter { - if( this.notificationsCenter){ - return (this.notificationsCenter).prependListener(eventName,listener); - } - throw new Error(`notificationsCenter not initialized`) - } - - getMaxListeners() : number{ - if( this.notificationsCenter){ - return (this.notificationsCenter).getMaxListeners(); - } - throw new Error(`notificationsCenter not initialized`) + if (this.notificationsCenter) { + return (this.notificationsCenter).removeAllListeners(eventName); + } + throw new Error(`notificationsCenter not initialized`); + } + + prependOnceListener( + eventName: string | symbol, + listener: (...args: any[]) => void + ): NodeJS.EventEmitter { + if (this.notificationsCenter) { + return (this.notificationsCenter).prependOnceListener( + eventName, + listener + ); + } + throw new Error(`notificationsCenter not initialized`); + } + + prependListener( + eventName: string | symbol, + listener: (...args: any[]) => void + ): NodeJS.EventEmitter { + if (this.notificationsCenter) { + return (this.notificationsCenter).prependListener( + eventName, + listener + ); + } + throw new Error(`notificationsCenter not initialized`); } - listenerCount(eventName: string | symbol, listener?: Function | undefined) : number{ - if( this.notificationsCenter){ - return (this.notificationsCenter).listenerCount(eventName, listener); - } - throw new Error(`notificationsCenter not initialized`) + getMaxListeners(): number { + if (this.notificationsCenter) { + return (this.notificationsCenter).getMaxListeners(); + } + throw new Error(`notificationsCenter not initialized`); + } + + listenerCount( + eventName: string | symbol, + listener?: Function | undefined + ): number { + if (this.notificationsCenter) { + return (this.notificationsCenter).listenerCount( + eventName, + listener + ); + } + throw new Error(`notificationsCenter not initialized`); } - listeners(eventName: string | symbol) : Function[] { - if( this.notificationsCenter){ - return (this.notificationsCenter).listeners(eventName); - } - throw new Error(`notificationsCenter not initialized`) + listeners(eventName: string | symbol): Function[] { + if (this.notificationsCenter) { + return (this.notificationsCenter).listeners(eventName); + } + throw new Error(`notificationsCenter not initialized`); } - rawListeners(eventName: string | symbol): Function[] { - if( this.notificationsCenter){ - return (this.notificationsCenter).rawListeners(eventName); - } - throw new Error(`notificationsCenter not initialized`) + rawListeners(eventName: string | symbol): Function[] { + if (this.notificationsCenter) { + return (this.notificationsCenter).rawListeners(eventName); + } + throw new Error(`notificationsCenter not initialized`); } get(name: string) { @@ -282,24 +354,24 @@ class Service { return false; } - getParameters(name: string) : DynamicParam | null { + getParameters(name: string): DynamicParam | null { return (this.container).getParameters(name); } - setParameters(name: string, ele: T) : DynamicParam | null { - if( this.container){ - return (this.container).setParameters(name,ele ); + setParameters(name: string, ele: T): DynamicParam | null { + if (this.container) { + return (this.container).setParameters(name, ele); } - throw new Error(`container not initialized`) + throw new Error(`container not initialized`); } - has (name: string) : boolean { - if( this.container){ - return this.container.has(name); - } - return false + has(name: string): boolean { + if (this.container) { + return this.container.has(name); + } + return false; } - } -export default Service \ No newline at end of file +export default Service; +export { DefaultOptionsService }; diff --git a/src/Tools.ts b/src/Tools.ts index 6a73cc7..235bd11 100644 --- a/src/Tools.ts +++ b/src/Tools.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import Container from "./Container"; -import _ from 'lodash'; +import Container from "./Container"; +import _ from "lodash"; const { isArray, isFunction, isRegExp } = _; const myobj = {}; const hasOwn = myobj.hasOwnProperty; @@ -8,37 +8,43 @@ const fnToString = hasOwn.toString; const ObjectFunctionString = fnToString.call(Object); const getProto = Object.getPrototypeOf; - const isPlainObject = (obj: any): boolean => { if (!obj || toString.call(obj) !== "[object Object]") { return false; } - const proto : any= getProto(obj); + const proto: any = getProto(obj); if (!proto) { return true; } const Ctor: any = hasOwn.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString; + return ( + typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString + ); }; -const isUndefined = (value: any) :boolean => { +const isUndefined = (value: any): boolean => { return value === undefined; -} - -const isEmptyObject = (obj: any) :boolean => { +}; + +const isEmptyObject = (obj: any): boolean => { let name; for (name in obj) { return false; } return true; -} +}; -const extend= (...args: any[])=> { - let options, name, src, copy, copyIsArray, clone, +const extend = (...args: any[]) => { + let options, + name, + src, + copy, + copyIsArray, + clone, target = args[0] || {}, i = 1, deep = false; - const {length} = args + const { length } = args; // Handle a deep copy situation if (typeof target === "boolean") { @@ -69,8 +75,11 @@ const extend= (...args: any[])=> { continue; } // Recurse if we're merging plain objects or arrays - if (deep && copy && (isPlainObject(copy) || - (copyIsArray = Array.isArray(copy)))) { + if ( + deep && + copy && + (isPlainObject(copy) || (copyIsArray = Array.isArray(copy))) + ) { src = target[name]; // Ensure proper type for the source value if (copyIsArray && !Array.isArray(src)) { @@ -92,74 +101,78 @@ const extend= (...args: any[])=> { } // Return the modified object return target; -} +}; /** - * @method typeOf - * @param value - * @return {String} type of value - */ - const typeOf = (value: any): string | null=> { - const t = typeof value; - if (t === "object") { - if (value === null) { - return null; - } - if (Buffer.isBuffer(value)) { - return "buffer"; - } - if (isArray(value)) { - return "array"; - } - if (isFunction(value)) { - return "function"; - } - if (value instanceof Date) { - return "date"; - } - if (isRegExp(value)) { - return "RegExp"; - } - if (value.callee) { - return "arguments"; - } - if (value instanceof SyntaxError) { - return "SyntaxError"; - } - if (isError(value)) { - return "Error"; - } - } else if (t === "function" && typeof value.call === "undefined") { - return "object"; + * @method typeOf + * @param value + * @return {String} type of value + */ +const typeOf = (value: any): string | null => { + const t = typeof value; + if (t === "object") { + if (value === null) { + return null; + } + if (Buffer.isBuffer(value)) { + return "buffer"; + } + if (isArray(value)) { + return "array"; } - return t; + if (isFunction(value)) { + return "function"; + } + if (value instanceof Date) { + return "date"; + } + if (isRegExp(value)) { + return "RegExp"; + } + if (value.callee) { + return "arguments"; + } + if (value instanceof SyntaxError) { + return "SyntaxError"; + } + if (isError(value)) { + return "Error"; + } + } else if (t === "function" && typeof value.call === "undefined") { + return "object"; } + return t; +}; - const isContainer = (container: Container) :boolean => { - if (container) { - if (container instanceof Container) { - return true; - } - return false; +const isContainer = (container: Container): boolean => { + if (container) { + if (container instanceof Container) { + return true; } return false; } + return false; +}; - const isError = (it: Error) : boolean=> { - return it instanceof Error - } +const isError = (it: Error): boolean => { + return it instanceof Error; +}; - const isPromise = (obj: any): boolean => { - switch (true) { +const isPromise = (obj: any): boolean => { + switch (true) { case obj instanceof Promise: - //case obj instanceof BlueBird: + //case obj instanceof BlueBird: return true; default: - return Boolean(obj) && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; - } + return ( + Boolean(obj) && + (typeof obj === "object" || typeof obj === "function") && + typeof obj.then === "function" + ); } +}; -export { +export { extend, isEmptyObject, isPlainObject, @@ -169,5 +182,5 @@ export { typeOf, isFunction, isArray, - isPromise -} \ No newline at end of file + isPromise, +}; diff --git a/src/command/Builder.ts b/src/command/Builder.ts index a36907b..ee05898 100644 --- a/src/command/Builder.ts +++ b/src/command/Builder.ts @@ -1,17 +1,17 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import path from "node:path" -import Service from '../Service' -import Container from '../Container' -import Event from '../Event' -import Command from './Command' -import {extend, typeOf} from "../Tools" -import FileClass from '../FileClass' -import File from '../finder/File' -import Cli from '../Cli' -import { PathLike } from "node:fs" -import fs from 'node:fs' -import twig from 'twig' -import shelljs from 'shelljs' +import path from "node:path"; +import Service from "../Service"; +import Container from "../Container"; +import Event from "../Event"; +import Command from "./Command"; +import { extend, typeOf } from "../Tools"; +import FileClass from "../FileClass"; +import File from "../finder/File"; +import Cli from "../Cli"; +import { PathLike } from "node:fs"; +import fs from "node:fs"; +import twig from "twig"; +import shelljs from "shelljs"; interface SymlinkParams { source: string; @@ -22,87 +22,112 @@ interface CopyParams { recurse?: boolean; } -type FileType = "file" | "directory" | "copy" | "symlink" +type FileType = "file" | "directory" | "copy" | "symlink"; interface BuilderObject { - name: string - type: FileType - path?: string | PathLike - skeleton?: string | PathLike - params?: SymlinkParams | CopyParams | fs.MakeDirectoryOptions |Record - chmod?: string | number - parse?: boolean - childs?: BuilderObject[] + name: string; + type: FileType; + path?: string | PathLike; + skeleton?: string | PathLike; + params?: + | SymlinkParams + | CopyParams + | fs.MakeDirectoryOptions + | Record; + chmod?: string | number; + parse?: boolean; + childs?: BuilderObject[]; } - const twigOptions = { views: process.cwd(), "twig options": { async: false, - cache: false - } + cache: false, + }, }; -class Builder extends Service{ +class Builder extends Service { public force: boolean = false; - public command : Command | undefined - public cli : Cli | undefined | null - public response : Record = {} - public debug : boolean = false - public interactive : boolean = false - public location : string = process.cwd() - private twig : typeof twig = twig; - constructor(command: Command ){ - super("Builder", command?.container, command?.notificationsCenter) - this.command = command - this.getCliOptions() - + public command: Command | undefined; + public cli: Cli | undefined | null; + public response: Record = {}; + public debug: boolean = false; + public interactive: boolean = false; + public location: string = process.cwd(); + private twig: typeof twig = twig; + constructor(command: Command) { + super( + "Builder", + command?.container, + command?.notificationsCenter + ); + this.command = command; + this.getCliOptions(); } - private getCliOptions(): void{ - this.cli = this.command?.cli - this.debug = this.cli?.commander?.opts().debug - this.interactive = this.cli?.commander?.opts().interactive - this.response = extend(true, {}, this.cli?.response) + private getCliOptions(): void { + this.cli = this.command?.cli; + this.debug = this.cli?.commander?.opts().debug; + this.interactive = this.cli?.commander?.opts().interactive; + this.response = extend(true, {}, this.cli?.response || {}); } - run(): void{ - + async run(...args: any[]): Promise { + return Promise.resolve(args); } - setLocation (location: string | FileClass) { + generate(response: Record, force: boolean = false) { + return new Promise((resolve, reject) => { + try { + // if (this.createBuilder) { + // this.build(this.createBuilder(response), this.location, force); + // return resolve(this.cli?.response); + // } + return resolve(this.cli?.response); + } catch (e) { + return reject(e); + } + }); + } + + setLocation(location: string | FileClass) { if (location instanceof FileClass) { - return this.location = location.path; + return (this.location = location.path); } - return this.location = path.resolve(location); + return (this.location = path.resolve(location)); } - async removeInteractivePath (file: string) : Promise { - if( !this.command){ - throw new Error(`Command not found`) + async removeInteractivePath(file: string): Promise { + if (!this.command) { + throw new Error(`Command not found`); } - return this.command.prompts.confirm({ - message: `Do You Want Remove : ${file}?`, - default: false - }) - .then((response) => { - if (response) { - if (! fs.existsSync(file)) { - throw `${file} not exist`; - } + return this.command.prompts + .confirm({ + message: `Do You Want Remove : ${file}?`, + default: false, + }) + .then((response) => { + if (response) { + if (!fs.existsSync(file)) { + throw `${file} not exist`; + } shelljs.rm("-rf", file); return response; - } - return response; - }) - .catch((e) => { - throw e; - }); + } + return response; + }) + .catch((e) => { + throw e; + }); } - buildSkeleton(skeleton: string | FileClass, parse: boolean, data:Record) : Promise { - let skelete = null; + buildSkeleton( + skeleton: string | FileClass, + parse: boolean, + data: Record + ): Promise { + let skelete = null; return new Promise((resolve, reject) => { try { if (skeleton instanceof FileClass) { @@ -113,24 +138,34 @@ class Builder extends Service{ if (skelete.type === "File") { if (parse === true) { data.settings = twigOptions; - this.twig.renderFile((skelete).path as string, data, (error, result) => { - if (error) { - return reject(error); + this.twig.renderFile( + (skelete).path as string, + data, + (error, result) => { + if (error) { + return reject(error); + } + return resolve(result); } - return resolve(result); - }); + ); } else { - fs.readFile(skelete.path, { - encoding: "utf8" - }, (error, result) => { - if (error) { - return reject(error); + fs.readFile( + skelete.path, + { + encoding: "utf8", + }, + (error, result) => { + if (error) { + return reject(error); + } + return resolve(result); } - return resolve(result); - }); + ); } } else { - const error = new Error(` skeleton must be file !!! : ${skelete.path}`); + const error = new Error( + ` skeleton must be file !!! : ${skelete.path}` + ); return reject(error); } } catch (e) { @@ -140,169 +175,196 @@ class Builder extends Service{ } async build( - obj: BuilderObject | BuilderObject[], - parent: FileClass | string | File = new File(process.cwd()), - force: boolean = false -): Promise { - let child: FileClass | File | null = null; - //const result = null - try { - if (parent) { - if( ! (parent instanceof File) ){ - if(parent instanceof FileClass ){ - parent = new File(parent.path); - }else{ - parent = new File(parent); + obj: BuilderObject | BuilderObject[], + parent: FileClass | string | File = new File(process.cwd()), + force: boolean = false + ): Promise { + let child: FileClass | File | null = null; + try { + if (parent) { + if (!(parent instanceof File)) { + if (parent instanceof FileClass) { + parent = new File(parent.path); + } else { + parent = new File(parent); + } } } - } - - switch (typeOf(obj)) { - case "array": { - const elements = obj as BuilderObject[]; - for (const element of elements) { - const res = await this.build(element, parent, force); - if(parent && res){ - //(parent as File).childrens.push(res) + switch (typeOf(obj)) { + case "array": { + const elements = obj as BuilderObject[]; + for (const element of elements) { + const res = await this.build(element, parent, force); + if (parent && res) { + //(parent as File).childrens.push(res) + } } + break; } - break; - } - case "object": { - const myobj = obj as BuilderObject; - let name = ""; - for (const [key, value] of Object.entries(myobj)) { - switch (key) { - case "name": - name = value as string; - break; - case "type":{ - switch (value as FileType) { - case "directory":{ - const directoryPath = path.resolve( - (parent as File)?.path as string, - name - ); - child = await this.createDirectory( - directoryPath, - myobj.params as fs.MakeDirectoryOptions || {mode: 0o755}, - force - ) - .catch(e=>{ - throw e - }); - if(parent){ - (parent as File).childrens.push(child) + case "object": { + const myobj = obj as BuilderObject; + let name = ""; + for (const [key, value] of Object.entries(myobj)) { + switch (key) { + case "name": + name = value as string; + break; + case "type": { + switch (value as FileType) { + case "directory": { + const directoryPath = path.resolve( + (parent as File)?.path as string, + name + ); + child = await this.createDirectory( + directoryPath, + (myobj.params as fs.MakeDirectoryOptions) || { + mode: 0o755, + }, + force + ).catch((e) => { + throw e; + }); + if (parent) { + (parent as File).childrens.push(child); + } + if (force) { + this.log(`Force Create Directory: ${child?.name}`); + } else { + this.log(`Create Directory: ${child?.name}`); + } + break; } - if (force) { - this.log(`Force Create Directory: ${child?.name}`); - } else { - this.log(`Create Directory: ${child?.name}`); - } - break; - } - case "file":{ - const filePath = path.resolve( - (parent as FileClass)?.path as string, - name - ); - await this.createFile( - filePath, - myobj.skeleton as string, - myobj.parse, - myobj.params as SymlinkParams - ); - this.log(`Create File: ${filePath}`); - if (myobj.chmod) { - shelljs.chmod((myobj.chmod as string) || 644, filePath) + case "file": { + const filePath = path.resolve( + (parent as FileClass)?.path as string, + name + ); + await this.createFile( + filePath, + myobj.skeleton as string, + myobj.parse, + myobj.params as SymlinkParams + ); + this.log(`Create File: ${filePath}`); + if (myobj.chmod) { + shelljs.chmod((myobj.chmod as string) || 644, filePath); + } + child = new File(filePath, parent); + if (parent) { + (parent as File).childrens.push(child); + } + break; } - child = new File(filePath, parent) - if(parent){ - (parent as File).childrens.push(child) + case "symlink": { + const symlinkParams = myobj.params as SymlinkParams; + const parentPath = (parent as FileClass).path as string; + const sourcePath = path.resolve( + parentPath, + symlinkParams.source + ); + const destPath = path.resolve( + parentPath, + symlinkParams.dest + ); + const symlinkArgs = force + ? ["-sf", sourcePath, destPath] + : ["-s", sourcePath, destPath]; + shelljs.ln(...(symlinkArgs as [string, string, string])); + this.log(`Create symbolic link: ${myobj.name}`); + child = new File(destPath, parent); + if (parent) { + (parent as File).childrens.push(child); + } + break; } - break; - } - case "symlink":{ - const symlinkParams = myobj.params as SymlinkParams; - const parentPath = (parent as FileClass).path as string; - const sourcePath = path.resolve(parentPath, symlinkParams.source); - const destPath = path.resolve(parentPath, symlinkParams.dest); - const symlinkArgs = force ? ["-sf", sourcePath, destPath] : ["-s", sourcePath, destPath]; - shelljs.ln(...(symlinkArgs as [string, string, string])) - this.log(`Create symbolic link: ${myobj.name}`); - child = new File(destPath, parent) - if(parent){ - (parent as File).childrens.push(child) + case "copy": { + const copyParams = myobj.params as CopyParams; + const copyFilePath = path.resolve( + (parent as FileClass).path as string, + name + ); + const copyArgs = copyParams.recurse + ? ["-R", myobj.path as string, copyFilePath] + : ["-f", myobj.path as string, copyFilePath]; + shelljs.cp(...(copyArgs as [string, string, string])); + this.log(`Copy: ${myobj.name}`); + if (myobj.chmod) { + shelljs.chmod( + (myobj.chmod as string) || 0o644, + copyFilePath + ); + } + child = new File(copyFilePath, parent); + if (parent) { + (parent as File).childrens.push(child); + } + break; } - break; } - case "copy":{ - const copyParams = myobj.params as CopyParams; - const copyFilePath = path.resolve( - (parent as FileClass).path as string, - name - ); - const copyArgs = copyParams.recurse ? ["-R", myobj.path as string, copyFilePath] : ["-f", myobj.path as string, copyFilePath]; - shelljs.cp(...(copyArgs as [string, string, string])) - this.log(`Copy: ${myobj.name}`); - if (myobj.chmod) { - shelljs.chmod((myobj.chmod as string) || 0o644, copyFilePath) - } - child = new File(copyFilePath, parent) - if(parent){ - (parent as File).childrens.push(child) - } - break; - } + break; } - break; + case "childs": + await this.build( + value as BuilderObject[], + child as FileClass, + force + ); + break; } - case "childs": - await this.build(value as BuilderObject[], child as FileClass, force); - break; } + break; } - break; + default: + this.log("generate build error arguments: ", "ERROR"); } - default: - this.log("generate build error arguments: ", "ERROR"); + } catch (e) { + this.log(e, "ERROR"); + throw e; } - } catch (e) { - this.log(e, "ERROR"); - throw e; + return Promise.resolve(child as File); } - return Promise.resolve(child as File); -} -createFile ( - myPath: string , - skeleton: string, - parse: boolean = true, - params: Record = {} ) : File | Promise { + createFile( + myPath: string, + skeleton: string, + parse: boolean = true, + params: Record = {} + ): File | Promise { return new Promise((resolve, reject) => { if (skeleton) { return this.buildSkeleton(skeleton, parse, params) .then((file) => { - fs.writeFile(myPath, file, { - mode: params.mode || "644" - }, (err) => { - if (err) { - return reject(err); + fs.writeFile( + myPath, + file, + { + mode: params.mode || "644", + }, + (err) => { + if (err) { + return reject(err); + } + return resolve(new File(myPath)); } - return resolve(new File(myPath)); - }); + ); }) .catch((e: Error) => reject(e)); } const data = ""; - fs.writeFile(myPath, data, { - mode: params.mode || "644" - }, (err) => { - if (err) { - return reject(err); + fs.writeFile( + myPath, + data, + { + mode: params.mode || "644", + }, + (err) => { + if (err) { + return reject(err); + } + return resolve(new File(myPath)); } - return resolve(new File(myPath)); - }); + ); }); } @@ -310,28 +372,22 @@ createFile ( myPath: fs.PathLike, mode?: fs.MakeDirectoryOptions | fs.Mode | null, force: boolean = false - ): Promise { - try { - await fs.promises.mkdir(myPath, mode); - return new File(myPath); - } catch (e: any) { - switch (e.code) { - case "EEXIST": - if (force) { - return new File(myPath); - } - break; - } - throw e + ): Promise { + try { + await fs.promises.mkdir(myPath, mode); + return new File(myPath); + } catch (e: any) { + switch (e.code) { + case "EEXIST": + if (force) { + return new File(myPath); + } + break; } + throw e; } - } +} -export default Builder -export { - FileType, - SymlinkParams, - CopyParams, - BuilderObject -} \ No newline at end of file +export default Builder; +export { FileType, SymlinkParams, CopyParams, BuilderObject }; diff --git a/src/command/Command.ts b/src/command/Command.ts index 5fdb7ba..e91835d 100644 --- a/src/command/Command.ts +++ b/src/command/Command.ts @@ -1,139 +1,255 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import Service from '../Service' -import Container from "../Container" -import Event from '../Event' -import { Severity, Msgid, Message} from '../syslog/Pdu' -import Cli from '../Cli' -import {Command as Cmd, program, Option, Argument} from 'commander' -//import { Command as Program, program, Option } from '@commander-js/extra-typings'; -import Builder from './Builder' -import * as prompts from '@inquirer/prompts'; +import Service, { DefaultOptionsService } from "../Service"; +import Container from "../Container"; +import Event from "../Event"; +import { Severity, Msgid, Message } from "../syslog/Pdu"; +import Cli from "../Cli"; +import commander, { + Command as Cmd, + program, + Option, + Argument, +} from "commander"; +import Builder from "./Builder"; +import * as prompts from "@inquirer/prompts"; +import { extend } from "../Tools"; +import clui from "clui"; -class Command extends Service { +interface OptionsCommandInterface extends DefaultOptionsService { + progress?: boolean; + sizeProgress?: number; + showBanner?: boolean; +} + +const defaultCommandOptions: OptionsCommandInterface = { + progress: false, + sizeProgress: 100, + showBanner: true, +}; - public cli : Cli | undefined | null = undefined - private command: Cmd | null = null - private program : typeof program = program - public json : boolean = false - public debug : boolean = false - public interactive : boolean = false - public builder : Builder| null = null - public prompts : typeof prompts = prompts - constructor(name: string , description?: string, cli?: Cli){ - const container: undefined | Container | null = cli?.container - const notificationsCenter = cli?.notificationsCenter - const options = cli?.options - super(name, container, notificationsCenter , options) - if( cli ){ - this.cli = cli +class Command extends Service { + public cli: Cli | undefined | null = undefined; + private command: Cmd | null = null; + private program: typeof program = program; + public json: boolean = false; + public debug: boolean = false; + public interactive: boolean = false; + public builder: Builder | null = null; + public prompts: typeof prompts = prompts; + public progress: number = 0; + public response: Record = {}; + constructor( + name: string, + description?: string, + cli?: Cli, + options?: OptionsCommandInterface + ) { + const container: undefined | Container | null = cli?.container; + const notificationsCenter = cli?.notificationsCenter; + const myoptions: OptionsCommandInterface = extend( + {}, + defaultCommandOptions, + options + ); + super( + name, + container, + notificationsCenter, + myoptions + ); + if (cli) { + this.cli = cli; } - this.addCommand(name, description) - this.command?.action(this.action.bind(this)) + this.addCommand(name, description); + this.command?.action(this.action.bind(this)); } - private getCliOptions(): void{ - this.debug = this.cli?.commander?.opts().debug - this.interactive = this.cli?.commander?.opts().interactive + private async action(...args: any[]): Promise { + this.getCliOptions(); + if (this.options.showBanner) { + await this.showBanner(); + } + if (this.cli) { + if (this.options.progress) { + this.progress = 0; + this.setProgress(); + } + if (this.builder) { + await this.builder.run(...args); + } + await this.run(...args); + } else { + this.program.parse(); + } + if (this.options.progress) { + this.fire("onProgress", this.options.sizeProgress); + } } - private addCommand(name: string, description?: string): Cmd{ - this.command = new Cmd(name); - if( description){ - this.command.description(description) + public async run(...args: any[]): Promise { + if (this.interactive) { + return this.interaction(...args) + .then((...response) => this.generate(...response)) + .catch((e) => { + throw e; + }); } - return this.program.addCommand(this.command) + return this.generate(...args).catch((e) => { + throw e; + }); + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public async interaction(...args: any[]): Promise { + //console.log(`interaction`, ...args) + //const answer = await this.prompts.confirm({ message: 'Continue?' }); + return Promise.resolve(this.response); } - public addBuilder(builder: typeof Builder): Builder{ - return this.builder = new builder(this) + async generate(...args: any[]): Promise { + return Promise.resolve(args); + // let i: NodeJS.Timeout + // return new Promise ((resolve, reject)=>{ + // //return resolve(args) + // i = setInterval(()=>{ + // this.progress++ + // this.fire("onProgress") + // if( this.progress === this.options.sizeProgress ){ + // //console.log("pass clean :", i) + // clearInterval(i) + // return resolve(args); + // } + // }, 100) + // }) } - public parse(argv?: string[]): this { - this.program.parse(argv) - return this + private getCliOptions(): void { + this.debug = this.cli?.commander?.opts().debug; + this.interactive = this.cli?.commander?.opts().interactive; } - async action(...args: any[]): Promise{ - // console.log(`action`, ...args) - this.getCliOptions() - await this.showBanner() - if(this.cli){ - await this.run(...args) - }else{ - this.program.parse() + private addCommand(name: string, description?: string): Cmd { + this.command = new Cmd(name); + if (description) { + this.command.description(description); } + return this.program.addCommand(this.command); } - async run (...args: any[]) : Promise{ - //console.log(`run`, ...args) - if (this.interactive) { - return this.interaction(...args) - .then((...response) => this.generate(...response)) - .catch((e) => { - throw e; - }); + public addBuilder(builder: typeof Builder): Builder { + return (this.builder = new builder(this)); + } + + public parse(argv?: string[], options?: commander.ParseOptions): Cmd { + if (this.program) { + return this.program?.parse(argv, options); } - return this.generate(...args) - .catch((e) => { - throw e; - }); + throw new Error(`program not found`); } - async generate (...args: any[]) : Promise { - //console.log(`generate`, ...args) - if(this.builder){ - console.log("pass") + private clearCommand(): void { + if (this.cli) { + this.cli.clearCommand(); + } else { + while (process.argv.length > 2) { + process.argv.pop(); + } } - return Promise.resolve(args); } - async interaction (...args: any[]): Promise{ - //console.log(`interaction`, ...args) - //const answer = await this.prompts.confirm({ message: 'Continue?' }); - return Promise.resolve([...args]); + runCommand(cmd: string, args: any[] = []): Cmd { + this.clearCommand(); + if (cmd) { + process.argv.push(cmd); + } + return this.parse(process.argv.concat(args)); + } + + public setProgress( + size: number = this.options.sizeProgress + ): Promise { + if (!this.cli || this.json) { + return Promise.resolve(null); + } + return new Promise((resolve, reject) => { + try { + this.log(`START PROGRESS : ${this.cli?.getEmoji("clapper")}`); + const pg = this.cli?.createProgress(size); + pg?.update(++this.progress, size); + this.on("onProgress", (step?: number) => { + let res = null; + if (step) { + this.progress = step; + res = pg?.update(this.progress, this.options.sizeProgress); + } else { + res = pg?.update(++this.progress, this.options.sizeProgress); + } + this.log(res, "SPINNER"); + if ( + this.progress === this.options.sizeProgress || + this.progress > this.options.sizeProgress + ) { + this.progress = this.options.sizeProgress; + this.fire("onProgressEnd", pg); + } + }); + this.on("onProgressEnd", () => { + this.cli?.blankLine(); + this.log( + `\u001b[13pEND PROGRESS : ${this.cli?.getEmoji("checkered_flag")}` + ); + this.removeAllListeners("onProgress"); + this.removeAllListeners("onProgressEnd"); + }); + return resolve(pg); + } catch (e) { + return reject(e); + } + }); } - addOption(flags: string, description?: string | undefined) : Option{ - if( this.command ){ - const opt = new Option(flags, description) - this.command.addOption(opt) - return opt + addOption(flags: string, description?: string | undefined): Option { + if (this.command) { + const opt = new Option(flags, description); + this.command.addOption(opt); + return opt; } - throw new Error(`Commander not ready`) + throw new Error(`Commander not ready`); } - addArgument(arg: string, description?: string | undefined): Argument{ - if( this.command ){ - const Arg = new Argument(arg, description) - this.command.addArgument(Arg) - return Arg + addArgument(arg: string, description?: string | undefined): Argument { + if (this.command) { + const Arg = new Argument(arg, description); + this.command.addArgument(Arg); + return Arg; } - throw new Error(`Command not ready`) + throw new Error(`Command not ready`); } - async showBanner () : Promise { - if( this.cli ){ - return this.cli.asciify(` ${this.name}`) - .then((data) => { - if (this.json) { - return data; - } - if( this.cli ){ - if( this.cli.options.clear){ - this.cli.clear(); + async showBanner(): Promise { + if (this.cli) { + return this.cli + .asciify(` ${this.name}`) + .then((data) => { + if (this.json) { + return data; + } + if (this.cli) { + if (this.cli.options.clear) { + this.cli.clear(); + } + const color = this.cli.clc.blueBright.bold; + console.log(color(data)); + this.cli.blankLine(); } - const color = this.cli.clc.blueBright.bold; - console.log(color(data)); - this.cli.blankLine(); - } - return data; - }) - .catch((e) => e); + return data; + }) + .catch((e) => e); } - return Promise.resolve("") + return Promise.resolve(""); } - override logger (pci: any, severity: Severity , msgid: Msgid , msg: Message) { + override logger(pci: any, severity: Severity, msgid: Msgid, msg: Message) { try { if (!msgid) { msgid = `COMMAND ${this.name}`; @@ -142,7 +258,9 @@ class Command extends Service { } catch (e) { console.log(e, "\n", pci); } - } + } } -export default Command +export default Command; + +export { OptionsCommandInterface }; diff --git a/src/finder/File.ts b/src/finder/File.ts index 422e7fe..868144e 100644 --- a/src/finder/File.ts +++ b/src/finder/File.ts @@ -1,28 +1,30 @@ -import FileClass, {FileClassInterface} from '../FileClass' -import FileResult from './FileResult' -import fs from 'node:fs' +import FileClass, { FileClassInterface } from "../FileClass"; +import FileResult from "./FileResult"; +import fs from "node:fs"; interface FileInterface extends FileClassInterface { childrens?: string; - parent?: FileInterface + parent?: FileInterface; } class File extends FileClass { + public parent: File | null = null; + public childrens: FileResult = new FileResult(); - public parent : File | null = null - public childrens : FileResult = new FileResult() - - constructor (path: string | fs.PathOrFileDescriptor, parent :File | null = null) { + constructor( + path: string | fs.PathOrFileDescriptor, + parent: File | null = null + ) { super(path); this.parent = parent; } - get length () : number{ + get length(): number { return this.childrens.length; } - override toJson () : FileInterface{ - const obj : FileInterface= { + override toJson(): FileInterface { + const obj: FileInterface = { path: this.path, name: this.name, ext: this.ext, @@ -30,7 +32,7 @@ class File extends FileClass { type: this.type, stats: this.stats, dirName: this.dirName, - parse: this.parse + parse: this.parse, }; if (this.type === "File") { obj.encoding = this.encoding; @@ -38,7 +40,7 @@ class File extends FileClass { obj.extention = this.extention; } obj.childrens = this.childrens.toJson(); - obj.parent = this.parent?.toJson() + obj.parent = this.parent?.toJson(); return obj; } } diff --git a/src/finder/FileResult.ts b/src/finder/FileResult.ts index 0e83f25..0a6bb7e 100644 --- a/src/finder/FileResult.ts +++ b/src/finder/FileResult.ts @@ -1,17 +1,15 @@ /* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */ /* eslint-disable @typescript-eslint/no-explicit-any */ -import Result from './Result' -import File from './File' - +import Result from "./Result"; +import File from "./File"; class FileResult extends Result { - - constructor (res?: File[] | undefined) { + constructor(res?: File[] | undefined) { super(res); //Array.prototype.find } - override toString () : string { + override toString(): string { let txt = ""; for (let index = 0; index < this.length; index++) { const info = this[index]; @@ -20,35 +18,38 @@ class FileResult extends Result { return txt; } - override toJson (json :any[]= []) : string{ + override toJson(json: any[] = []): string { for (let index = 0; index < this.length; index++) { - const info :File = this[index]; + const info: File = this[index]; switch (info.type) { - case "File": - json.push(info.toJson()); - break; - case "symbolicLink": - case "Directory":{ - const dir = info.toJson(); - if (info.childrens) { - dir.childrens = info.childrens.toJson(); + case "File": + json.push(info.toJson()); + break; + case "symbolicLink": + case "Directory": { + const dir = info.toJson(); + if (info.childrens) { + dir.childrens = info.childrens.toJson(); + } + json.push(dir); + break; } - json.push(dir); - break; - } } } return JSON.stringify(json); } - uniq () { + uniq() { return this; } - override find (predicate: (value: any, index: number, obj: any[]) => value is S, result : FileResult = new FileResult()) : FileResult { + override find( + predicate: (value: any, index: number, obj: any[]) => value is S, + result: FileResult = new FileResult() + ): FileResult { for (let index = 0; index < this.length; index++) { const info: File = this[index]; - const unknownType : unknown= predicate + const unknownType: unknown = predicate; const match = info.matchName(unknownType); if (match) { result.push(info); @@ -58,39 +59,39 @@ class FileResult extends Result { return result.uniq(); } - getDirectories (result :FileResult = new FileResult()) :FileResult { + getDirectories(result: FileResult = new FileResult()): FileResult { for (let index = 0; index < this.length; index++) { const info: File = this[index]; switch (info.type) { - case "Directory": - result.push(info); - info.childrens.getDirectories(result); - break; - case "symbolicLink": - info.childrens.getDirectories(result); - break; + case "Directory": + result.push(info); + info.childrens.getDirectories(result); + break; + case "symbolicLink": + info.childrens.getDirectories(result); + break; } } return result; } - getFiles (result :FileResult = new FileResult()) : FileResult{ + getFiles(result: FileResult = new FileResult()): FileResult { for (let index = 0; index < this.length; index++) { - const info :File= this[index]; + const info: File = this[index]; switch (info.type) { - case "File": - result.push(info); - break; - case "symbolicLink": - case "Directory": - info.childrens.getFiles(result); - break; + case "File": + result.push(info); + break; + case "symbolicLink": + case "Directory": + info.childrens.getFiles(result); + break; } } return result; } - sortByName (result : FileResult = new FileResult()) : FileResult{ + sortByName(result: FileResult = new FileResult()): FileResult { const res = this.sort((a, b) => { if (a.name.toString() > b.name.toString()) { return 1; @@ -102,12 +103,12 @@ class FileResult extends Result { }); if (res) { const unknownResult: unknown = result.concat(res); - return unknownResult; + return unknownResult; } return this; } - sortByType (result = new FileResult()) : FileResult{ + sortByType(result = new FileResult()): FileResult { const res = this.sort((a, b) => { if (a.type.toString() > b.type.toString()) { return 1; @@ -125,4 +126,4 @@ class FileResult extends Result { } } -export default FileResult +export default FileResult; diff --git a/src/finder/Finder.ts b/src/finder/Finder.ts index 4625aa1..64c22fd 100644 --- a/src/finder/Finder.ts +++ b/src/finder/Finder.ts @@ -1,40 +1,40 @@ /* eslint-disable no-async-promise-executor */ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { promises as fsPromises } from 'fs'; -import Event from '../Event' -import {extend, typeOf} from '../Tools' -import FileResult from './FileResult' -import File from './File' -import FileClass from '../FileClass' -import Result from './Result'; -import path from 'node:path' -import fs from 'node:fs' -import _ from 'lodash'; -const { isNull} = _; +import { promises as fsPromises } from "fs"; +import Event from "../Event"; +import { extend, typeOf } from "../Tools"; +import FileResult from "./FileResult"; +import File from "./File"; +import FileClass from "../FileClass"; +import Result from "./Result"; +import path from "node:path"; +import fs from "node:fs"; +import _ from "lodash"; +const { isNull } = _; -interface DefaultSettingsInterface{ - recurse?: boolean - depth?: number - seeHidden?: boolean - match?: RegExp | string | null - exclude?: string|RegExp|null - excludeFile?: string|RegExp|null - excludeDir?: string|RegExp|null - followSymLink?: boolean - matchFile?: string - matchDir?: string +interface DefaultSettingsInterface { + recurse?: boolean; + depth?: number; + seeHidden?: boolean; + match?: RegExp | string | null; + exclude?: string | RegExp | null; + excludeFile?: string | RegExp | null; + excludeDir?: string | RegExp | null; + followSymLink?: boolean; + matchFile?: string; + matchDir?: string; } interface TotalInterface { - Directory: number - File: number - BlockDevice: number - CharacterDevice: number - symbolicLink: number - Fifo: number - Socket: number - hidden: number + Directory: number; + File: number; + BlockDevice: number; + CharacterDevice: number; + symbolicLink: number; + Fifo: number; + Socket: number; + hidden: number; [key: string]: number; } @@ -46,7 +46,7 @@ const defaultSettings: DefaultSettingsInterface = { exclude: null, excludeFile: null, excludeDir: null, - followSymLink: false + followSymLink: false, }; const checkExclude = function (info: File, options: DefaultSettingsInterface) { @@ -80,13 +80,18 @@ const checkExclude = function (info: File, options: DefaultSettingsInterface) { return false; }; -const checkMatch = function (this: Finder, info: File, options: DefaultSettingsInterface= {}, result: Result) { +const checkMatch = function ( + this: Finder, + info: File, + options: DefaultSettingsInterface = {}, + result: Result +) { let match = false; - let rec : string | undefined = undefined; + let rec: string | undefined = undefined; const test = options.matchFile || options.matchDir || options.match; if (!test) { result.push(info); - if( info.type) { + if (info.type) { this.totals[info.type]++; this.fire(`on${info.type}`, info, this); } @@ -128,21 +133,28 @@ const checkMatch = function (this: Finder, info: File, options: DefaultSettingsI return true; } switch (rec) { - // false match - case "Directory": - case "symbolicLink": - result.push(info); - this.totals[info.type]++; - this.fire(`on${info.type}`, info, this); - return true; - default: - // false file - // console.log("bypass ", info.name) - return false; + // false match + case "Directory": + case "symbolicLink": + result.push(info); + this.totals[info.type]++; + this.fire(`on${info.type}`, info, this); + return true; + default: + // false file + // console.log("bypass ", info.name) + return false; } }; -const parser = function (this: Finder ,file: FileClass, result = new FileResult(), options : DefaultSettingsInterface, depth :number| null = null, parent : File | null= null) { +const parser = function ( + this: Finder, + file: FileClass, + result = new FileResult(), + options: DefaultSettingsInterface, + depth: number | null = null, + parent: File | null = null +) { return new Promise(async (resolve, reject) => { if (depth === 0) { return resolve(result); @@ -151,17 +163,19 @@ const parser = function (this: Finder ,file: FileClass, result = new FileResult( if (parent) { parent.childrens = result; } - + try { if (file.type !== "symbolicLink") { - res = await fsPromises.readdir(file.path, { - encoding: "utf8", - withFileTypes: false - }) + res = await fsPromises + .readdir(file.path, { + encoding: "utf8", + withFileTypes: false, + }) .catch((e) => reject(e)); } else if (options.followSymLink) { // console.log("symbolicLink First", file.name) - res = await fsPromises.readlink(file.path) + res = await fsPromises + .readlink(file.path) .catch((e) => reject(e)); } // console.log(res) @@ -183,7 +197,10 @@ const parser = function (this: Finder ,file: FileClass, result = new FileResult( let symLink = null; if (info.type === "symbolicLink" && options.followSymLink) { try { - const read = path.resolve(info.dirName, await fsPromises.readlink(info.path)); + const read = path.resolve( + info.dirName, + await fsPromises.readlink(info.path) + ); symLink = new File(read, info); } catch (e) { this.fire("onError", e, this); @@ -210,20 +227,29 @@ const parser = function (this: Finder ,file: FileClass, result = new FileResult( } // console.log("RECCCCCC", info.type, info.name) switch (info.type) { - case "Directory":{ - const myDeph : null | number = isNull(depth) ? null : depth - 1 - await parser.call(this, info, undefined, options, myDeph, info); - break; - } - case "symbolicLink": - if (symLink) { - if (symLink.isDirectory()) { - // info.children = await parser.call(this, symLink, undefined, options, depth - 1, info); - const myDeph : null | number = isNull(depth) ? null : depth - 1 - await parser.call(this, symLink, undefined, options, myDeph, info); - } + case "Directory": { + const myDeph: null | number = isNull(depth) ? null : depth - 1; + await parser.call(this, info, undefined, options, myDeph, info); + break; } - break; + case "symbolicLink": + if (symLink) { + if (symLink.isDirectory()) { + // info.children = await parser.call(this, symLink, undefined, options, depth - 1, info); + const myDeph: null | number = isNull(depth) + ? null + : depth - 1; + await parser.call( + this, + symLink, + undefined, + options, + myDeph, + info + ); + } + } + break; } } } @@ -237,13 +263,12 @@ const parser = function (this: Finder ,file: FileClass, result = new FileResult( }; class Finder extends Event { + public settings: DefaultSettingsInterface; + public totals: TotalInterface; - public settings : DefaultSettingsInterface - public totals : TotalInterface - - constructor (settings: DefaultSettingsInterface) { + constructor(settings: DefaultSettingsInterface) { super(settings); - this.settings = extend({}, defaultSettings, settings || {}); + this.settings = extend({}, defaultSettings, settings || {}); this.totals = { Directory: 0, File: 0, @@ -252,40 +277,45 @@ class Finder extends Event { symbolicLink: 0, Fifo: 0, Socket: 0, - hidden: 0 + hidden: 0, }; } - clean () { + clean() { this.removeAllListeners(); for (const total in this.totals) { this.totals[total] = 0; } } - ckeckPath (Path: string | FileClass | string[]) :Result{ + ckeckPath(Path: string | FileClass | string[]): Result { const type = typeOf(Path); const result = new FileResult(); switch (true) { - case type === "string": - result.push(new File(Path)); - return result; - case type === "array":{ - const length: number = (Path).length - for (let i = 0; i < length; i++) { - result.push(new File((Path)[i])); + case type === "string": + result.push(new File(Path)); + return result; + case type === "array": { + const length: number = (Path).length; + for (let i = 0; i < length; i++) { + result.push(new File((Path)[i])); + } + return result; } - return result; - } - case Path instanceof FileClass: - result.push(new File((Path).path)); - return result; - default: - throw new Error(`Bad Path type: ${type} Accept only String, Array or fileClass`); + case Path instanceof FileClass: + result.push(new File((Path).path)); + return result; + default: + throw new Error( + `Bad Path type: ${type} Accept only String, Array or fileClass` + ); } } - async in (Path: string | FileClass | string[], settings = {}) : Promise{ + async in( + Path: string | FileClass | string[], + settings = {} + ): Promise { let result = null; try { result = this.ckeckPath(Path); @@ -305,6 +335,4 @@ class Finder extends Event { } export default Finder; -export { - TotalInterface -} +export { TotalInterface }; diff --git a/src/finder/Result.ts b/src/finder/Result.ts index 7f02ebb..38e5af4 100644 --- a/src/finder/Result.ts +++ b/src/finder/Result.ts @@ -2,8 +2,7 @@ import { Severity } from "../syslog/Pdu"; /* eslint-disable @typescript-eslint/no-explicit-any */ class Result extends Array { - - constructor (res? : any[]) { + constructor(res?: any[]) { if (res) { if (res instanceof Array) { super(); @@ -21,7 +20,7 @@ class Result extends Array { } } - toJson (json: any[] = []) : string{ + toJson(json: any[] = []): string { for (let index = 0; index < this.length; index++) { const ele = this[index]; json.push(ele); @@ -29,15 +28,15 @@ class Result extends Array { return JSON.stringify(json); } - override toString (json : any[]= []) : string{ + override toString(json: any[] = []): string { for (let index = 0; index < this.length; index++) { - const ele : any= this[index]; + const ele: any = this[index]; json.push(ele); } return JSON.stringify(json, null, "\n"); } - clean (callback?: (ele: any)=> void) { + clean(callback?: (ele: any) => void) { if (callback) { Array.prototype.forEach.call(this, (ele: any) => { return callback(ele); @@ -46,28 +45,38 @@ class Result extends Array { this.length = 0; } - query (query: string, logger: boolean = false, options = {}, sevrity : Severity = "INFO", clean: boolean = false) : Result{ - const res = new Result(this.filter((data: Result) => { + query( + query: string, + logger: boolean = false, + options = {}, + sevrity: Severity = "INFO", + clean: boolean = false + ): Result { + const res = new Result( + this.filter((data: Result) => { const res = data.query(query, logger, options, sevrity); if (res) { return data; } return null; - })); - if (clean) { - this.clean(); - } - return res; + }) + ); + if (clean) { + this.clean(); + } + return res; } - queryGrep (query: string, grep: string, clean: boolean = false): Result { - const res = new Result(this.filter((data: Result) => { - const res = data.queryGrep(query, grep); - if (res) { - return data; - } - return null; - })); + queryGrep(query: string, grep: string, clean: boolean = false): Result { + const res = new Result( + this.filter((data: Result) => { + const res = data.queryGrep(query, grep); + if (res) { + return data; + } + return null; + }) + ); if (clean) { this.clean(); } @@ -75,4 +84,4 @@ class Result extends Array { } } -export default Result +export default Result; diff --git a/src/index.ts b/src/index.ts index c5f4ad0..5a55aca 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,11 +1,10 @@ // index.ts -import nodefony, {kernel} from './Nodefony'; +import nodefony, { kernel } from "./Nodefony"; // Vérifie si module.exports est défini (module CommonJS) -if (typeof module !== 'undefined' && module.exports) { +if (typeof module !== "undefined" && module.exports) { // Exporte directement l'objet nodefony module.exports = nodefony; -} +} export default nodefony; -export { kernel , nodefony}; - +export { kernel, nodefony }; diff --git a/src/syslog/Pdu.ts b/src/syslog/Pdu.ts index bb06a4e..e765093 100644 --- a/src/syslog/Pdu.ts +++ b/src/syslog/Pdu.ts @@ -1,29 +1,29 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import {typeOf} from "../Tools" -export type Pci = any -export type ModuleName = string -export type Message = string -export type Msgid = string -export type PduDate = string | number | Date -export type Status = "NOTDEFINED" | "INVALID"| "ACCEPTED" | "DROPPED" - -type SeverityKeys = keyof typeof SysLogSeverity -type SeverityValues= | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | -1 -export type Severity = SeverityKeys | SeverityValues; +import { typeOf } from "../Tools"; +export type Pci = any; +export type ModuleName = string; +export type Message = string; +export type Msgid = string; +export type PduDate = string | number | Date; +export type Status = "NOTDEFINED" | "INVALID" | "ACCEPTED" | "DROPPED"; + +type SeverityKeys = keyof typeof SysLogSeverity; +type SeverityValues = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | -1; +export type Severity = SeverityKeys | SeverityValues; /* - * Severity syslog - *
-   *    EMERGENCY   = 0
-   *    ALERT       = 1
-   *    CRITIC      = 2
-   *    ERROR       = 3
-   *    WARNING     = 4
-   *    NOTICE      = 5
-   *    INFO        = 6
-   *    DEBUG       = 7
-   * 
- */ + * Severity syslog + *
+ *    EMERGENCY   = 0
+ *    ALERT       = 1
+ *    CRITIC      = 2
+ *    ERROR       = 3
+ *    WARNING     = 4
+ *    NOTICE      = 5
+ *    INFO        = 6
+ *    DEBUG       = 7
+ * 
+ */ enum SysLogSeverity { EMERGENCY = 0, ALERT = 1, @@ -64,7 +64,9 @@ const translateSeverity = function (severity: Severity = "INFO"): number { } }; -const sysLogSeverityObj: Record = Object.entries(SysLogSeverity).reduce( +const sysLogSeverityObj: Record = Object.entries( + SysLogSeverity +).reduce( (acc, [key, value]) => { acc[key as Severity] = value as Severity; return acc; @@ -73,27 +75,26 @@ const sysLogSeverityObj: Record = Object.entries(SysLogSever ); /** - * Protocol Data Unit - * @class PDU - * @constructor - * @module library - * @return {PDU} - */ + * Protocol Data Unit + * @class PDU + * @constructor + * @module library + * @return {PDU} + */ let guid = 0; class Pdu { - - public payload : Pci - public uid : number - public severity : number - public timeStamp : number - public severityName: keyof typeof SysLogSeverity - public typePayload: unknown - public moduleName : ModuleName - public msgid: Msgid - public msg: Message - public status : Status - - constructor ( + public payload: Pci; + public uid: number; + public severity: number; + public timeStamp: number; + public severityName: keyof typeof SysLogSeverity; + public typePayload: unknown; + public moduleName: ModuleName; + public msgid: Msgid; + public msg: Message; + public status: Status; + + constructor( pci: Pci, severity?: Severity, moduleName: ModuleName = "nodefony", @@ -103,7 +104,7 @@ class Pdu { ) { /* timeStamp @type Date*/ this.timeStamp = this.convertToDate(date).getTime(); - + /* uid */ this.uid = ++guid; @@ -111,7 +112,7 @@ class Pdu { this.severity = translateSeverity(severity); /* severityName */ - this.severityName = this.getSeverityName(this.severity) + this.severityName = this.getSeverityName(this.severity); /* typePayload */ this.typePayload = typeOf(pci); @@ -132,9 +133,13 @@ class Pdu { this.status = "NOTDEFINED"; } - private getSeverityName(severity: SysLogSeverity): keyof typeof SysLogSeverity { + private getSeverityName( + severity: SysLogSeverity + ): keyof typeof SysLogSeverity { // Obtenez la clé pour la valeur enum - const keys = Object.keys(SysLogSeverity).filter((key) => SysLogSeverity[key as keyof typeof SysLogSeverity] === severity); + const keys = Object.keys(SysLogSeverity).filter( + (key) => SysLogSeverity[key as keyof typeof SysLogSeverity] === severity + ); if (keys.length === 1) { return keys[0] as keyof typeof SysLogSeverity; @@ -143,7 +148,7 @@ class Pdu { } private convertToDate(value: PduDate): Date { - if (typeof value === 'string' || typeof value === 'number') { + if (typeof value === "string" || typeof value === "number") { return new Date(value); } else if (value instanceof Date) { return value; @@ -152,40 +157,44 @@ class Pdu { } } - static sysLogSeverity () { + static sysLogSeverity() { return sysLogSeverityObj; } - static severityToString (severity: number | string): string | undefined { - const numericSeverity = typeof severity === 'string' ? parseInt(severity, 10) : severity; - if (!isNaN(numericSeverity) && SysLogSeverity[numericSeverity] !== undefined) { + static severityToString(severity: number | string): string | undefined { + const numericSeverity = + typeof severity === "string" ? parseInt(severity, 10) : severity; + if ( + !isNaN(numericSeverity) && + SysLogSeverity[numericSeverity] !== undefined + ) { return SysLogSeverity[numericSeverity]; } - const severityKey = Pdu.severityToString(SysLogSeverity[severity as number]) + const severityKey = Pdu.severityToString( + SysLogSeverity[severity as number] + ); return severityKey !== undefined ? severityKey : undefined; } /** - * Get Date in string format - * @method getDate - * @return {String} a date in string format . - */ - getDate () :string{ + * Get Date in string format + * @method getDate + * @return {String} a date in string format . + */ + getDate(): string { return new Date(this.timeStamp).toTimeString(); } /** - * get a string representating the PDU protocole - * @method toString - * @return {String} . - */ - toString () :string { - return `TimeStamp:${this.getDate() - } Log:${this.payload - } ModuleName:${this.moduleName - } SeverityName:${this.severityName - } MessageID:${this.msgid - } UID:${this.uid + * get a string representating the PDU protocole + * @method toString + * @return {String} . + */ + toString(): string { + return `TimeStamp:${this.getDate()} Log:${this.payload} ModuleName:${ + this.moduleName + } SeverityName:${this.severityName} MessageID:${this.msgid} UID:${ + this.uid } Message:${this.msg}`; } @@ -196,10 +205,8 @@ class Pdu { (this as Record)[key] = value; } }); - return json + return json; } } export default Pdu; - - diff --git a/src/syslog/Syslog.ts b/src/syslog/Syslog.ts index 532b171..a49e517 100644 --- a/src/syslog/Syslog.ts +++ b/src/syslog/Syslog.ts @@ -1,54 +1,57 @@ /* eslint-disable @typescript-eslint/ban-types */ /* eslint-disable @typescript-eslint/no-explicit-any */ import clc from "cli-color"; -import {typeOf, extend} from "../Tools" -import Pdu, {Severity, ModuleName, Msgid, Message} from './Pdu' -import { DebugType, EnvironmentType} from "../Nodefony" -import Event from '../Event' +import { typeOf, extend } from "../Tools"; +import Pdu, { Severity, ModuleName, Msgid, Message } from "./Pdu"; +import { DebugType, EnvironmentType } from "../Nodefony"; +import Event from "../Event"; const yellow = clc.yellow.bold; -const red = clc.red.bold ; +const red = clc.red.bold; const cyan = clc.cyan.bold; const blue = clc.blueBright.bold; -const green = clc.green +const green = clc.green; //type DebugType = boolean | string | string[] -type Operator = "<" | ">" | "<=" | ">=" | "==" | "===" | "!=" | "RegExp" -type Condition = "&&" | "||" -type Data = any +type Operator = "<" | ">" | "<=" | ">=" | "==" | "===" | "!=" | "RegExp"; +type Condition = "&&" | "||"; +type Data = any; interface LogicCondition { - "&&" : (myConditions: ConditionSetting, pdu: Pdu) => boolean; - "||" : (myConditions: ConditionSetting, pdu: Pdu) => boolean; + "&&": (myConditions: ConditionSetting, pdu: Pdu) => boolean; + "||": (myConditions: ConditionSetting, pdu: Pdu) => boolean; } interface Conditions { - severity : (pdu: Pdu, condition: ConditionSetting) => boolean; - msgid : (pdu: Pdu, condition: ConditionSetting) => boolean; - date : (pdu: Pdu, condition: ConditionSetting) => boolean; + severity: (pdu: Pdu, condition: ConditionSetting) => boolean; + msgid: (pdu: Pdu, condition: ConditionSetting) => boolean; + date: (pdu: Pdu, condition: ConditionSetting) => boolean; [key: string]: (pdu: Pdu, condition: ConditionSetting) => boolean; } - interface ConditionSetting { - operator?: Operator - data: Data, +interface ConditionSetting { + operator?: Operator; + data: Data; [key: string]: any; } - interface conditionsInterface { - severity?: ConditionSetting - msgid?: ConditionSetting, - data?: Data - checkConditions?: Condition +interface conditionsInterface { + severity?: ConditionSetting; + msgid?: ConditionSetting; + data?: Data; + checkConditions?: Condition; [key: string]: any; } - interface SyslogDefaultSettings { - moduleName?: ModuleName - msgid?: Msgid - maxStack?: number - rateLimit?: boolean | number - burstLimit?: number - defaultSeverity?: Severity - checkConditions?: Condition - async?: boolean | undefined +interface SyslogDefaultSettings { + moduleName?: ModuleName; + msgid?: Msgid; + maxStack?: number; + rateLimit?: boolean | number; + burstLimit?: number; + defaultSeverity?: Severity; + checkConditions?: Condition; + async?: boolean | undefined; } //type ComparisonOperatorNumber = (ele1: number , ele2: number ) => boolean; -type ComparisonOperator = (ele1: number | string, ele2: number | string | RegExp) => boolean; +type ComparisonOperator = ( + ele1: number | string, + ele2: number | string | RegExp +) => boolean; //type RegExpOperator = (ele1: string, ele2: RegExp) => boolean; interface Operators { "<": ComparisonOperator; @@ -58,61 +61,64 @@ interface Operators { "==": ComparisonOperator; "===": ComparisonOperator; "!=": ComparisonOperator; - "RegExp": ComparisonOperator; + RegExp: ComparisonOperator; } -const formatDebug = function (debug: DebugType) : DebugType { +const formatDebug = function (debug: DebugType): DebugType { switch (typeOf(debug)) { - case "boolean": - return debug; - case "string":{ - if (["false", "undefined", "null"].includes(debug)) { - return false; - } - if (debug === "true" || debug === "*") { - return true; - } - const mytab : string[] = (debug).split(/,| /); - if (mytab[0] === "*") { - return true; - } - return mytab; - } - case "array": - debug = <[]>debug - if (debug[0] === "*") { - return true; + case "boolean": + return debug; + case "string": { + if (["false", "undefined", "null"].includes(debug)) { + return false; + } + if (debug === "true" || debug === "*") { + return true; + } + const mytab: string[] = (debug).split(/,| /); + if (mytab[0] === "*") { + return true; + } + return mytab; } - return debug; - case "undefined": - case "object": - default: - return false; + case "array": + debug = <[]>debug; + if (debug[0] === "*") { + return true; + } + return debug; + case "undefined": + case "object": + default: + return false; } }; -const conditionOptions = function (environment: string , debug : DebugType= false) { +const conditionOptions = function ( + environment: string, + debug: DebugType = false +) { debug = formatDebug(debug); - let obj: conditionsInterface | null = null; + let obj: conditionsInterface | null = null; if (environment === "development") { obj = { severity: { operator: "<=", - data: debug === false ? 6 : 7 - } + data: debug === false ? 6 : 7, + }, }; } else { obj = { severity: { operator: "<=", - data: debug ? 7 : 6 - } + data: debug ? 7 : 6, + }, }; } if (typeof debug === "object") { obj.msgid = { operator: "==", - data: debug + data: debug, }; } return obj; @@ -131,7 +137,7 @@ const conditionOptions = function (environment: string , debug : DebugType= fals * * */ -const defaultSettings : SyslogDefaultSettings = { +const defaultSettings: SyslogDefaultSettings = { moduleName: "SYSLOG", msgid: "", maxStack: 100, @@ -139,7 +145,7 @@ const defaultSettings : SyslogDefaultSettings = { burstLimit: 3, defaultSeverity: "DEBUG", checkConditions: "&&", - async: false + async: false, }; const sysLogSeverity = Pdu.sysLogSeverity(); @@ -152,15 +158,17 @@ const operators: Operators = { "==": (ele1, ele2) => ele1 == ele2, "===": (ele1, ele2) => ele1 === ele2, "!=": (ele1, ele2) => ele1 !== ele2, - "RegExp": (ele1, ele2) => (ele2).test(ele1), + RegExp: (ele1, ele2) => (ele2).test(ele1), }; - -const conditionsObj : Conditions = { +const conditionsObj: Conditions = { severity: (pdu: Pdu, condition: ConditionSetting) => { for (const sev in condition.data) { //console.log("Ope : ", condition.operator, " sev: ",pdu.severity , "contiton : ",condition.data[sev]) - if ( condition.operator && operators[condition.operator](pdu.severity, condition.data[sev]) ){ + if ( + condition.operator && + operators[condition.operator](pdu.severity, condition.data[sev]) + ) { //console.log("passs op" , condition.operator, " sev: ",pdu.severity , "contiton : ",condition.data[sev]) return true; } @@ -169,18 +177,21 @@ const conditionsObj : Conditions = { }, msgid: (pdu: Pdu, condition: ConditionSetting) => { for (const sev in condition.data) { - if( condition.operator && operators[condition.operator](pdu.msgid, sev)){ + if (condition.operator && operators[condition.operator](pdu.msgid, sev)) { return true; } } return false; }, - date: (pdu: Pdu , condition: ConditionSetting) => condition.operator ? operators[condition.operator](pdu.timeStamp, condition.data) : false + date: (pdu: Pdu, condition: ConditionSetting) => + condition.operator + ? operators[condition.operator](pdu.timeStamp, condition.data) + : false, }; -const logicCondition : LogicCondition = { - "&&": (myConditions: ConditionSetting, pdu: Pdu) : boolean => { - let res : boolean = false; +const logicCondition: LogicCondition = { + "&&": (myConditions: ConditionSetting, pdu: Pdu): boolean => { + let res: boolean = false; for (const ele in myConditions) { res = conditionsObj[ele](pdu, myConditions[ele]); if (!res) { @@ -189,8 +200,8 @@ const logicCondition : LogicCondition = { } return res; }, - "||": (myConditions: ConditionSetting, pdu: Pdu) : boolean => { - let res : boolean = false; + "||": (myConditions: ConditionSetting, pdu: Pdu): boolean => { + let res: boolean = false; for (const ele in myConditions) { res = conditionsObj[ele](pdu, myConditions[ele]); if (res) { @@ -198,11 +209,11 @@ const logicCondition : LogicCondition = { } } return res; - } + }, }; -const checkFormatSeverity = (ele: any): string|number[] => { - let res: any[] ; +const checkFormatSeverity = (ele: any): string | number[] => { + let res: any[]; switch (typeof ele) { case "object": if (Array.isArray(ele)) { @@ -212,12 +223,12 @@ const checkFormatSeverity = (ele: any): string|number[] => { } break; case "string": - res = ele.split(/,| /) ; + res = ele.split(/,| /); break; case "number": res = [ele]; break; - default:{ + default: { console.trace(ele); const error = `checkFormatSeverity bad format type : ${typeof ele}`; throw new Error(error); @@ -226,79 +237,87 @@ const checkFormatSeverity = (ele: any): string|number[] => { return res; }; -const checkFormatDate = function (ele: Date | string) : number { - let res : number ; +const checkFormatDate = function (ele: Date | string): number { + let res: number; switch (typeOf(ele)) { - case "date": - res = (ele as Date).getTime(); - break; - case "string": - res = new Date(ele).getTime(); - break; - default: - throw new Error(`checkFormatDate bad format ${typeOf(ele)} : ${ele}`); + case "date": + res = (ele as Date).getTime(); + break; + case "string": + res = new Date(ele).getTime(); + break; + default: + throw new Error(`checkFormatDate bad format ${typeOf(ele)} : ${ele}`); } return res; }; -const checkFormatMsgId = function (ele: any) : RegExp | any[] { - let res : any; +const checkFormatMsgId = function (ele: any): RegExp | any[] { + let res: any; switch (typeOf(ele)) { - case "string": - res = (ele as string).split(/,| /); - break; - case "number": - res = [ele]; - break; - case "RegExp": - res = ele; - break; - case "array": - res = ele; - break; - default: - throw new Error(`checkFormatMsgId bad format ${typeOf(ele)} : ${ele}`); + case "string": + res = (ele as string).split(/,| /); + break; + case "number": + res = [ele]; + break; + case "RegExp": + res = ele; + break; + case "array": + res = ele; + break; + default: + throw new Error(`checkFormatMsgId bad format ${typeOf(ele)} : ${ele}`); } return res; }; -const wrapperCondition = function (this: Syslog ,conditions : conditionsInterface, callback: Function | Pdu[] | null) : any { - let myFuncCondition : Function =()=>{}; - if (conditions.checkConditions && conditions.checkConditions in logicCondition) { +const wrapperCondition = function ( + this: Syslog, + conditions: conditionsInterface, + callback: Function | Pdu[] | null +): any { + let myFuncCondition: Function = () => {}; + if ( + conditions.checkConditions && + conditions.checkConditions in logicCondition + ) { myFuncCondition = logicCondition[conditions.checkConditions]; delete conditions.checkConditions; } else { - if(this.settings.checkConditions ){ + if (this.settings.checkConditions) { myFuncCondition = logicCondition[this.settings.checkConditions]; } } - const Conditions : ConditionSetting | boolean = sanitizeConditions(conditions); + const Conditions: ConditionSetting | boolean = sanitizeConditions(conditions); //console.log("Sanitize : ", conditions, myFuncCondition) - const tab : Function[] = []; + const tab: Function[] = []; switch (typeOf(callback)) { - case "function": - return (pdu : Pdu) => { - const res = myFuncCondition(Conditions, pdu); - if (res) { - tab.push( (callback as Function)(pdu) ); - } - }; - case "array": - for (let i = 0; i < (callback as []).length; i++) { - const res = myFuncCondition(Conditions, (callback as Pdu[])[i]); - if (res) { - tab.push( res); + case "function": + return (pdu: Pdu) => { + const res = myFuncCondition(Conditions, pdu); + if (res) { + tab.push((callback as Function)(pdu)); + } + }; + case "array": + for (let i = 0; i < (callback as []).length; i++) { + const res = myFuncCondition(Conditions, (callback as Pdu[])[i]); + if (res) { + tab.push(res); + } } - } - return tab; - default: - throw new Error("Bad wrapper"); + return tab; + default: + throw new Error("Bad wrapper"); } - }; -const sanitizeConditions = function (settingsCondition: conditionsInterface) :boolean | ConditionSetting { - let res : any = true; +const sanitizeConditions = function ( + settingsCondition: conditionsInterface +): boolean | ConditionSetting { + let res: any = true; if (typeOf(settingsCondition) !== "object") { return false; } @@ -306,61 +325,64 @@ const sanitizeConditions = function (settingsCondition: conditionsInterface) :bo if (!(ele in conditionsObj)) { return false; } - const condi: ConditionSetting = settingsCondition[ele]; - + const condi: ConditionSetting = settingsCondition[ele]; + if (condi.operator && !(condi.operator in operators)) { throw new Error(`Contitions bad operator : ${condi.operator}`); } if (condi.data) { switch (ele) { - case "severity": - if (!condi.operator) { - condi.operator = "=="; - } - res = checkFormatSeverity(condi.data); - if (res !== false) { - condi.data = {}; - for (let i = 0; i < res.length; i++) { - const mySeverity: string | undefined = Pdu.severityToString(res[i]); - if (mySeverity) { - condi.data[mySeverity as Severity] = sysLogSeverity[mySeverity as Severity]; - } else { - return false; - } + case "severity": + if (!condi.operator) { + condi.operator = "=="; } - } else { - return false; - } - break; - case "msgid": - if (!condi.operator) { - condi.operator = "=="; - } - res = checkFormatMsgId(condi.data); - if (res !== false) { - const format = typeOf(res); - if (format === "array") { + res = checkFormatSeverity(condi.data); + if (res !== false) { condi.data = {}; for (let i = 0; i < res.length; i++) { - condi.data[res[i]] = "||"; + const mySeverity: string | undefined = Pdu.severityToString( + res[i] + ); + if (mySeverity) { + condi.data[mySeverity as Severity] = + sysLogSeverity[mySeverity as Severity]; + } else { + return false; + } + } + } else { + return false; + } + break; + case "msgid": + if (!condi.operator) { + condi.operator = "=="; + } + res = checkFormatMsgId(condi.data); + if (res !== false) { + const format = typeOf(res); + if (format === "array") { + condi.data = {}; + for (let i = 0; i < res.length; i++) { + condi.data[res[i]] = "||"; + } + } else { + condi.data = res; } } else { + return false; + } + break; + case "date": + res = checkFormatDate(condi.data); + if (res) { condi.data = res; + } else { + return false; } - } else { - return false; - } - break; - case "date": - res = checkFormatDate(condi.data); - if (res) { - condi.data = res; - } else { + break; + default: return false; - } - break; - default: - return false; } } else { return false; @@ -370,8 +392,21 @@ const sanitizeConditions = function (settingsCondition: conditionsInterface) :bo // console.log(settingsCondition); }; -const createPDU = function (this: Syslog , payload: any , severity?: Severity, moduleName?: ModuleName, msgid?: Message ,msg?: Message) { - return new Pdu(payload, severity || this.settings.defaultSeverity, moduleName, msgid, msg); +const createPDU = function ( + this: Syslog, + payload: any, + severity?: Severity, + moduleName?: ModuleName, + msgid?: Message, + msg?: Message +) { + return new Pdu( + payload, + severity || this.settings.defaultSeverity, + moduleName, + msgid, + msg + ); }; /** @@ -384,20 +419,19 @@ const createPDU = function (this: Syslog , payload: any , severity?: Severity, m * @return syslog */ class Syslog extends Event { - - public settings : SyslogDefaultSettings - public ringStack : Pdu[] - public burstPrinted : number - public missed : number - public invalid : number - public valid : number - public start : number - private _async: boolean= false; + public settings: SyslogDefaultSettings; + public ringStack: Pdu[]; + public burstPrinted: number; + public missed: number; + public invalid: number; + public valid: number; + public start: number; + private _async: boolean = false; //fire(eventName: string | symbol, ...args: any[]): boolean; //fireAsync(eventName: string | symbol, ...args: any[]): Promise ; - constructor (settings?: SyslogDefaultSettings) { + constructor(settings?: SyslogDefaultSettings) { super(settings); /** @@ -451,17 +485,21 @@ class Syslog extends Event { */ this.start = 0; - this._async = this.settings.async || false + this._async = this.settings.async || false; } - static formatDebug (debug: DebugType) { + static formatDebug(debug: DebugType) { return formatDebug(debug); } - init (environment : EnvironmentType, debug?: DebugType , options? : conditionsInterface ) { + init( + environment: EnvironmentType, + debug?: DebugType, + options?: conditionsInterface + ) { return this.listenWithConditions( options || conditionOptions(environment, debug), - (pdu : Pdu ) => Syslog.normalizeLog(pdu) + (pdu: Pdu) => Syslog.normalizeLog(pdu) ); } @@ -481,11 +519,11 @@ class Syslog extends Event { // } // } - clean () { + clean() { return this.reset(); } - reset () { + reset() { this.ringStack.length = 0; this.removeAllListeners(); } @@ -496,11 +534,11 @@ class Syslog extends Event { * @method clearLogStack * */ - clearLogStack () { + clearLogStack() { this.ringStack.length = 0; } - pushStack (pdu :Pdu) : number{ + pushStack(pdu: Pdu): number { if (this.ringStack.length === this.settings.maxStack) { this.ringStack.shift(); } @@ -513,10 +551,15 @@ class Syslog extends Event { * logger message * @method log */ - log (payload: any, severity? :Severity , msgid?: ModuleName, msg?: Message) : Pdu { - let pdu ; + log( + payload: any, + severity?: Severity, + msgid?: ModuleName, + msg?: Message + ): Pdu { + let pdu; if (this.settings.rateLimit !== false) { - const rate : number = this.settings.rateLimit + const rate: number = this.settings.rateLimit; const now = new Date().getTime(); this.start = this.start || now; if (now > this.start + rate) { @@ -524,17 +567,27 @@ class Syslog extends Event { this.missed = 0; this.start = 0; } - if (this.settings.burstLimit && this.settings.burstLimit > this.burstPrinted) { + if ( + this.settings.burstLimit && + this.settings.burstLimit > this.burstPrinted + ) { try { if (payload instanceof Pdu) { pdu = payload; } else { - pdu = createPDU.call(this, payload, severity, this.settings.moduleName, msgid || this.settings.msgid, msg); + pdu = createPDU.call( + this, + payload, + severity, + this.settings.moduleName, + msgid || this.settings.msgid, + msg + ); } } catch (e) { console.error(e); this.invalid++; - if(! pdu){ + if (!pdu) { pdu = createPDU.call(this, e, "ERROR"); } pdu.status = "INVALID"; @@ -547,7 +600,7 @@ class Syslog extends Event { return pdu; } this.missed++; - if(! pdu){ + if (!pdu) { pdu = createPDU.call(this, "DROPPED", "WARNING"); } pdu.status = "DROPPED"; @@ -557,12 +610,19 @@ class Syslog extends Event { if (payload instanceof Pdu) { pdu = payload; } else { - pdu = createPDU.call(this, payload, severity, this.settings.moduleName, msgid || this.settings.msgid, msg); + pdu = createPDU.call( + this, + payload, + severity, + this.settings.moduleName, + msgid || this.settings.msgid, + msg + ); } } catch (e) { console.error(e); this.invalid++; - if( !pdu ){ + if (!pdu) { pdu = createPDU.call(this, e, "ERROR"); } pdu.status = "INVALID"; @@ -582,8 +642,12 @@ class Syslog extends Event { * @return {array} new array between start end * @return {Pdu} pdu */ - getLogStack (start?: number, end?: number, contition?: conditionsInterface): Pdu[] | Pdu { - let stack :Pdu[] | null= null; + getLogStack( + start?: number, + end?: number, + contition?: conditionsInterface + ): Pdu[] | Pdu { + let stack: Pdu[] | null = null; if (contition) { stack = this.getLogs(contition); } else { @@ -607,7 +671,7 @@ class Syslog extends Event { * @param {Object} conditions . * @return {array} new array with matches conditions */ - getLogs (conditions: conditionsInterface , stack: Pdu[] | null = null): Pdu[] { + getLogs(conditions: conditionsInterface, stack: Pdu[] | null = null): Pdu[] { if (conditions) { return wrapperCondition.call(this, conditions, stack || this.ringStack); } @@ -619,7 +683,7 @@ class Syslog extends Event { * @method logToJson * @return {String} string in JSON format */ - logToJson (conditions : conditionsInterface, stack = null): string { + logToJson(conditions: conditionsInterface, stack = null): string { let res = null; if (conditions) { res = this.getLogs(conditions, stack); @@ -633,37 +697,45 @@ class Syslog extends Event { * load the stack as JSON string * @method loadStack */ - loadStack (stack: Pdu[] | string, doEvent = false, beforeConditions : Function | null = null) : Pdu[]{ + loadStack( + stack: Pdu[] | string, + doEvent = false, + beforeConditions: Function | null = null + ): Pdu[] { if (!stack) { throw new Error("syslog loadStack : not stack in arguments "); } switch (typeOf(stack)) { - case "string": - return this.loadStack(JSON.parse(stack), doEvent, beforeConditions); - case "array": - case "object": - for (const stackItem of stack ) { - const pdu = new Pdu( - stackItem.payload, - stackItem.severity as Severity | undefined , - stackItem.moduleName || this.settings.moduleName, - stackItem.msgid, - stackItem.msg, - stackItem.timeStamp + case "string": + return this.loadStack( + JSON.parse(stack), + doEvent, + beforeConditions ); - this.pushStack(pdu); - if (doEvent) { - if (beforeConditions && typeof beforeConditions === "function") { - beforeConditions.call(this, pdu, stackItem); + case "array": + case "object": + for (const stackItem of stack) { + const pdu = new Pdu( + stackItem.payload, + stackItem.severity as Severity | undefined, + stackItem.moduleName || this.settings.moduleName, + stackItem.msgid, + stackItem.msg, + stackItem.timeStamp + ); + this.pushStack(pdu); + if (doEvent) { + if (beforeConditions && typeof beforeConditions === "function") { + beforeConditions.call(this, pdu, stackItem); + } + this.fire("onLog", pdu); } - this.fire("onLog", pdu); } - } - break; - default: - throw new Error("syslog loadStack : bad stack in arguments type"); + break; + default: + throw new Error("syslog loadStack : bad stack in arguments type"); } - return stack; + return stack; } /** @@ -671,14 +743,17 @@ class Syslog extends Event { * @method filter * */ - filter (conditions : conditionsInterface, callback : Function | Pdu[]| null = null): void { + filter( + conditions: conditionsInterface, + callback: Function | Pdu[] | null = null + ): void { if (!conditions) { throw new Error("filter conditions not found "); } conditions = extend(true, {}, conditions); const wrapper = wrapperCondition.call(this, conditions, callback); if (wrapper) { - super.on("onLog", wrapper); + super.on("onLog", wrapper); } } @@ -687,101 +762,118 @@ class Syslog extends Event { * @method listenWithConditions * */ - listenWithConditions (conditions: conditionsInterface, callback :Function) : void{ + listenWithConditions( + conditions: conditionsInterface, + callback: Function + ): void { return this.filter(conditions, callback); } - error (data: any) : Pdu { + error(data: any): Pdu { return this.log(data, "ERROR"); } - warn (data: any) : Pdu { + warn(data: any): Pdu { return this.log(data, "WARNING"); } - warnning (data: any) : Pdu { + warnning(data: any): Pdu { return this.log(data, "WARNING"); } - info (data: any) : Pdu{ + info(data: any): Pdu { return this.log(data, "INFO"); } - debug (data: any) : Pdu{ + debug(data: any): Pdu { return this.log(data, "DEBUG"); } - trace (data: any, ...args : any[]) : Pdu{ + trace(data: any, ...args: any[]): Pdu { return this.log(data, "NOTICE", ...args); } - static wrapper (pdu: Pdu) { + static wrapper(pdu: Pdu) { if (!pdu) { throw new Error("Syslog pdu not defined"); } const date = new Date(pdu.timeStamp); switch (pdu.severity) { - case 0: - case 1: - case 2: - case 3: - return { - logger: console.error, - text: `${date.toDateString()} ${date.toLocaleTimeString()} ${red(pdu.severityName)} ${green(pdu.msgid)} : ` - }; - case 4: - return { - logger: console.warn, - text: `${date.toDateString()} ${date.toLocaleTimeString()} ${yellow(pdu.severityName)} ${green(pdu.msgid)} : ` - }; - case 5: - return { - logger: console.log, - text: `${date.toDateString()} ${date.toLocaleTimeString()} ${red(pdu.severityName)} ${green(pdu.msgid)} : ` - }; - case 6: - return { - logger: console.info, - text: `${date.toDateString()} ${date.toLocaleTimeString()} ${blue(pdu.severityName)} ${green(pdu.msgid)} : ` - }; - case 7: - return { - logger: console.debug, - text: `${date.toDateString()} ${date.toLocaleTimeString()} ${cyan(pdu.severityName)} ${green(pdu.msgid)} : ` - }; - default: - return { - logger: console.log, - text: `${date.toDateString()} ${date.toLocaleTimeString()} ${cyan(pdu.severityName)} ${green(pdu.msgid)} : ` - }; + case 0: + case 1: + case 2: + case 3: + return { + logger: console.error, + text: `${date.toDateString()} ${date.toLocaleTimeString()} ${red( + pdu.severityName + )} ${green(pdu.msgid)} : `, + }; + case 4: + return { + logger: console.warn, + text: `${date.toDateString()} ${date.toLocaleTimeString()} ${yellow( + pdu.severityName + )} ${green(pdu.msgid)} : `, + }; + case 5: + return { + logger: console.log, + text: `${date.toDateString()} ${date.toLocaleTimeString()} ${red( + pdu.severityName + )} ${green(pdu.msgid)} : `, + }; + case 6: + return { + logger: console.info, + text: `${date.toDateString()} ${date.toLocaleTimeString()} ${blue( + pdu.severityName + )} ${green(pdu.msgid)} : `, + }; + case 7: + return { + logger: console.debug, + text: `${date.toDateString()} ${date.toLocaleTimeString()} ${cyan( + pdu.severityName + )} ${green(pdu.msgid)} : `, + }; + default: + return { + logger: console.log, + text: `${date.toDateString()} ${date.toLocaleTimeString()} ${cyan( + pdu.severityName + )} ${green(pdu.msgid)} : `, + }; } } - static normalizeLog ( pdu: Pdu, pid: string = "") { + static normalizeLog(pdu: Pdu, pid: string = "") { if (pdu.payload === "" || pdu.payload === undefined) { - console.warn(`${pdu.severityName} ${pdu.msgid} : logger message empty !!!!`); + console.warn( + `${pdu.severityName} ${pdu.msgid} : logger message empty !!!!` + ); console.trace(pdu); return pdu; } const message = pdu.payload; switch (typeof message) { - case "object": - // switch (true) { - // case message instanceof nodefony.Error: - // if (kernel && kernel.console) { - // message = message.message; - // } - // break; - // case message instanceof Error: - // if (kernel && kernel.console) { - // message = message.message; - // } else { - // message = new nodefony.Error(message); - // } - // break; - // } - break; - default: + case "object": + // switch (true) { + // case message instanceof nodefony.Error: + // if (kernel && kernel.console) { + // message = message.message; + // } + // break; + // case message instanceof Error: + // if (kernel && kernel.console) { + // message = message.message; + // } else { + // message = new nodefony.Error(message); + // } + // break; + // } + break; + default: } if (pdu.severity === -1) { process.stdout.write("\u001b[0G"); @@ -795,9 +887,5 @@ class Syslog extends Event { } } -export default Syslog -export { - ConditionSetting, - conditionsInterface, - SyslogDefaultSettings -} +export default Syslog; +export { ConditionSetting, conditionsInterface, SyslogDefaultSettings }; diff --git a/src/tests/Container.test.ts b/src/tests/Container.test.ts index 08455ad..47a61c2 100644 --- a/src/tests/Container.test.ts +++ b/src/tests/Container.test.ts @@ -1,10 +1,8 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { expect, assert } from 'chai'; - - -import 'mocha'; -import Container from '../Container'; +import { expect, assert } from "chai"; +import "mocha"; +import Container from "../Container"; declare global { interface NodeJSGlobal { @@ -13,129 +11,130 @@ declare global { } declare let global: NodeJS.Global & { container?: Container }; -class myClass{ - name: string - constructor(name: string){ - this.name = name +class myClass { + name: string; + constructor(name: string) { + this.name = name; } } -class myClass2{ - name: string - constructor(name: string){ - this.name = name +class myClass2 { + name: string; + constructor(name: string) { + this.name = name; } } -class myClass3{ - name: string - constructor(name: string){ - this.name = name +class myClass3 { + name: string; + constructor(name: string) { + this.name = name; } } -describe('Container', () => { - +describe("Container", () => { beforeEach(() => { - if ('container' in global) { - delete (global as any).container; + if ("container" in global) { + delete (global as any).container; } global.container = new Container(); - // Ajout d'un service - global.container.set('service1', function () { - console.log('Service 1'); + // Ajout d'un service + global.container.set("service1", function () { + console.log("Service 1"); }); - global.container.set('myclass' , new myClass('test')) + global.container.set("myclass", new myClass("test")); }); - it('Container set and get services', () => { - if(! global.container){ - throw new Error(`global not ready `) + it("Container set and get services", () => { + if (!global.container) { + throw new Error(`global not ready `); } // Récupération du service - expect(global.container.get('service1')).to.be.a('function'); - expect(global.container.get('myclass')).to.be.instanceOf(myClass) + expect(global.container.get("service1")).to.be.a("function"); + expect(global.container.get("myclass")).to.be.instanceOf(myClass); }); - it('Container set and get parameters', () => { - if(! global.container){ - throw new Error(`global not ready `) + it("Container set and get parameters", () => { + if (!global.container) { + throw new Error(`global not ready `); } // Récupération du service - global.container.setParameters("foo.bar", "test") - expect(global.container.getParameters("foo.bar")).eq("test") - assert.throws(() =>{ - if(! global.container){ - throw new Error(`global not ready `) - } - global.container.setParameters("foo.bar.ele", {}) - }, Error, "Cannot create property 'ele' on string 'test'") - const obj = {} - global.container.setParameters("foo.bar", obj) - expect(global.container.getParameters("foo.bar")).to.be.an("object") - expect(global.container.getParameters("foo")).to.be.an("object") + global.container.setParameters("foo.bar", "test"); + expect(global.container.getParameters("foo.bar")).eq("test"); + assert.throws( + () => { + if (!global.container) { + throw new Error(`global not ready `); + } + global.container.setParameters("foo.bar.ele", {}); + }, + Error, + "Cannot create property 'ele' on string 'test'" + ); + const obj = {}; + global.container.setParameters("foo.bar", obj); + expect(global.container.getParameters("foo.bar")).to.be.an("object"); + expect(global.container.getParameters("foo")).to.be.an("object"); expect(global.container.getParameters("foo")).to.include({ bar: obj }); }); - it('Container Scope', () => { - if(! global.container){ - throw new Error(`global not ready `) + it("Container Scope", () => { + if (!global.container) { + throw new Error(`global not ready `); } - global.container.addScope("myscope") - const scopeContainer = global.container.enterScope("myscope") - global.container.addScope("myscope2") - const scopeContainer2 = global.container.enterScope("myscope2") - expect(scopeContainer.get('service1')).to.be.a('function'); - expect(scopeContainer.get('myclass')).to.be.instanceOf(myClass) - expect(scopeContainer2.get('service1')).to.be.a('function'); - expect(scopeContainer2.get('myclass')).to.be.instanceOf(myClass) - }) + global.container.addScope("myscope"); + const scopeContainer = global.container.enterScope("myscope"); + global.container.addScope("myscope2"); + const scopeContainer2 = global.container.enterScope("myscope2"); + expect(scopeContainer.get("service1")).to.be.a("function"); + expect(scopeContainer.get("myclass")).to.be.instanceOf(myClass); + expect(scopeContainer2.get("service1")).to.be.a("function"); + expect(scopeContainer2.get("myclass")).to.be.instanceOf(myClass); + }); - it('Container Scope set and get parameters', () => { - if(! global.container){ - throw new Error(`global not ready `) + it("Container Scope set and get parameters", () => { + if (!global.container) { + throw new Error(`global not ready `); } - const obj = {} - global.container.setParameters("foo.bar", obj) - global.container.addScope("myscope") - const scopeContainer = global.container.enterScope("myscope") + const obj = {}; + global.container.setParameters("foo.bar", obj); + global.container.addScope("myscope"); + const scopeContainer = global.container.enterScope("myscope"); //console.log(scopeContainer) //console.log(global.container, scopeContainer.parameters, global.container.parameters) - expect(scopeContainer.getParameters("foo.bar")).to.be.an("object") - expect(scopeContainer.getParameters("foo")).to.be.an("object") + expect(scopeContainer.getParameters("foo.bar")).to.be.an("object"); + expect(scopeContainer.getParameters("foo")).to.be.an("object"); expect(scopeContainer.getParameters("foo")).to.include({ bar: obj }); - scopeContainer.setParameters("foo.bar", "test") + scopeContainer.setParameters("foo.bar", "test"); //console.log(scopeContainer.getParameters("foo.bar") ) - expect(scopeContainer.getParameters("foo.bar")).equal("test") + expect(scopeContainer.getParameters("foo.bar")).equal("test"); //console.log(scopeContainer) expect(global.container.getParameters("foo")).to.include({ bar: obj }); - }) + }); - it('Container Scope add service on scope', () => { - - if(! global.container){ - throw new Error(`global not ready `) + it("Container Scope add service on scope", () => { + if (!global.container) { + throw new Error(`global not ready `); } - global.container.addScope("myscope") - const scopeContainer = global.container.enterScope("myscope") - global.container.addScope("myscope2") - const scopeContainer2 = global.container.enterScope("myscope2") - scopeContainer.set('myclass2' , new myClass2('test2')) - expect(scopeContainer.get('myclass2') ).to.be.instanceOf(myClass2) - expect(global.container.get('myclass2')).to.be.null - expect(scopeContainer2.get('myclass2')).to.be.null - }) + global.container.addScope("myscope"); + const scopeContainer = global.container.enterScope("myscope"); + global.container.addScope("myscope2"); + const scopeContainer2 = global.container.enterScope("myscope2"); + scopeContainer.set("myclass2", new myClass2("test2")); + expect(scopeContainer.get("myclass2")).to.be.instanceOf(myClass2); + expect(global.container.get("myclass2")).to.be.null; + expect(scopeContainer2.get("myclass2")).to.be.null; + }); - it('Container Scope add service on main container', () => { - if(! global.container){ - throw new Error(`global not ready `) + it("Container Scope add service on main container", () => { + if (!global.container) { + throw new Error(`global not ready `); } - global.container.addScope("myscope") - const scopeContainer = global.container.enterScope("myscope") - global.container.addScope("myscope2") - const scopeContainer2 = global.container.enterScope("myscope2") - global.container.set('myclass3' , new myClass3('test3')) - expect(scopeContainer.get('myclass3') ).to.be.instanceOf(myClass3) - expect(scopeContainer2.get('myclass3') ).to.be.instanceOf(myClass3) - }) - + global.container.addScope("myscope"); + const scopeContainer = global.container.enterScope("myscope"); + global.container.addScope("myscope2"); + const scopeContainer2 = global.container.enterScope("myscope2"); + global.container.set("myclass3", new myClass3("test3")); + expect(scopeContainer.get("myclass3")).to.be.instanceOf(myClass3); + expect(scopeContainer2.get("myclass3")).to.be.instanceOf(myClass3); + }); }); diff --git a/src/tests/Event.test.ts b/src/tests/Event.test.ts index 50ae8cb..09f0c2f 100644 --- a/src/tests/Event.test.ts +++ b/src/tests/Event.test.ts @@ -11,10 +11,9 @@ * */ -import { assert } from 'chai' -import Event ,{create , notification} from '../Event' -import {isPromise} from '../Tools' - +import { assert } from "chai"; +import Event, { create, notification } from "../Event"; +import { isPromise } from "../Tools"; declare global { interface NodeJSGlobal { @@ -23,7 +22,6 @@ declare global { } declare let global: NodeJS.Global & { notificationsCenter?: Event }; - describe("NODEFONY Notifications Center", () => { describe("namespace", () => { before(() => { @@ -40,8 +38,8 @@ describe("NODEFONY Notifications Center", () => { describe("sync", () => { it("sync", (done) => { - if ( ! global.notificationsCenter){ - throw new Error(`global not ready`) + if (!global.notificationsCenter) { + throw new Error(`global not ready`); } const obj = {}; global.notificationsCenter.on("myEvent", (count, args) => { @@ -54,8 +52,8 @@ describe("NODEFONY Notifications Center", () => { }); let i = 0; setTimeout(() => { - if ( ! global.notificationsCenter){ - throw new Error(`global not ready`) + if (!global.notificationsCenter) { + throw new Error(`global not ready`); } global.notificationsCenter.fire("myEvent", i, obj); global.notificationsCenter.emit("myEvent", ++i, obj); @@ -69,31 +67,39 @@ describe("NODEFONY Notifications Center", () => { // global.notificationsCenter = nodefony.notificationsCenter.create(); }); beforeEach(() => { - if ('notificationsCenter' in global) { + if ("notificationsCenter" in global) { delete (global as any).notificationsCenter; } global.notificationsCenter = create(); }); it("simple", async () => { - if ( ! global.notificationsCenter){ - throw new Error(`global not ready`) + if (!global.notificationsCenter) { + throw new Error(`global not ready`); } const obj = {}; - global.notificationsCenter.on("myEvent", async (count, args) => new Promise((resolve) => { - assert.strictEqual(args, obj); - if (count === 1) { - setTimeout(() => { - resolve(count); - }, 100); - } else { - assert.strictEqual(count, 0); - setTimeout(() => { - resolve(args); - }, 500); - } - })); + global.notificationsCenter.on( + "myEvent", + async (count, args) => + new Promise((resolve) => { + assert.strictEqual(args, obj); + if (count === 1) { + setTimeout(() => { + resolve(count); + }, 100); + } else { + assert.strictEqual(count, 0); + setTimeout(() => { + resolve(args); + }, 500); + } + }) + ); let i = 0; - let res :any[] = await global.notificationsCenter.fireAsync("myEvent", i, obj); + let res: any[] = await global.notificationsCenter.fireAsync( + "myEvent", + i, + obj + ); assert.strictEqual(res.length, 1); assert.strictEqual(res[0], obj); res = await global.notificationsCenter.emitAsync("myEvent", ++i, obj); @@ -102,23 +108,35 @@ describe("NODEFONY Notifications Center", () => { }); it("multi", async () => { - if ( ! global.notificationsCenter){ - throw new Error(`global not ready`) + if (!global.notificationsCenter) { + throw new Error(`global not ready`); } const obj = {}; - global.notificationsCenter.on("myEvent", async (count, args) => new Promise((resolve) => { - setTimeout(() => { - resolve(args); - }, 400); - })); - global.notificationsCenter.on("myEvent", async (count) => new Promise((resolve) => { - setTimeout(() => { - resolve(count + 1); - }, 200); - })); + global.notificationsCenter.on( + "myEvent", + async (count, args) => + new Promise((resolve) => { + setTimeout(() => { + resolve(args); + }, 400); + }) + ); + global.notificationsCenter.on( + "myEvent", + async (count) => + new Promise((resolve) => { + setTimeout(() => { + resolve(count + 1); + }, 200); + }) + ); let i = 0; const res = await global.notificationsCenter.fireAsync("myEvent", i, obj); - const res1 = await global.notificationsCenter.emitAsync("myEvent", ++i, obj); + const res1 = await global.notificationsCenter.emitAsync( + "myEvent", + ++i, + obj + ); assert.strictEqual(res.length, 2); assert.strictEqual(res[0], obj); assert.strictEqual(res[1], 1); @@ -126,15 +144,19 @@ describe("NODEFONY Notifications Center", () => { assert.strictEqual(res1[0], obj); assert.strictEqual(res1[1], 2); - const res2 = await global.notificationsCenter.emitAsync("myEvent", --i, res1); + const res2 = await global.notificationsCenter.emitAsync( + "myEvent", + --i, + res1 + ); assert.strictEqual(res2.length, 2); assert.strictEqual(res2[0], res1); assert.strictEqual(res2[1], 1); }); it("await", async () => { - if ( ! global.notificationsCenter){ - throw new Error(`global not ready`) + if (!global.notificationsCenter) { + throw new Error(`global not ready`); } const myFunc = async function (count: number, args: any) { if (count === 0) { @@ -144,15 +166,23 @@ describe("NODEFONY Notifications Center", () => { }; const obj = {}; const i = 0; - global.notificationsCenter.on("myEvent", async (count, args) => await myFunc(count, args)); - global.notificationsCenter.on("myEvent", async (count, args) => await myFunc(count, args)); - const res = await global.notificationsCenter.fireAsync("myEvent", i, obj) + global.notificationsCenter.on( + "myEvent", + async (count, args) => await myFunc(count, args) + ); + global.notificationsCenter.on( + "myEvent", + async (count, args) => await myFunc(count, args) + ); + const res = await global.notificationsCenter + .fireAsync("myEvent", i, obj) .then((args) => { assert.strictEqual(args[0], 1); assert.strictEqual(args[1], 1); return args; }); - const res2 = await global.notificationsCenter.fireAsync("myEvent", res[0], obj) + const res2 = await global.notificationsCenter + .fireAsync("myEvent", res[0], obj) .then((args) => { assert.strictEqual(args[0], obj); assert.strictEqual(args[1], obj); @@ -165,8 +195,8 @@ describe("NODEFONY Notifications Center", () => { }); it("await error", async () => { - if ( ! global.notificationsCenter){ - throw new Error(`global not ready`) + if (!global.notificationsCenter) { + throw new Error(`global not ready`); } const myFunc = async function (count: number, args: any) { if (count === 0) { @@ -179,12 +209,19 @@ describe("NODEFONY Notifications Center", () => { const myFunc2 = async function () { throw new Error("myError"); }; - global.notificationsCenter.on("myEvent", async (count, args) => await myFunc(count, args)); + global.notificationsCenter.on( + "myEvent", + async (count, args) => await myFunc(count, args) + ); // eslint-disable-next-line @typescript-eslint/no-unused-vars - global.notificationsCenter.on("myEvent", async (count, args) => await myFunc2()); + global.notificationsCenter.on( + "myEvent", + async (count, args) => await myFunc2() + ); let res = null; - - res = await global.notificationsCenter.fireAsync("myEvent", i, obj) + + res = await global.notificationsCenter + .fireAsync("myEvent", i, obj) .then((...args: any[]) => { console.log(args); throw new Error("then don't be call"); @@ -194,7 +231,8 @@ describe("NODEFONY Notifications Center", () => { }); assert.strictEqual(res, undefined); res = null; - res = global.notificationsCenter.fireAsync("myEvent", i, obj) + res = global.notificationsCenter + .fireAsync("myEvent", i, obj) .then((...args: any[]) => { console.log(args); throw new Error("then don't be call"); @@ -203,7 +241,6 @@ describe("NODEFONY Notifications Center", () => { assert.strictEqual(e.message, "myError"); }); assert(isPromise(res)); - }); }); -}) \ No newline at end of file +}); diff --git a/src/tests/Extend.test.ts b/src/tests/Extend.test.ts index 1a73c20..f2ffd9f 100644 --- a/src/tests/Extend.test.ts +++ b/src/tests/Extend.test.ts @@ -1,10 +1,9 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { assert } from 'chai'; -import 'mocha'; -import {extend, isEmptyObject} from '../Tools' +import { assert } from "chai"; +import "mocha"; +import { extend, isEmptyObject } from "../Tools"; describe("TOOLS extend", () => { - describe("CONTRUSTROR ", () => { it("LIB LOADED", (done) => { assert.equal(typeof extend, "function"); @@ -20,31 +19,31 @@ describe("TOOLS extend", () => { describe("Simple Object", () => { it("Simple Object", (done) => { const myobj = { - foo: "bar" + foo: "bar", }; //let res = extend({}); //assert(res === nodefony); let res = extend(true); assert(isEmptyObject(res)); res = extend(myobj, { - bar: "foo" + bar: "foo", }); assert(res === myobj); - let obj:{foo?: string, bar?:string} = {}; + let obj: { foo?: string; bar?: string } = {}; res = extend(obj, myobj, { - bar: "foo" + bar: "foo", }); assert(res === obj); assert.equal(res.foo, "bar"); assert.equal(res.bar, "foo"); res = extend(myobj, { - foo: "bar1" + foo: "bar1", }); assert(res === myobj); assert.equal(res.foo, "bar1"); obj = {}; res = extend(obj, myobj, { - foo: "bar2" + foo: "bar2", }); assert.equal(myobj.foo, "bar1"); assert.equal(obj.foo, "bar2"); @@ -53,21 +52,21 @@ describe("TOOLS extend", () => { }); it("Deep Object", (done) => { - const myobj : {[key: string]: any} = { + const myobj: { [key: string]: any } = { foo: { bar: { ele: 1, - obj: 1 - } - } + obj: 1, + }, + }, }; let res = extend(myobj, { - bar: "foo" + bar: "foo", }); assert(myobj.bar, "foo"); - let obj: any = {}; + let obj: any = {}; res = extend(obj, myobj, { - bar: "foo1" + bar: "foo1", }); assert(res, obj); assert.equal(res.foo, myobj.foo); @@ -78,9 +77,9 @@ describe("TOOLS extend", () => { res = extend(obj, myobj, { foo: { bar: { - ele: 2 - } - } + ele: 2, + }, + }, }); assert.equal(res.bar, "foo"); assert.equal(res.foo.bar.ele, 2); @@ -89,16 +88,16 @@ describe("TOOLS extend", () => { res = extend(true, obj, myobj, { foo: { bar: { - ele: 3 - } - } + ele: 3, + }, + }, }); assert.equal(res.bar, "foo"); assert.equal(res.foo.bar.ele, 3); assert.equal(res.foo.bar.obj, 1); obj = {}; res = extend(true, obj, myobj, { - bar: "foo" + bar: "foo", }); assert(res, obj); assert.notEqual(res.foo, myobj.foo); @@ -113,7 +112,7 @@ describe("TOOLS extend", () => { //assert.equal(res, nodefony); const myobj = { tab: myArray, - foo: "bar" + foo: "bar", }; let res = extend({}, myobj); assert.equal(res.tab, myArray); @@ -122,11 +121,11 @@ describe("TOOLS extend", () => { const tab = [4, 5, 6]; res = extend({}, myobj, { - tab + tab, }); assert.equal(res.tab, tab); res = extend(true, {}, myobj, { - tab + tab, }); assert.notEqual(res.tab, tab); done(); diff --git a/src/tests/FileClass.test.ts b/src/tests/FileClass.test.ts index 05b7598..742e796 100644 --- a/src/tests/FileClass.test.ts +++ b/src/tests/FileClass.test.ts @@ -1,22 +1,14 @@ -import { assert } from 'chai'; -import 'mocha'; -import FileClass from '../FileClass' - +import { assert } from "chai"; +import "mocha"; +import FileClass from "../FileClass"; describe("NODEFONY CORE FINDER", () => { - - before( () => { - try{ - console.log(FileClass) - assert.isDefined(FileClass) - }catch(e){ - console.error(e) - } + before(() => { + try { + console.log(FileClass); + assert.isDefined(FileClass); + } catch (e) { + console.error(e); + } }); - - - - - - -}) \ No newline at end of file +}); diff --git a/src/tests/Finder.test.ts b/src/tests/Finder.test.ts index f023252..437f1ee 100644 --- a/src/tests/Finder.test.ts +++ b/src/tests/Finder.test.ts @@ -1,37 +1,38 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import 'mocha'; -import assert from 'node:assert' -import Finder , {TotalInterface}from '../finder/Finder' -import path from 'node:path' -import Result from '../finder/Result'; -import FileResult from '../finder/FileResult' -import File from '../finder/File' -import FileClass from '../FileClass' +import "mocha"; +import assert from "node:assert"; +import Finder, { TotalInterface } from "../finder/Finder"; +import path from "node:path"; +import Result from "../finder/Result"; +import FileResult from "../finder/FileResult"; +import File from "../finder/File"; +import FileClass from "../FileClass"; -declare let global: NodeJS.Global & { - bundlePath :string - nodefonyPath: string - dataPath: string - arrayPath: string[] - excludeDir: RegExp - finder: Finder - finderInstance: Finder - }; +declare let global: NodeJS.Global & { + bundlePath: string; + nodefonyPath: string; + dataPath: string; + arrayPath: string[]; + excludeDir: RegExp; + finder: Finder; + finderInstance: Finder; +}; describe("NODEFONY CORE FINDER", () => { - before( () => { - try{ - global.bundlePath = path.resolve("src", "tests", "finder" , "bundles"); - global.nodefonyPath = path.resolve("src", "tests", "finder" ,"nodefony"); - global.dataPath = path.resolve("src", "tests", "finder","data"); - global.arrayPath = [global.bundlePath, global.nodefonyPath]; - global.excludeDir = /node_modules|tmp|docker|.git|assets|tests|test|doc|documentation|public/; - global.finderInstance = new Finder({ - // excludeDir: global.excludeDir - }); - }catch(e){ - console.error(e) - } + before(() => { + try { + global.bundlePath = path.resolve("src", "tests", "finder", "bundles"); + global.nodefonyPath = path.resolve("src", "tests", "finder", "nodefony"); + global.dataPath = path.resolve("src", "tests", "finder", "data"); + global.arrayPath = [global.bundlePath, global.nodefonyPath]; + global.excludeDir = + /node_modules|tmp|docker|.git|assets|tests|test|doc|documentation|public/; + global.finderInstance = new Finder({ + // excludeDir: global.excludeDir + }); + } catch (e) { + console.error(e); + } }); describe("CONTRUSTROR ", () => { @@ -42,7 +43,7 @@ describe("NODEFONY CORE FINDER", () => { recurse: true, depth: 1, seeHidden: true, - followSymLink: true + followSymLink: true, }); }); @@ -93,32 +94,26 @@ describe("NODEFONY CORE FINDER", () => { it("PARSE IN", async () => { assert.rejects(global.finder.in("bad path")); - let res = await global.finder - .in("bad path") - .catch((e) => { - assert.ok(e.message.indexOf("no such file or director") >= 0); - }); + let res = await global.finder.in("bad path").catch((e) => { + assert.ok(e.message.indexOf("no such file or director") >= 0); + }); assert.equal(res, undefined); assert.rejects(async () => { - res = await global.finder - .in("bad path") - .catch((e) => { - assert.match(e.message, /no such file or director/); - throw e; - }); + res = await global.finder.in("bad path").catch((e) => { + assert.match(e.message, /no such file or director/); + throw e; + }); }); - res = await global.finder - .in(global.nodefonyPath) - .then((result) => { - assert(result); - assert.strictEqual(result.length, 1); - const file = result[0]; - assert(result instanceof FileResult); - assert.equal(file.name, "nodefony"); - assert.equal(file.path, global.nodefonyPath); - return result; - }); + res = await global.finder.in(global.nodefonyPath).then((result) => { + assert(result); + assert.strictEqual(result.length, 1); + const file = result[0]; + assert(result instanceof FileResult); + assert.equal(file.name, "nodefony"); + assert.equal(file.path, global.nodefonyPath); + return result; + }); assert(res); assert.strictEqual(res.length, 1); }); @@ -129,7 +124,7 @@ describe("NODEFONY CORE FINDER", () => { describe("RESULT ", () => { beforeEach(() => { global.finder = new Finder({ - excludeDir: global.excludeDir + excludeDir: global.excludeDir, // match: /.*.js$|.*.es6$/, }); }); @@ -138,7 +133,7 @@ describe("NODEFONY CORE FINDER", () => { const res = await global.finder .in(global.dataPath, { recurse: false, - seeHidden: true + seeHidden: true, }) .then((result) => { assert(result); @@ -169,7 +164,7 @@ describe("NODEFONY CORE FINDER", () => { it("HIDDEN", async () => { const res = await global.finder .in(global.dataPath, { - seeHidden: false + seeHidden: false, }) .then((result) => { assert(result[0]); @@ -185,7 +180,7 @@ describe("NODEFONY CORE FINDER", () => { .in(global.dataPath, { seeHidden: true, recurse: true, - depth: 2 + depth: 2, }) .then((result) => { assert(result[0]); @@ -207,7 +202,7 @@ describe("NODEFONY CORE FINDER", () => { .in(global.dataPath, { seeHidden: true, recurse: true, - depth: 3 + depth: 3, }) .then((result) => { assert(result[0]); @@ -230,7 +225,7 @@ describe("NODEFONY CORE FINDER", () => { .in(global.dataPath, { recurse: true, seeHidden: true, - followSymLink: true + followSymLink: true, }) .then((result) => { const sort = result[0].childrens.sortByName(); @@ -250,9 +245,9 @@ describe("NODEFONY CORE FINDER", () => { excludeDir: global.excludeDir, seeHidden: true, recurse: true, - followSymLink: true + followSymLink: true, }); - await finder.in(global.dataPath, { + await finder.in(global.dataPath, { onFinish: (res: Result, totals: TotalInterface) => { if (process.platform !== "win32") { assert.strictEqual(totals.Directory, 4); @@ -260,9 +255,9 @@ describe("NODEFONY CORE FINDER", () => { assert.strictEqual(totals.symbolicLink, 3); assert.strictEqual(totals.hidden, 3); } - } + }, }); - await finder.in(global.dataPath, { + await finder.in(global.dataPath, { seeHidden: false, onFinish: (res: Result, totals: TotalInterface) => { if (process.platform !== "win32") { @@ -271,11 +266,11 @@ describe("NODEFONY CORE FINDER", () => { assert.strictEqual(totals.symbolicLink, 3); assert.strictEqual(totals.hidden, 0); } - } + }, }); - await finder.in(global.dataPath, { + await finder.in(global.dataPath, { followSymLink: false, - onFinish: (res: Result , totals: TotalInterface) => { + onFinish: (res: Result, totals: TotalInterface) => { // console.log(res) // console.log( res[0].childrens.getDirectories() ) // assert.strictEqual(totals.Directory, 4); @@ -284,7 +279,7 @@ describe("NODEFONY CORE FINDER", () => { assert.strictEqual(totals.symbolicLink, 2); assert.strictEqual(totals.hidden, 2); } - } + }, }); }); }); @@ -296,7 +291,7 @@ describe("NODEFONY CORE FINDER", () => { // match: /.*.js$|.*.es6$/, seeHidden: true, recurse: true, - followSymLink: true + followSymLink: true, }); }); @@ -305,9 +300,9 @@ describe("NODEFONY CORE FINDER", () => { excludeDir: global.excludeDir, seeHidden: true, recurse: true, - followSymLink: true + followSymLink: true, }); - await finder.in(global.dataPath, {}); + await finder.in(global.dataPath, {}); // let ret = res[0].childrens.find(/^dir/); }); }); @@ -319,7 +314,7 @@ describe("NODEFONY CORE FINDER", () => { // match: /.*.js$|.*.es6$/, seeHidden: true, recurse: true, - followSymLink: true + followSymLink: true, }); }); it("SIMPLE RESULT JSON", async () => { diff --git a/src/tests/Service.test.ts b/src/tests/Service.test.ts index 520ae9d..9a11818 100644 --- a/src/tests/Service.test.ts +++ b/src/tests/Service.test.ts @@ -1,9 +1,8 @@ -import 'mocha'; -import assert from 'node:assert' -import Service from '../Service' +import "mocha"; +import assert from "node:assert"; +import Service from "../Service"; //import mochaJsdom from 'mocha-jsdom'; - declare global { interface NodeJSGlobal { service: Service; @@ -11,12 +10,9 @@ declare global { } declare let global: NodeJS.Global & { service?: Service }; - describe("NODEFONY Service", () => { - describe("namespace", () => { - - before(() => { + before(() => { global.service = new Service("test"); // mochaJsdom({ // // Options jsdom @@ -28,11 +24,5 @@ describe("NODEFONY Service", () => { assert(global.service instanceof Service); done(); }); - - }) - - - - - -}) \ No newline at end of file + }); +}); diff --git a/src/tests/Syslog.test.ts b/src/tests/Syslog.test.ts index 68f521a..b13ae65 100644 --- a/src/tests/Syslog.test.ts +++ b/src/tests/Syslog.test.ts @@ -11,12 +11,11 @@ * kernel : instance of kernel who launch the test * */ -//import { expect, assert as assertChai} from 'chai' -import Syslog ,{ conditionsInterface}from "../syslog/Syslog"; +//import { expect, assert as assertChai} from 'chai' +import Syslog, { conditionsInterface } from "../syslog/Syslog"; //import nodefony from "../Nodefony" -import Pdu from '../syslog/Pdu' -import assert from 'node:assert'; - +import Pdu from "../syslog/Pdu"; +import assert from "node:assert"; class TestSyslog extends Syslog { _eventsCount?: number; @@ -26,22 +25,26 @@ class TestPdu extends Pdu { before?: string; } -declare let global: NodeJS.Global & { syslog: TestSyslog , logger: Function, Pdu: TestPdu }; +declare let global: NodeJS.Global & { + syslog: TestSyslog; + logger: Function; + Pdu: TestPdu; +}; -const defaultOptions : conditionsInterface = { +const defaultOptions: conditionsInterface = { severity: { operator: "<=", - data: "7" - } + data: "7", + }, }; describe("NODEFONY SYSLOG", () => { before(() => { global.syslog = new Syslog(); - + global.syslog.listenWithConditions( defaultOptions, - (pdu : Pdu) => + (pdu: Pdu) => // nodefony.Syslog.normalizeLog(pdu); true ); @@ -65,39 +68,33 @@ describe("NODEFONY SYSLOG", () => { }); it("Check options moduleName ", (done) => { const inst = new Syslog({ - moduleName: "MYMODULE" + moduleName: "MYMODULE", + }); + inst.listenWithConditions(defaultOptions, (pdu: Pdu) => { + assert.strict.equal(pdu.moduleName, "MYMODULE"); + assert.strict.equal(pdu.severity, 7); + assert.strict.equal(pdu.payload, "test"); }); - inst.listenWithConditions( - defaultOptions, - (pdu: Pdu) => { - assert.strict.equal(pdu.moduleName, "MYMODULE"); - assert.strict.equal(pdu.severity, 7); - assert.strict.equal(pdu.payload, "test"); - } - ); inst.log("test"); done(); }); it("Check options sevirity ", (done) => { const inst = new Syslog({ moduleName: "MYMODULE2", - defaultSeverity: "ALERT" + defaultSeverity: "ALERT", + }); + inst.listenWithConditions(defaultOptions, (pdu: Pdu) => { + assert.strict.equal(pdu.moduleName, "MYMODULE2"); + assert.strict.equal(pdu.severity, 1); + assert.strict.equal(pdu.payload, "test"); }); - inst.listenWithConditions( - defaultOptions, - (pdu: Pdu) => { - assert.strict.equal(pdu.moduleName, "MYMODULE2"); - assert.strict.equal(pdu.severity, 1); - assert.strict.equal(pdu.payload, "test"); - } - ); inst.log("test"); done(); }); it("Change stack size ", (done) => { const inst = new Syslog({ - maxStack: 500 + maxStack: 500, }); for (let i = 0; i < 1000; i++) { inst.log(i); @@ -137,12 +134,9 @@ describe("NODEFONY SYSLOG", () => { it("1000 entries ", (done) => { let i = 0; - global.syslog.on( - "onLog", - (pdu) => i++ - ); + global.syslog.on("onLog", (pdu) => i++); for (let i = 0; i < 1000; i++) { - global.syslog.log(i, i % 2 ? "INFO" : "DEBUG"); + global.syslog.log(i, i % 2 ? "INFO" : "DEBUG"); } assert.strict.equal(global.syslog.ringStack.length, 100); assert.strict.equal(global.syslog.ringStack[0].payload, 900); @@ -180,8 +174,8 @@ describe("NODEFONY SYSLOG", () => { it("getLogs 1000 entries ", (done) => { const res: conditionsInterface = global.syslog.getLogs({ severity: { - data: "INFO" - } + data: "INFO", + }, }); assert.strict.equal(res.length, 50); done(); @@ -189,10 +183,9 @@ describe("NODEFONY SYSLOG", () => { }); describe("loadStack ", () => { - it("loadStack 1000 entries ", (done) => { const inst = new Syslog({ - maxStack: 100 + maxStack: 100, }); inst.loadStack(global.syslog.ringStack); assert.strict.equal(inst.ringStack.length, 100); @@ -201,17 +194,20 @@ describe("NODEFONY SYSLOG", () => { it("loadStack 1000 events ", (done) => { const inst = new Syslog({ - maxStack: 100 + maxStack: 100, }); let i = 0; - inst.listenWithConditions({ - severity: { - data: "INFO" + inst.listenWithConditions( + { + severity: { + data: "INFO", + }, + }, + (pdu: Pdu) => { + i++; + // nodefony.Syslog.normalizeLog(pdu); } - }, (pdu: Pdu) => { - i++; - // nodefony.Syslog.normalizeLog(pdu); - }); + ); inst.loadStack(global.syslog.ringStack, true); assert.strict.equal(inst.ringStack.length, 100); assert.strict.equal(i, 50); @@ -220,23 +216,26 @@ describe("NODEFONY SYSLOG", () => { it("loadStack 1000 events ", (done) => { const inst = new Syslog({ - maxStack: 100 + maxStack: 100, }); let i = 0; - inst.listenWithConditions({ - severity: { - data: "INFO" + inst.listenWithConditions( + { + severity: { + data: "INFO", + }, + }, + (pdu: Pdu) => { + i++; + // nodefony.Syslog.normalizeLog(pdu); } - }, (pdu: Pdu) => { - i++; - // nodefony.Syslog.normalizeLog(pdu); - }); + ); inst.loadStack(global.syslog.ringStack, true, (pdu: TestPdu) => { - (pdu as TestPdu ).before = "add"; + (pdu as TestPdu).before = "add"; }); assert.strict.equal(inst.ringStack.length, 100); assert.strict.equal(i, 50); - assert.strict.equal((inst.getLogStack() as TestPdu ).before, "add"); + assert.strict.equal((inst.getLogStack() as TestPdu).before, "add"); done(); }); }); @@ -247,69 +246,58 @@ describe("NODEFONY SYSLOG", () => { }); it("LOG sevirity ", (done) => { let i = 0; - global.syslog.listenWithConditions( - defaultOptions, - (pdu: Pdu) => { - switch (pdu.severityName) { - case "EMERGENCY": - { + global.syslog.listenWithConditions(defaultOptions, (pdu: Pdu) => { + switch (pdu.severityName) { + case "EMERGENCY": { assert.strict.equal(pdu.severity, 0); assert.strict.equal(pdu.msgid, "MYMODULE0"); i++; break; } - case "ALERT": - { + case "ALERT": { i++; assert.strict.equal(pdu.severity, 1); assert.strict.equal(pdu.msgid, "MYMODULE1"); break; } - case "CRITIC": - { + case "CRITIC": { assert.strict.equal(pdu.severity, 2); assert.strict.equal(pdu.msgid, "MYMODULE2"); i++; break; } - case "ERROR": - { + case "ERROR": { assert.strict.equal(pdu.severity, 3); assert.strict.equal(pdu.msgid, "MYMODULE3"); i++; break; } - case "WARNING": - { + case "WARNING": { assert.strict.equal(pdu.severity, 4); assert.strict.equal(pdu.msgid, "MYMODULE4"); i++; break; } - case "NOTICE": - { + case "NOTICE": { assert.strict.equal(pdu.severity, 5); assert.strict.equal(pdu.msgid, "MYMODULE5"); i++; break; } - case "INFO": - { + case "INFO": { assert.strict.equal(pdu.severity, 6); assert.strict.equal(pdu.msgid, "MYMODULE6"); i++; break; } - case "DEBUG": - { + case "DEBUG": { assert.strict.equal(pdu.severity, 7); assert.strict.equal(pdu.msgid, "MYMODULE7"); i++; break; } - } } - ); + }); global.syslog.log("test", "EMERGENCY", "MYMODULE0"); global.syslog.log("test", "ALERT", "MYMODULE1"); global.syslog.log("test", "CRITIC", "MYMODULE2"); @@ -331,13 +319,10 @@ describe("NODEFONY SYSLOG", () => { it("listener ", (done) => { let i = 0; - global.syslog.listenWithConditions( - defaultOptions, - (pdu: Pdu) => i++ - ); + global.syslog.listenWithConditions(defaultOptions, (pdu: Pdu) => i++); assert.strict.equal(global.syslog._eventsCount, 1); for (let i = 0; i < 10; i++) { - global.syslog.log(i, i % 2 ? "INFO" : "DEBUG"); + global.syslog.log(i, i % 2 ? "INFO" : "DEBUG"); } assert.strict.equal(i, 10); done(); @@ -349,8 +334,8 @@ describe("NODEFONY SYSLOG", () => { { severity: { operator: "<=", - data: "INFO" - } + data: "INFO", + }, }, (pdu: Pdu) => i++ ); @@ -368,10 +353,10 @@ describe("NODEFONY SYSLOG", () => { { severity: { operator: "<=", - data: "INFO" - } + data: "INFO", + }, }, - (pdu : Pdu) => { + (pdu: Pdu) => { assert.strict.equal(pdu.severity, 6); assert.strict.equal(pdu.severityName, "INFO"); return i++; @@ -390,11 +375,11 @@ describe("NODEFONY SYSLOG", () => { global.syslog.listenWithConditions( { severity: { - data: 6 - } + data: 6, + }, }, (pdu: Pdu) => { - // nodefony.Syslog.normalizeLog(pdu); + // nodefony.Syslog.normalizeLog(pdu); assert.strict.equal(pdu.severity, 6); assert.strict.equal(pdu.severityName, "INFO"); return i++; @@ -413,11 +398,11 @@ describe("NODEFONY SYSLOG", () => { { severity: { operator: "==", - data: "7" - } + data: "7", + }, }, (pdu: Pdu) => { - // nodefony.Syslog.normalizeLog(pdu); + // nodefony.Syslog.normalizeLog(pdu); assert.strict.equal(pdu.severity, 7); assert.strict.equal(pdu.severityName, "DEBUG"); return i++; @@ -425,7 +410,7 @@ describe("NODEFONY SYSLOG", () => { ); assert.strict.equal(global.syslog._eventsCount, 1); for (let i = 0; i < 10; i++) { - global.syslog.log(i, i % 2 ? "INFO" : "DEBUG"); + global.syslog.log(i, i % 2 ? "INFO" : "DEBUG"); } assert.strict.equal(i, 5); done(); @@ -436,8 +421,8 @@ describe("NODEFONY SYSLOG", () => { global.syslog.listenWithConditions( { severity: { - data: "INFO,DEBUG,WARNING" - } + data: "INFO,DEBUG,WARNING", + }, }, (pdu: Pdu) => // nodefony.Syslog.normalizeLog(pdu); @@ -452,8 +437,8 @@ describe("NODEFONY SYSLOG", () => { global.syslog.listenWithConditions( { severity: { - data: ["INFO", "WARNING", "DEBUG"] - } + data: ["INFO", "WARNING", "DEBUG"], + }, }, (pdu: Pdu) => // nodefony.Syslog.normalizeLog(pdu); @@ -468,8 +453,8 @@ describe("NODEFONY SYSLOG", () => { global.syslog.listenWithConditions( { severity: { - data: ["6", "4", "7"] - } + data: ["6", "4", "7"], + }, }, (pdu: Pdu) => // nodefony.Syslog.normalizeLog(pdu); @@ -484,8 +469,8 @@ describe("NODEFONY SYSLOG", () => { global.syslog.listenWithConditions( { severity: { - data: [6, 4, 7] - } + data: [6, 4, 7], + }, }, (pdu: Pdu) => // nodefony.Syslog.normalizeLog(pdu); @@ -502,8 +487,8 @@ describe("NODEFONY SYSLOG", () => { { severity: { operator: ">=", - data: 4 - } + data: 4, + }, }, (pdu: Pdu) => // nodefony.Syslog.normalizeLog(pdu); @@ -519,8 +504,8 @@ describe("NODEFONY SYSLOG", () => { { severity: { operator: ">", - data: 4 - } + data: 4, + }, }, (pdu: Pdu) => // nodefony.Syslog.normalizeLog(pdu); @@ -536,8 +521,8 @@ describe("NODEFONY SYSLOG", () => { { severity: { operator: "<", - data: 4 - } + data: 4, + }, }, (pdu: Pdu) => // nodefony.Syslog.normalizeLog(pdu); @@ -553,8 +538,8 @@ describe("NODEFONY SYSLOG", () => { { severity: { operator: "<", - data: "WARNING" - } + data: "WARNING", + }, }, (pdu: Pdu) => // nodefony.Syslog.normalizeLog(pdu); @@ -570,32 +555,33 @@ describe("NODEFONY SYSLOG", () => { beforeEach(() => { global.syslog.reset(); }); - it("listener condition MSGID ", () => new Promise((resolve, reject) => { - let i = 0; - global.syslog.listenWithConditions( - { - msgid: { - data: "NODEFONY" + it("listener condition MSGID ", () => + new Promise((resolve, reject) => { + let i = 0; + global.syslog.listenWithConditions( + { + msgid: { + data: "NODEFONY", + }, + severity: { + data: ["INFO", "ERROR"], + }, }, - severity:{ - data:["INFO","ERROR"] - } - }, - (pdu : Pdu) => { - i++; - // nodefony.Syslog.normalizeLog(pdu); - assert.strict.equal(pdu.msgid, "NODEFONY"); - assert.strict.equal(pdu.payload, "pass"); - if (i === 3) { - resolve(true); + (pdu: Pdu) => { + i++; + // nodefony.Syslog.normalizeLog(pdu); + assert.strict.equal(pdu.msgid, "NODEFONY"); + assert.strict.equal(pdu.payload, "pass"); + if (i === 3) { + resolve(true); + } } - } - ); - global.syslog.log("pass", "INFO", "NODEFONY"); - global.syslog.log("nopass", "INFO"); - global.syslog.log("pass", "INFO", "NODEFONY"); - global.syslog.log("nopass", "DEBUG", "NODEFONY"); - global.syslog.log("pass", "ERROR", "NODEFONY"); - })); + ); + global.syslog.log("pass", "INFO", "NODEFONY"); + global.syslog.log("nopass", "INFO"); + global.syslog.log("pass", "INFO", "NODEFONY"); + global.syslog.log("nopass", "DEBUG", "NODEFONY"); + global.syslog.log("pass", "ERROR", "NODEFONY"); + })); }); }); diff --git a/src/tests/cli.test.ts b/src/tests/cli.test.ts index 5b90e79..22dc761 100644 --- a/src/tests/cli.test.ts +++ b/src/tests/cli.test.ts @@ -1,18 +1,17 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { assert } from 'chai'; -import 'mocha'; -import clc from 'cli-color' -import Cli ,{CliDefaultOptions} from '../Cli' +import { assert } from "chai"; +import "mocha"; +import clc from "cli-color"; +import Cli, { CliDefaultOptions } from "../Cli"; //console.log(Cli) -import path from "node:path" -let processName: string| null = null; +import path from "node:path"; +let processName: string | null = null; if (process.argv && process.argv[1]) { processName = path.basename(process.argv[1]); } else { processName = process.title || "nodefony"; } - describe("NODEFONY CLI", () => { beforeEach(() => {}); @@ -27,7 +26,7 @@ describe("NODEFONY CLI", () => { assert.strictEqual(project.name, "project"); assert.strictEqual(project.commander.version(), "2.0.0"); const options = { - processName , + processName, autostart: true, asciify: true, clear: false, @@ -40,25 +39,30 @@ describe("NODEFONY CLI", () => { version: "2.0.0", warning: false, pid: true, - promiseRejection: true + promiseRejection: true, }; assert.deepStrictEqual(options, project.options); - const banner = ` Version : ${clc.blueBright.bold("2.0.0")} Platform : ${clc.green(process.platform)} Process : ${clc.green("project")} Pid : ${project.pid}`; + const banner = ` Version : ${clc.blueBright.bold( + "2.0.0" + )} Platform : ${clc.green(process.platform)} Process : ${clc.green( + "project" + )} Pid : ${project.pid}`; let res = null; - project.start() - .then((cli :Cli) => { + project + .start() + .then((cli: Cli) => { res = cli.showBanner(); assert.strictEqual(banner, res); - + res = cli.terminate(0, true); assert.strictEqual(res, 0); done(); }) .catch((e) => { - console.error(e) + console.error(e); throw e; }); }); }); -}); \ No newline at end of file +}); diff --git a/src/tests/command/Builder.test.ts b/src/tests/command/Builder.test.ts index 1d0613c..ae6a9ca 100644 --- a/src/tests/command/Builder.test.ts +++ b/src/tests/command/Builder.test.ts @@ -1,97 +1,113 @@ // Builder.test.ts //mport fs from 'node:fs' -import { expect } from 'chai'; -import 'mocha'; -import Builder, {BuilderObject}from '../../command/Builder'; -import path from 'path'; -import Cli from '../../Cli'; -import Command from '../../command/Command'; +import { expect } from "chai"; +import "mocha"; +import Builder, { BuilderObject } from "../../command/Builder"; +import path from "path"; +import Cli from "../../Cli"; +import Command from "../../command/Command"; -describe('FileManager', () => { +describe("FileManager", () => { let builder: Builder; - let cli :Cli ; + let cli: Cli; beforeEach(async () => { - cli = new Cli("NODE",{ - clear:false, - asciify:false, - autostart:false - }) - builder = new Builder(new Command("start", "start framawork", cli)); + cli = new Cli("NODE", { + clear: false, + asciify: false, + autostart: false, + }); + builder = new Builder(new Command("start", "start framawork", cli)); }); - it('devrait construire un répertoire', async () => { + it("devrait construire un répertoire", async () => { // Définissez vos données de test const objetRepertoire: BuilderObject = { - name: 'testRepertoire', - type: 'directory' + name: "testRepertoire", + type: "directory", }; - const resultat = await builder.build(objetRepertoire, path.resolve(process.cwd(), "tmp") ,true); + const resultat = await builder.build( + objetRepertoire, + path.resolve(process.cwd(), "tmp"), + true + ); expect(resultat).not.to.be.null; - expect(resultat?.name).to.equal('testRepertoire'); + expect(resultat?.name).to.equal("testRepertoire"); }); - it('devrait construire un fichier', async () => { + it("devrait construire un fichier", async () => { // Définissez vos données de test const objetFichier: BuilderObject = { - name: 'testFichier', - type: 'file' + name: "testFichier", + type: "file", }; - const resultat = await builder.build(objetFichier, path.resolve(process.cwd(), "tmp") ); + const resultat = await builder.build( + objetFichier, + path.resolve(process.cwd(), "tmp") + ); //console.log(resultat) - expect(resultat).not.be.null + expect(resultat).not.be.null; }); - it('devrait créer un symlink', async () => { + it("devrait créer un symlink", async () => { const objetSymlink: BuilderObject = { - name: 'testSymlink', - type: 'symlink', + name: "testSymlink", + type: "symlink", params: { - source: path.resolve(process.cwd(), "tmp",'testFichier'), - dest: path.resolve(process.cwd(), "tmp", 'testSymlink'), + source: path.resolve(process.cwd(), "tmp", "testFichier"), + dest: path.resolve(process.cwd(), "tmp", "testSymlink"), }, }; - const resultat = await builder.build(objetSymlink, path.resolve(process.cwd(), "tmp") , true); + const resultat = await builder.build( + objetSymlink, + path.resolve(process.cwd(), "tmp"), + true + ); expect(resultat).not.be.null; //console.log(resultat) }); - it('devrait construire un répertoire avec des enfants de manière récursive', async () => { + it("devrait construire un répertoire avec des enfants de manière récursive", async () => { //await fs.promises.mkdir(path.resolve(process.cwd(), "tmp",'sboob'), { mode: 0o755 }); const objetParent: BuilderObject = { - name: 'parentDirectory', - type: 'directory', - childs: [{ - name: 'childFile', - type: 'file', - }, { - name: 'childDirectory', - type: 'directory', - childs: [{ - name: 'grandchildFile', - type: 'file', - }], - }] + name: "parentDirectory", + type: "directory", + childs: [ + { + name: "childFile", + type: "file", + }, + { + name: "childDirectory", + type: "directory", + childs: [ + { + name: "grandchildFile", + type: "file", + }, + ], + }, + ], }; - const parentDirectory = await builder.build(objetParent, path.resolve(process.cwd(), "tmp"), true); + const parentDirectory = await builder.build( + objetParent, + path.resolve(process.cwd(), "tmp"), + true + ); expect(parentDirectory).to.not.be.null; - expect(parentDirectory?.name).to.equal('parentDirectory'); + expect(parentDirectory?.name).to.equal("parentDirectory"); //console.log(parentDirectory) - }); - it('devrait copier un fichier avec succès', async () => { - + it("devrait copier un fichier avec succès", async () => { const destinationFile: BuilderObject = { - name: 'src', - type: 'copy', - path: path.resolve(process.cwd(), 'src',"tests"), + name: "src", + type: "copy", + path: path.resolve(process.cwd(), "src", "tests"), params: { - recurse: true, // Exemple de paramètre pour une copie récursive - } + recurse: true, // Exemple de paramètre pour une copie récursive + }, }; // Utilisez la fonction de copie - await builder.build(destinationFile, path.resolve(process.cwd(), "tmp")); - + await builder.build(destinationFile, path.resolve(process.cwd(), "tmp")); }); - }); diff --git a/src/tests/command/Command.test.ts b/src/tests/command/Command.test.ts index f627182..79483c8 100644 --- a/src/tests/command/Command.test.ts +++ b/src/tests/command/Command.test.ts @@ -1,41 +1,46 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import assert from 'node:assert'; -import 'mocha'; -import Command from '../../command/Command'; -import Cli from '../../Cli' - -describe('Command', () => { - - beforeEach(() => {}) - - - describe ('Instance' , ()=>{ - beforeEach(() => {}) - - it('instance', ()=>{ - const inst = new Command("start1", "start1 framawork") - assert(inst) - assert.equal(inst.name, "start1") - }) - - it('instance Cli', async ()=>{ - return new Cli("NODE",{ - clear:false, - autostart:false - }) - .start() - .then((cli )=>{ - new Command("start3", "start3 framawork", cli) - const inst2 = new Command("start2", "start2 framawork", cli) - assert(inst2) - assert.equal(inst2.name, "start2") - inst2.parse(["node","node", "start3", "-i", "-d" ]) - }) - - - }) - - }) - - -}) \ No newline at end of file +import assert from "node:assert"; +import "mocha"; +import Command, { OptionsCommandInterface } from "../../command/Command"; +import Cli from "../../Cli"; + +describe("Command", () => { + beforeEach(() => {}); + describe("Instance", () => { + beforeEach(() => {}); + it("instance", () => { + const inst = new Command("start1", "start1 framawork"); + assert(inst); + assert.equal(inst.name, "start1"); + }); + it("instance Cli", async () => { + return new Cli("NODE", { + clear: false, + autostart: false, + asciify: false, + }) + .start() + .then((cli) => { + const options: OptionsCommandInterface = { + showBanner: false, + }; + const inst2 = new Command("start2", "start2 framawork", cli, options); + const inst3 = new Command("start3", "start3 framawork", cli, options); + assert(inst2); + assert(inst3); + assert.equal(inst2.name, "start2"); + assert.equal(inst3.name, "start3"); + cli.runCommand("start2", ["-i", "-d"]); + assert.strictEqual(inst2.debug, true); + assert.strictEqual(inst2.interactive, true); + + inst3.runCommand("start3", ["-i"]); + assert.strictEqual(inst3.debug, false); + assert.strictEqual(inst3.interactive, true); + inst3.runCommand("start3"); + assert.strictEqual(inst3.debug, false); + assert.strictEqual(inst3.interactive, false); + }); + }); + }); +}); diff --git a/src/tests/index.ts b/src/tests/index.ts index 7db480c..0716621 100644 --- a/src/tests/index.ts +++ b/src/tests/index.ts @@ -1,15 +1,13 @@ -import { expect } from 'chai'; -import 'mocha'; -import nodefony from '../index'; +import { expect } from "chai"; +import "mocha"; +import nodefony from "../index"; -describe('Index', () => { - beforeEach(() => {}) +describe("Index", () => { + beforeEach(() => {}); - it('Index Singleton', () => { - const inst = new nodefony.Container() - expect(inst).to.be.instanceOf(nodefony.Container) + it("Index Singleton", () => { + const inst = new nodefony.Container(); + expect(inst).to.be.instanceOf(nodefony.Container); //console.log( kernel) }); - -}) - +}); diff --git a/src/types/globals.d.ts b/src/types/globals.d.ts index ed0ba11..f7b08db 100644 --- a/src/types/globals.d.ts +++ b/src/types/globals.d.ts @@ -1,5 +1,4 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ export interface nodefonyOptions { - [key: string]: any; + [key: string]: any; } - diff --git a/src/types/types.d.ts b/src/types/types.d.ts index d8bab8e..ace81c8 100644 --- a/src/types/types.d.ts +++ b/src/types/types.d.ts @@ -1,42 +1,42 @@ // Importez chaque déclaration de type individuelle -import Globals from './globals'; +import Globals from "./globals"; -import Index from '../../dist/types/src/index'; -import Container from '../../dist/types/src/Container'; -import nodefonyError from '../../dist/types/src/Error'; -import Event from '../../dist/types/src/Event'; -import Fileclass from '../../dist/types/src/FileClass'; -import Kernel from '../../dist/types/src/Kernel'; -import nodefony from '../../dist/types/src/Nodefony'; -import Service from '../../dist/types/src/Service'; -import Tool from '../../dist/types/src/Tools'; -import Syslog from '../../dist/types/src/syslog/Syslog'; -import Pdu from '../../dist/types/src/syslog/Pdu'; -import File from '../../dist/types/src/finder/File'; -import FileResult from '../../dist/types/src/finder/FileResult'; -import Finder from '../../dist/types/src/finder/Finder'; -import Result from '../../dist/types/src/finder/Result'; -import Command from '../../dist/types/src/command/Command'; -import Builder from '../../dist/types/src/command/Builder'; +import Index from "../../dist/types/src/index"; +import Container from "../../dist/types/src/Container"; +import nodefonyError from "../../dist/types/src/Error"; +import Event from "../../dist/types/src/Event"; +import Fileclass from "../../dist/types/src/FileClass"; +import Kernel from "../../dist/types/src/Kernel"; +import nodefony from "../../dist/types/src/Nodefony"; +import Service from "../../dist/types/src/Service"; +import Tool from "../../dist/types/src/Tools"; +import Syslog from "../../dist/types/src/syslog/Syslog"; +import Pdu from "../../dist/types/src/syslog/Pdu"; +import File from "../../dist/types/src/finder/File"; +import FileResult from "../../dist/types/src/finder/FileResult"; +import Finder from "../../dist/types/src/finder/Finder"; +import Result from "../../dist/types/src/finder/Result"; +import Command from "../../dist/types/src/command/Command"; +import Builder from "../../dist/types/src/command/Builder"; // Exportez tous les types -export { - Globals, - Index, - Container, - nodefonyError, - Event, - Fileclass, - Kernel, - nodefony, - Service, - Tool, - Syslog, +export { + Globals, + Index, + Container, + nodefonyError, + Event, + Fileclass, + Kernel, + nodefony, + Service, + Tool, + Syslog, Pdu, File, FileResult, Finder, Result, Command, - Builder + Builder, };