@modern-js/plugin-proxy 1.1.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,45 @@
1
1
  # @modern-js/plugin-proxy
2
2
 
3
+ ## 1.2.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 83166714: change .npmignore
8
+ - Updated dependencies [83166714]
9
+ - Updated dependencies [c3de9882]
10
+ - Updated dependencies [33ff48af]
11
+ - @modern-js/core@1.3.2
12
+ - @modern-js/utils@1.2.2
13
+
14
+ ## 1.2.1
15
+
16
+ ### Patch Changes
17
+
18
+ - e2d3a575: fix extending core config interface
19
+ - e2d3a575: fix extending core config interface
20
+ - Updated dependencies [823809c6]
21
+ - Updated dependencies [4584cc04]
22
+ - Updated dependencies [7c19fd94]
23
+ - @modern-js/utils@1.2.1
24
+ - @modern-js/core@1.3.1
25
+
26
+ ## 1.2.0
27
+
28
+ ### Minor Changes
29
+
30
+ - cfe11628: Make Modern.js self bootstraping
31
+
32
+ ### Patch Changes
33
+
34
+ - f6932de7: fix proxy bin error
35
+ - bc87647d: fix: terminate whistle proxy when exiting the process
36
+ - Updated dependencies [2da09c69]
37
+ - Updated dependencies [fc71e36f]
38
+ - Updated dependencies [c3d46ee4]
39
+ - Updated dependencies [cfe11628]
40
+ - @modern-js/utils@1.2.0
41
+ - @modern-js/core@1.3.0
42
+
3
43
  ## 1.1.1
4
44
 
5
45
  ### Patch Changes
@@ -2,6 +2,7 @@ import { createPlugin, useAppContext, useResolvedConfigContext } from '@modern-j
2
2
  import { PLUGIN_SCHEMAS } from '@modern-js/utils';
3
3
  import { createProxyRule } from "./utils/createProxyRule";
4
4
  import WhistleProxy from "./utils/whistleProxy";
5
+ let proxyServer;
5
6
  export default createPlugin(() => ({
6
7
  validateSchema() {
7
8
  return PLUGIN_SCHEMAS['@modern-js/plugin-proxy'];
@@ -17,20 +18,23 @@ export default createPlugin(() => ({
17
18
  } = useAppContext();
18
19
  /* eslint-enable react-hooks/rules-of-hooks */
19
20
 
20
- if (!dev.proxy) {
21
+ if (!(dev !== null && dev !== void 0 && dev.proxy)) {
21
22
  return;
22
23
  }
23
24
 
24
25
  const rule = createProxyRule(internalDirectory, dev.proxy);
25
- const proxyServer = new WhistleProxy({
26
+ proxyServer = new WhistleProxy({
26
27
  port: 8899,
27
28
  rule
28
29
  });
29
- await proxyServer.start(); // TODO
30
- // should exit proxy server before process exit
31
- // api.on('process-exit', () => {
32
- // proxyServer.close();
33
- // });
30
+ await proxyServer.start();
31
+ },
32
+
33
+ beforeExit() {
34
+ var _proxyServer;
35
+
36
+ // terminate whistle proxy
37
+ (_proxyServer = proxyServer) === null || _proxyServer === void 0 ? void 0 : _proxyServer.close();
34
38
  }
35
39
 
36
40
  }), {
@@ -35,7 +35,7 @@ export const generateRootCA = () => new Promise((resolve, reject) => {
35
35
 
36
36
  fs.ensureDirSync(defaultCertDir);
37
37
  const stream = fs.createWriteStream(defaultRootCA);
38
- http.get('http://127.0.0.1:8899/cgi-bin/rootca', response => {
38
+ http.get('http://localhost:8899/cgi-bin/rootca', response => {
39
39
  response.pipe(stream);
40
40
  stream.on('finish', () => {
41
41
  resolve(defaultRootCA);
@@ -16,7 +16,7 @@ const getNetworkType = () => {
16
16
  };
17
17
 
18
18
  export const enableGlobalProxy = (ip, port) => {
19
- const networkType = getNetworkType(); // && networksetup -setproxybypassdomains ${networkType} 127.0.0.1 localhost
19
+ const networkType = getNetworkType(); // && networksetup -setproxybypassdomains ${networkType} localhost localhost
20
20
 
21
21
  execSync(`networksetup -setwebproxy ${networkType} ${ip} ${port}`);
22
22
  execSync(`networksetup -setsecurewebproxy ${networkType} ${ip} ${port}`);
@@ -39,14 +39,14 @@ export default class WhistleProxy {
39
39
  execSync(`${this.bin} start --certDir=${this.certDir} --port=${this.port}`);
40
40
  execSync(`${this.bin} use ${this.rule} --force`);
41
41
  await this.installRootCA();
42
- enableGlobalProxy('127.0.0.1', this.port);
42
+ enableGlobalProxy('localhost', this.port);
43
43
  logger.info(`Proxy Server start on localhost:${this.port}\n`);
44
44
  }
45
45
 
46
46
  close() {
47
47
  execSync(`${this.bin} stop`);
48
48
  disableGlobalProxy();
49
- logger.info(`Proxy Server has closed`);
49
+ logger.info(`Proxy Server has been closed`);
50
50
  }
51
51
 
52
52
  }
@@ -15,6 +15,8 @@ var _whistleProxy = _interopRequireDefault(require("./utils/whistleProxy"));
15
15
 
16
16
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
17
 
18
+ let proxyServer;
19
+
18
20
  var _default = (0, _core.createPlugin)(() => ({
19
21
  validateSchema() {
20
22
  return _utils.PLUGIN_SCHEMAS['@modern-js/plugin-proxy'];
@@ -30,20 +32,23 @@ var _default = (0, _core.createPlugin)(() => ({
30
32
  } = (0, _core.useAppContext)();
31
33
  /* eslint-enable react-hooks/rules-of-hooks */
32
34
 
33
- if (!dev.proxy) {
35
+ if (!(dev !== null && dev !== void 0 && dev.proxy)) {
34
36
  return;
35
37
  }
36
38
 
37
39
  const rule = (0, _createProxyRule.createProxyRule)(internalDirectory, dev.proxy);
38
- const proxyServer = new _whistleProxy.default({
40
+ proxyServer = new _whistleProxy.default({
39
41
  port: 8899,
40
42
  rule
41
43
  });
42
- await proxyServer.start(); // TODO
43
- // should exit proxy server before process exit
44
- // api.on('process-exit', () => {
45
- // proxyServer.close();
46
- // });
44
+ await proxyServer.start();
45
+ },
46
+
47
+ beforeExit() {
48
+ var _proxyServer;
49
+
50
+ // terminate whistle proxy
51
+ (_proxyServer = proxyServer) === null || _proxyServer === void 0 ? void 0 : _proxyServer.close();
47
52
  }
48
53
 
49
54
  }), {
@@ -62,7 +62,7 @@ const generateRootCA = () => new Promise((resolve, reject) => {
62
62
 
63
63
  const stream = _utils.fs.createWriteStream(defaultRootCA);
64
64
 
65
- _http.default.get('http://127.0.0.1:8899/cgi-bin/rootca', response => {
65
+ _http.default.get('http://localhost:8899/cgi-bin/rootca', response => {
66
66
  response.pipe(stream);
67
67
  stream.on('finish', () => {
68
68
  resolve(defaultRootCA);
@@ -26,7 +26,7 @@ const getNetworkType = () => {
26
26
  };
27
27
 
28
28
  const enableGlobalProxy = (ip, port) => {
29
- const networkType = getNetworkType(); // && networksetup -setproxybypassdomains ${networkType} 127.0.0.1 localhost
29
+ const networkType = getNetworkType(); // && networksetup -setproxybypassdomains ${networkType} localhost localhost
30
30
 
31
31
  (0, _execSync.default)(`networksetup -setwebproxy ${networkType} ${ip} ${port}`);
32
32
  (0, _execSync.default)(`networksetup -setsecurewebproxy ${networkType} ${ip} ${port}`);
@@ -52,7 +52,7 @@ class WhistleProxy {
52
52
  (0, _execSync.default)(`${this.bin} start --certDir=${this.certDir} --port=${this.port}`);
53
53
  (0, _execSync.default)(`${this.bin} use ${this.rule} --force`);
54
54
  await this.installRootCA();
55
- enableGlobalProxy('127.0.0.1', this.port);
55
+ enableGlobalProxy('localhost', this.port);
56
56
 
57
57
  _utils.logger.info(`Proxy Server start on localhost:${this.port}\n`);
58
58
  }
@@ -61,7 +61,7 @@ class WhistleProxy {
61
61
  (0, _execSync.default)(`${this.bin} stop`);
62
62
  disableGlobalProxy();
63
63
 
64
- _utils.logger.info(`Proxy Server has closed`);
64
+ _utils.logger.info(`Proxy Server has been closed`);
65
65
  }
66
66
 
67
67
  }
@@ -4,8 +4,6 @@ export default _default;
4
4
  export declare type ProxyOptions = string | Record<string, string>;
5
5
  declare module '@modern-js/core' {
6
6
  interface DevConfig {
7
- dev: {
8
- proxy?: ProxyOptions;
9
- };
7
+ proxy?: ProxyOptions;
10
8
  }
11
9
  }
package/jest.config.js ADDED
@@ -0,0 +1,8 @@
1
+ const sharedConfig = require('@scripts/jest-config');
2
+
3
+ /** @type {import('@jest/types').Config.InitialOptions} */
4
+ module.exports = {
5
+ // eslint-disable-next-line node/no-unsupported-features/es-syntax
6
+ ...sharedConfig,
7
+ rootDir: __dirname,
8
+ };
package/modern.config.js CHANGED
@@ -1,10 +1,2 @@
1
1
  /** @type {import('@modern-js/module-tools').UserConfig} */
2
- module.exports = {
3
- testing: {
4
- jest: {
5
- collectCoverage: true,
6
- collectCoverageFrom: ['src/**/*.ts'],
7
- coveragePathIgnorePatterns: ['/node_modules/'],
8
- },
9
- },
10
- };
2
+ module.exports = {};
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.1.1",
14
+ "version": "1.2.2",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
@@ -20,31 +20,33 @@
20
20
  "exports": {
21
21
  ".": {
22
22
  "node": {
23
+ "jsnext:source": "./src/index.ts",
23
24
  "import": "./dist/js/modern/index.js",
24
25
  "require": "./dist/js/node/index.js"
25
26
  },
26
27
  "default": "./dist/js/treeshaking/index.js"
27
28
  },
28
- "./cli": "./dist/js/node/index.js"
29
- },
30
- "bin": {
31
- "modern": "./bin/modern.js"
29
+ "./cli": {
30
+ "jsnext:source": "./src/index.ts",
31
+ "default": "./dist/js/node/index.js"
32
+ }
32
33
  },
33
34
  "dependencies": {
34
35
  "@babel/runtime": "^7",
35
- "@modern-js/utils": "^1.1.2",
36
+ "@modern-js/utils": "^1.2.2",
36
37
  "whistle": "^2.7.18"
37
38
  },
38
39
  "devDependencies": {
39
40
  "@types/jest": "^26",
40
41
  "@types/node": "^14",
41
42
  "typescript": "^4",
42
- "@modern-js/core": "^1.1.2",
43
- "@modern-js/plugin-testing": "^1.1.0",
44
- "@modern-js/module-tools": "^1.1.0"
43
+ "@modern-js/core": "^1.3.2",
44
+ "@scripts/build": "0.0.0",
45
+ "jest": "^27",
46
+ "@scripts/jest-config": "0.0.0"
45
47
  },
46
48
  "peerDependencies": {
47
- "@modern-js/core": "^1.1.2"
49
+ "@modern-js/core": "^1.3.2"
48
50
  },
49
51
  "sideEffects": false,
50
52
  "modernConfig": {
@@ -54,11 +56,13 @@
54
56
  },
55
57
  "publishConfig": {
56
58
  "registry": "https://registry.npmjs.org/",
57
- "access": "public"
59
+ "access": "public",
60
+ "types": "./dist/types/index.d.ts"
58
61
  },
59
62
  "scripts": {
60
63
  "new": "modern new",
61
64
  "build": "modern build",
62
- "test": "modern test --passWithNoTests"
63
- }
65
+ "test": "jest --passWithNoTests"
66
+ },
67
+ "readme": "\n<p align=\"center\">\n <a href=\"https://modernjs.dev\" target=\"blank\"><img src=\"https://lf3-static.bytednsdoc.com/obj/eden-cn/ylaelkeh7nuhfnuhf/modernjs-cover.png\" width=\"300\" alt=\"Modern.js Logo\" /></a>\n</p>\n<p align=\"center\">\n现代 Web 工程体系\n <br/>\n <a href=\"https://modernjs.dev\" target=\"blank\">\n modernjs.dev\n </a>\n</p>\n<p align=\"center\">\n The meta-framework suite designed from scratch for frontend-focused modern web development\n</p>\n\n# Introduction\n\n> The doc site ([modernjs.dev](https://modernjs.dev)) and articles are only available in Chinese for now, we are planning to add English versions soon.\n\n- [Modern.js: Hello, World!](https://zhuanlan.zhihu.com/p/426707646)\n\n## Getting Started\n\n- [Quick Start](https://modernjs.dev/docs/start)\n- [Guides](https://modernjs.dev/docs/guides)\n- [API References](https://modernjs.dev/docs/apis)\n\n## Contributing\n\n- [Contributing Guide](https://github.com/modern-js-dev/modern.js/blob/main/CONTRIBUTING.md)\n"
64
68
  }
@@ -0,0 +1,6 @@
1
+ module.exports = {
2
+ extends: ['@modern-js'],
3
+ parserOptions: {
4
+ project: require.resolve('./tsconfig.json'),
5
+ },
6
+ };
@@ -0,0 +1,19 @@
1
+ // Jest Snapshot v1, https://goo.gl/fbAQLP
2
+
3
+ exports[`plugin proxy test config 1`] = `Array []`;
4
+
5
+ exports[`plugin proxy test schema 1`] = `
6
+ Array [
7
+ Array [
8
+ Object {
9
+ "schema": Object {
10
+ "typeof": Array [
11
+ "string",
12
+ "object",
13
+ ],
14
+ },
15
+ "target": "dev.proxy",
16
+ },
17
+ ],
18
+ ]
19
+ `;
@@ -0,0 +1,39 @@
1
+ import path from 'path';
2
+ import { manager } from '@modern-js/core';
3
+ import plugin from '../src';
4
+
5
+ const root = path.normalize(path.resolve(__dirname, '../../../../'));
6
+ expect.addSnapshotSerializer({
7
+ test: val =>
8
+ typeof val === 'string' &&
9
+ (val.includes('modern.js') ||
10
+ val.includes('node_modules') ||
11
+ val.includes(root)),
12
+ print: val =>
13
+ // eslint-disable-next-line no-nested-ternary
14
+ typeof val === 'string'
15
+ ? // eslint-disable-next-line no-nested-ternary
16
+ val.includes('node_modules')
17
+ ? `"${val.replace(/.+node_modules/, '')}"`
18
+ : val.includes('modern.js')
19
+ ? `"${val.replace(/.+modern\.js/, '')}"`
20
+ : `"${val.replace(root, '')}"`
21
+ : (val as string),
22
+ });
23
+
24
+ describe('plugin proxy test', () => {
25
+ it('schema', async () => {
26
+ const main = manager.clone().usePlugin(plugin);
27
+ const runner = await main.init();
28
+ const result = await runner.validateSchema();
29
+
30
+ expect(result).toMatchSnapshot();
31
+ });
32
+
33
+ it('config', async () => {
34
+ const main = manager.clone().usePlugin(plugin);
35
+ const runner = await main.init();
36
+ const result = await runner.config();
37
+ expect(result).toMatchSnapshot();
38
+ });
39
+ });
@@ -0,0 +1,14 @@
1
+ {
2
+ "extends": "@modern-js/tsconfig/base",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "jsx": "preserve",
6
+ "baseUrl": ".",
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "esModuleInterop": true,
10
+ "isolatedModules": true,
11
+ "paths": {},
12
+ "types": ["node", "jest"]
13
+ }
14
+ }
package/tsconfig.json CHANGED
@@ -5,9 +5,7 @@
5
5
  "jsx": "preserve",
6
6
  "baseUrl": "./",
7
7
  "isolatedModules": true,
8
- "paths": {
9
- "@/*": ["./src/*"]
10
- }
8
+ "paths": {}
11
9
  },
12
10
  "include": ["src"]
13
11
  }
package/src/index.ts DELETED
@@ -1,47 +0,0 @@
1
- import {
2
- createPlugin,
3
- useAppContext,
4
- useResolvedConfigContext,
5
- } from '@modern-js/core';
6
- import { PLUGIN_SCHEMAS } from '@modern-js/utils';
7
- import { createProxyRule } from './utils/createProxyRule';
8
- import WhistleProxy from './utils/whistleProxy';
9
-
10
- export default createPlugin(
11
- () => ({
12
- validateSchema() {
13
- return PLUGIN_SCHEMAS['@modern-js/plugin-proxy'];
14
- },
15
- async afterDev() {
16
- /* eslint-disable react-hooks/rules-of-hooks */
17
- const { dev } = useResolvedConfigContext();
18
- const { internalDirectory } = useAppContext();
19
- /* eslint-enable react-hooks/rules-of-hooks */
20
-
21
- if (!(dev as any).proxy) {
22
- return;
23
- }
24
-
25
- const rule = createProxyRule(internalDirectory, (dev as any).proxy);
26
- const proxyServer = new WhistleProxy({ port: 8899, rule });
27
- await proxyServer.start();
28
-
29
- // TODO
30
- // should exit proxy server before process exit
31
- // api.on('process-exit', () => {
32
- // proxyServer.close();
33
- // });
34
- },
35
- }),
36
- { name: '@modern-js/plugin-proxy' },
37
- ) as any;
38
-
39
- export type ProxyOptions = string | Record<string, string>;
40
-
41
- declare module '@modern-js/core' {
42
- export interface DevConfig {
43
- dev: {
44
- proxy?: ProxyOptions;
45
- };
46
- }
47
- }
@@ -1,50 +0,0 @@
1
- import path from 'path';
2
- import { logger, fs } from '@modern-js/utils';
3
- import type { ProxyOptions } from '..';
4
-
5
- interface ProxyRule {
6
- pattern: string;
7
- target: string;
8
- }
9
-
10
- const createWhistleProxyRule = (ruleDirectory: string, rules: ProxyRule[]) => {
11
- const dest = path.resolve(ruleDirectory, 'proxy.rule.js');
12
-
13
- let code = `/.*/ enable://intercept\n`;
14
-
15
- for (const rule of rules) {
16
- const { pattern, target } = rule;
17
- code += `${pattern} ${target}\n`;
18
- }
19
-
20
- fs.outputFileSync(
21
- dest,
22
- `exports.name = 'modernjs proxy rule';\nexports.rules = \`${code}\`;`,
23
- );
24
- return dest;
25
- };
26
-
27
- export const createProxyRule = (
28
- appDirectory: string,
29
- proxyOptions: ProxyOptions,
30
- ) => {
31
- const rules = [];
32
-
33
- if (proxyOptions && typeof proxyOptions === 'string') {
34
- return proxyOptions;
35
- }
36
-
37
- if (typeof proxyOptions === 'object') {
38
- for (const pattern of Object.keys(proxyOptions)) {
39
- const target = proxyOptions[pattern];
40
- if (!target || typeof target !== 'string') {
41
- logger.error(`dev.proxy.${pattern} value should be string type`);
42
- // eslint-disable-next-line no-process-exit
43
- process.exit(1);
44
- }
45
- rules.push({ pattern, target });
46
- }
47
- }
48
-
49
- return createWhistleProxyRule(appDirectory, rules);
50
- };
@@ -1,21 +0,0 @@
1
- import { execSync as nodeExecSync } from 'child_process';
2
-
3
- function execSync(cmd: string) {
4
- let stdout;
5
- let status = 0;
6
- try {
7
- stdout = nodeExecSync(cmd);
8
- } catch (err: any) {
9
- /* eslint-disable prefer-destructuring */
10
- stdout = err.stdout;
11
- status = err.status;
12
- /* eslint-enable prefer-destructuring */
13
- }
14
-
15
- return {
16
- stdout: stdout.toString(),
17
- status,
18
- };
19
- }
20
-
21
- export default execSync;
@@ -1,58 +0,0 @@
1
- import os from 'os';
2
- import http from 'http';
3
- import path from 'path';
4
- import { fs, logger } from '@modern-js/utils';
5
- import execSync from './execSync';
6
-
7
- const defaultCertDir = path.resolve(os.homedir(), './.whistle-proxy');
8
- export const defaultRootCA = path.resolve(defaultCertDir, './rootCA.crt');
9
-
10
- export const trustRootCA = () => {
11
- logger.info(`please type the password to trust the https certificate`);
12
- const { status } = execSync(
13
- `sudo security add-trusted-cert -d -k /Library/Keychains/System.keychain ${defaultRootCA}`,
14
- );
15
- if (status === 0) {
16
- logger.info('Root CA install, you are ready to intercept the https now');
17
- } else {
18
- logger.info('Failed to trust the root CA, please trust it manually');
19
- }
20
- };
21
-
22
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
23
- const isRootCATrusted = () => {
24
- // current empty
25
- };
26
-
27
- export const isRootCAExists = () => {
28
- if (fs.existsSync(defaultRootCA)) {
29
- return true;
30
- }
31
- return false;
32
- };
33
-
34
- export const generateRootCA = () =>
35
- new Promise((resolve, reject) => {
36
- if (fs.existsSync(defaultRootCA)) {
37
- fs.removeSync(defaultRootCA);
38
- }
39
-
40
- fs.ensureDirSync(defaultCertDir);
41
- const stream = fs.createWriteStream(defaultRootCA);
42
-
43
- http
44
- .get('http://127.0.0.1:8899/cgi-bin/rootca', response => {
45
- response.pipe(stream);
46
- stream
47
- .on('finish', () => {
48
- resolve(defaultRootCA);
49
- })
50
- .on('error', err => {
51
- reject(err);
52
- });
53
- })
54
- .on('error', err => {
55
- fs.unlink(defaultRootCA); // Delete the file
56
- reject(err);
57
- });
58
- });
@@ -1,31 +0,0 @@
1
- import execSync from './execSync';
2
-
3
- const networkTypes = ['Ethernet', 'Thunderbolt Ethernet', 'Wi-Fi'];
4
-
5
- const getNetworkType = () => {
6
- // eslint-disable-next-line @typescript-eslint/prefer-for-of
7
- for (let i = 0; i < networkTypes.length; i++) {
8
- const type = networkTypes[i];
9
- const result = execSync(`networksetup -getwebproxy ${type}`);
10
-
11
- if (result.status === 0) {
12
- return type;
13
- }
14
- }
15
-
16
- throw new Error('Unknown network type');
17
- };
18
-
19
- export const enableGlobalProxy = (ip: string, port: string) => {
20
- const networkType = getNetworkType();
21
-
22
- // && networksetup -setproxybypassdomains ${networkType} 127.0.0.1 localhost
23
- execSync(`networksetup -setwebproxy ${networkType} ${ip} ${port}`);
24
- execSync(`networksetup -setsecurewebproxy ${networkType} ${ip} ${port}`);
25
- };
26
-
27
- export const disableGlobalProxy = () => {
28
- const networkType = getNetworkType();
29
- execSync(`networksetup -setwebproxystate ${networkType} off`);
30
- execSync(`networksetup -setsecurewebproxystate ${networkType} off`);
31
- };
@@ -1,67 +0,0 @@
1
- import path from 'path';
2
- import { logger } from '@modern-js/utils';
3
- import execSync from './execSync';
4
- import {
5
- isRootCAExists,
6
- generateRootCA,
7
- defaultRootCA,
8
- trustRootCA,
9
- } from './macCAManager';
10
-
11
- const { disableGlobalProxy, enableGlobalProxy } = require('./macProxyManager');
12
-
13
- interface ProxyConfig {
14
- rule: string;
15
- port: number;
16
- // mode: 'pureProxy'|'debug'|'multiEnv'
17
- }
18
-
19
- export default class WhistleProxy {
20
- private readonly rule: string;
21
-
22
- private readonly port: number;
23
-
24
- private readonly bin: string;
25
-
26
- private readonly certDir: string;
27
-
28
- constructor(config: ProxyConfig) {
29
- this.rule = config.rule;
30
- this.port = config.port;
31
- // unused
32
- // this.mode = config.mode; // pureProxy|debug|multiEnv
33
- this.bin = path.resolve(
34
- path.dirname(require.resolve('whistle')),
35
- 'bin/whistle.js',
36
- );
37
- this.certDir = path.dirname(defaultRootCA);
38
- }
39
-
40
- async installRootCA() {
41
- try {
42
- if (!isRootCAExists()) {
43
- await generateRootCA();
44
- trustRootCA();
45
- }
46
- } catch (err) {
47
- this.close();
48
- throw err;
49
- }
50
- }
51
-
52
- async start() {
53
- logger.info(`Starting the proxy server.....`);
54
- execSync(`${this.bin} start --certDir=${this.certDir} --port=${this.port}`);
55
- execSync(`${this.bin} use ${this.rule} --force`);
56
- await this.installRootCA();
57
-
58
- enableGlobalProxy('127.0.0.1', this.port);
59
- logger.info(`Proxy Server start on localhost:${this.port}\n`);
60
- }
61
-
62
- close() {
63
- execSync(`${this.bin} stop`);
64
- disableGlobalProxy();
65
- logger.info(`Proxy Server has closed`);
66
- }
67
- }