Browse Source

代码格式调整:packages/core/**/*.js

pull/391/head
王良 1 week ago
parent
commit
48132c39b0
  1. 2
      packages/core/index.js
  2. 30
      packages/core/src/config.js
  3. 162
      packages/core/src/config/index.js
  4. 2
      packages/core/src/event.js
  5. 19
      packages/core/src/expose.js
  6. 2
      packages/core/src/index.js
  7. 6
      packages/core/src/merge.js
  8. 12
      packages/core/src/modules/index.js
  9. 6
      packages/core/src/modules/plugin/git/config.js
  10. 9
      packages/core/src/modules/plugin/git/index.js
  11. 10
      packages/core/src/modules/plugin/index.js
  12. 18
      packages/core/src/modules/plugin/node/config.js
  13. 17
      packages/core/src/modules/plugin/node/index.js
  14. 10
      packages/core/src/modules/plugin/overwall/config.js
  15. 12
      packages/core/src/modules/plugin/overwall/index.js
  16. 4
      packages/core/src/modules/plugin/pip/config.js
  17. 9
      packages/core/src/modules/plugin/pip/index.js
  18. 12
      packages/core/src/modules/proxy/index.js
  19. 12
      packages/core/src/modules/server/index.js
  20. 17
      packages/core/src/shell/index.js
  21. 8
      packages/core/src/shell/scripts/enable-loopback.js
  22. 4
      packages/core/src/shell/scripts/extra-path/index.js
  23. 10
      packages/core/src/shell/scripts/get-npm-env.js
  24. 8
      packages/core/src/shell/scripts/get-system-env.js
  25. 7
      packages/core/src/shell/scripts/kill-by-port.js
  26. 8
      packages/core/src/shell/scripts/set-npm-env.js
  27. 8
      packages/core/src/shell/scripts/set-system-env.js
  28. 33
      packages/core/src/shell/scripts/set-system-proxy/index.js
  29. 8
      packages/core/src/shell/scripts/setup-ca.js
  30. 19
      packages/core/src/shell/shell.js
  31. 6
      packages/core/src/shell/test.js
  32. 5
      packages/core/src/status.js
  33. 9
      packages/core/src/utils/util.log.js
  34. 2
      packages/core/start/index.js
  35. 7
      packages/core/start/mitmproxy.js
  36. 64
      packages/core/start/user_config.json5
  37. 13
      packages/core/test/httpsVerifyTest.js
  38. 28
      packages/core/test/mergeTest.js
  39. 6
      packages/core/test/regex.test.js
  40. 14
      packages/core/test/requestTest.js

2
packages/core/index.js

@ -3,5 +3,5 @@ module.exports = require('./src')
// TODO 这是一个解谜游戏 ↓ ↓ ↓ ↓ ↓ ↓ ,如果你破解了它,请不要公开,好好用它来学习和查资料吧(特别注意:为了你的人身安全,请不要用它来查看和发表不当言论,你懂得)。 // TODO 这是一个解谜游戏 ↓ ↓ ↓ ↓ ↓ ↓ ,如果你破解了它,请不要公开,好好用它来学习和查资料吧(特别注意:为了你的人身安全,请不要用它来查看和发表不当言论,你懂得)。
/** /**
\u0061\u0048\u0052\u0030\u0063\u0044\u006f\u0076\u004c\u0032\u0052\u006c\u0064\u0069\u0031\u007a\u0061\u0057\u0052\u006c\u0059\u0032\u0046\u0079\u004c\u006d\u0052\u0076\u0059\u0032\u0031\u0070\u0063\u006e\u004a\u0076\u0063\u0069\u0035\u006a\u0062\u0069\u0039\u0035\u0062\u0033\u0056\u006d\u0061\u0057\u0035\u006b\u0061\u0058\u0051\u0076\u0061\u0057\u0035\u006b\u005a\u0058\u0067\u0075\u0061\u0048\u0052\u0074\u0062\u0041\u003d\u003d \u0061\u0048\u0052\u0030\u0063\u0044\u006f\u0076\u004c\u0032\u0052\u006c\u0064\u0069\u0031\u007a\u0061\u0057\u0052\u006c\u0059\u0032\u0046\u0079\u004c\u006d\u0052\u0076\u0059\u0032\u0031\u0070\u0063\u006e\u004a\u0076\u0063\u0069\u0035\u006a\u0062\u0069\u0039\u0035\u0062\u0033\u0056\u006d\u0061\u0057\u0035\u006b\u0061\u0058\u0051\u0076\u0061\u0057\u0035\u006b\u005a\u0058\u0067\u0075\u0061\u0048\u0052\u0074\u0062\u0041\u003d\u003d
**/ */
// 这个项目里有一点点解谜提示: https://github.com/fast-crud/fast-crud (打开拉到最下面) // 这个项目里有一点点解谜提示: https://github.com/fast-crud/fast-crud (打开拉到最下面)

30
packages/core/src/config.js

@ -1,12 +1,12 @@
const fs = require('fs') const fs = require('fs')
const Shell = require('./shell') const path = require('path')
const lodash = require('lodash')
const defConfig = require('./config/index.js')
const jsonApi = require('@docmirror/mitmproxy/src/json') const jsonApi = require('@docmirror/mitmproxy/src/json')
const lodash = require('lodash')
const request = require('request') const request = require('request')
const path = require('path') const defConfig = require('./config/index.js')
const log = require('./utils/util.log')
const mergeApi = require('./merge.js') const mergeApi = require('./merge.js')
const Shell = require('./shell')
const log = require('./utils/util.log')
let configTarget = lodash.cloneDeep(defConfig) let configTarget = lodash.cloneDeep(defConfig)
@ -80,13 +80,13 @@ const configApi = {
configApi.deleteRemoteConfigFile(suffix) configApi.deleteRemoteConfigFile(suffix)
return return
} }
// eslint-disable-next-line handle-callback-err
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
log.info('开始下载远程配置:', remoteConfigUrl) log.info('开始下载远程配置:', remoteConfigUrl)
const headers = { const headers = {
'Cache-Control': 'no-cache', // 禁止使用缓存 'Cache-Control': 'no-cache', // 禁止使用缓存
Pragma: 'no-cache' // 禁止使用缓存 'Pragma': 'no-cache', // 禁止使用缓存
} }
if (remoteConfigUrl.startsWith('https://raw.githubusercontent.com/')) { if (remoteConfigUrl.startsWith('https://raw.githubusercontent.com/')) {
headers['Server-Name'] = 'baidu.com' headers['Server-Name'] = 'baidu.com'
@ -131,7 +131,7 @@ const configApi = {
if (response) { if (response) {
message = `下载远程配置失败: ${remoteConfigUrl}, message: ${response.message}, code: ${response.statusCode}` message = `下载远程配置失败: ${remoteConfigUrl}, message: ${response.message}, code: ${response.statusCode}`
} else { } else {
message = '下载远程配置失败: response: ' + response message = `下载远程配置失败: response: ${response}`
} }
reject(new Error(message)) reject(new Error(message))
} }
@ -205,7 +205,7 @@ const configApi = {
return { return {
diffConfig, diffConfig,
allConfig allConfig,
} }
}, },
doMerge: mergeApi.doMerge, doMerge: mergeApi.doMerge,
@ -330,31 +330,31 @@ const configApi = {
list.push({ list.push({
key, key,
value: map[key], value: map[key],
exists exists,
}) })
} }
return list return list
}, },
async setVariables (type) { async setVariables (type) {
const list = await configApi.getVariables(type) const list = await configApi.getVariables(type)
const noSetList = list.filter(item => { const noSetList = list.filter((item) => {
return !item.exists return !item.exists
}) })
if (list.length > 0) { if (list.length > 0) {
const context = { const context = {
root_ca_cert_path: configApi.get().server.setting.rootCaFile.certPath root_ca_cert_path: configApi.get().server.setting.rootCaFile.certPath,
} }
for (const item of noSetList) { for (const item of noSetList) {
if (item.value.indexOf('${') >= 0) { if (item.value.includes('${')) {
for (const key in context) { for (const key in context) {
item.value = item.value.replcace(new RegExp('${' + key + '}', 'g'), context[key]) item.value = item.value.replcace(new RegExp(`\${${key}}`, 'g'), context[key])
} }
} }
} }
const method = type === 'npm' ? Shell.setNpmEnv : Shell.setSystemEnv const method = type === 'npm' ? Shell.setNpmEnv : Shell.setSystemEnv
return method({ list: noSetList }) return method({ list: noSetList })
} }
} },
} }
module.exports = configApi module.exports = configApi

162
packages/core/src/config/index.js

@ -17,14 +17,14 @@ module.exports = {
app: { app: {
mode: 'default', mode: 'default',
autoStart: { autoStart: {
enabled: false enabled: false,
}, },
remoteConfig: { remoteConfig: {
enabled: true, enabled: true,
// 共享远程配置地址 // 共享远程配置地址
url: 'https://gitee.com/wangliang181230/dev-sidecar/raw/docmirror/packages/core/src/config/remote_config.json5', url: 'https://gitee.com/wangliang181230/dev-sidecar/raw/docmirror/packages/core/src/config/remote_config.json5',
// 个人远程配置地址 // 个人远程配置地址
personalUrl: '' personalUrl: '',
}, },
startShowWindow: true, // 启动时是否打开窗口:true=打开窗口, false=隐藏窗口 startShowWindow: true, // 启动时是否打开窗口:true=打开窗口, false=隐藏窗口
showHideShortcut: 'Alt + S', // 显示/隐藏窗口快捷键 showHideShortcut: 'Alt + S', // 显示/隐藏窗口快捷键
@ -33,10 +33,10 @@ module.exports = {
autoChecked: true, // 是否自动检查更新 autoChecked: true, // 是否自动检查更新
skipPreRelease: true, // 是否忽略预发布版本 skipPreRelease: true, // 是否忽略预发布版本
dock: { dock: {
hideWhenWinClose: false hideWhenWinClose: false,
}, },
closeStrategy: 0, closeStrategy: 0,
showShutdownTip: true showShutdownTip: true,
}, },
server: { server: {
enabled: true, enabled: true,
@ -47,12 +47,12 @@ module.exports = {
verifySsl: true, verifySsl: true,
script: { script: {
enabled: true, enabled: true,
defaultDir: './extra/scripts/' defaultDir: './extra/scripts/',
}, },
userBasePath: getUserBasePath(), userBasePath: getUserBasePath(),
rootCaFile: { rootCaFile: {
certPath: getRootCaCertPath(), certPath: getRootCaCertPath(),
keyPath: getRootCaKeyPath() keyPath: getRootCaKeyPath(),
}, },
// 默认超时时间配置 // 默认超时时间配置
@ -63,12 +63,12 @@ module.exports = {
timeoutMapping: { timeoutMapping: {
'github.com': { 'github.com': {
timeout: 20000, timeout: 20000,
keepAliveTimeout: 30000 keepAliveTimeout: 30000,
} },
}, },
// 慢速IP延迟时间:测速超过该值时,则视为延迟高,显示为橙色 // 慢速IP延迟时间:测速超过该值时,则视为延迟高,显示为橙色
lowSpeedDelay: 150 lowSpeedDelay: 150,
}, },
compatible: { compatible: {
// **** 自定义兼容配置 **** // // **** 自定义兼容配置 **** //
@ -87,15 +87,15 @@ module.exports = {
// rejectUnauthorized: false // rejectUnauthorized: false
// } // }
// } // }
} },
}, },
intercept: { intercept: {
enabled: true enabled: true,
}, },
intercepts: { intercepts: {
'github.com': { 'github.com': {
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
}, },
'^(/[\\w-.]+){2,}/?(\\?.*)?$': { '^(/[\\w-.]+){2,}/?(\\?.*)?$': {
// 篡改猴插件地址,以下是高速镜像地址 // 篡改猴插件地址,以下是高速镜像地址
@ -103,7 +103,7 @@ module.exports = {
// Github油猴脚本地址,以下是高速镜像地址 // Github油猴脚本地址,以下是高速镜像地址
script: 'https://gitee.com/wangliang181230/dev-sidecar/raw/scripts/GithubEnhanced-High-Speed-Download.user.js', script: 'https://gitee.com/wangliang181230/dev-sidecar/raw/scripts/GithubEnhanced-High-Speed-Download.user.js',
remark: '注:上面所使用的脚本地址,为高速镜像地址。', remark: '注:上面所使用的脚本地址,为高速镜像地址。',
desc: '油猴脚本:高速下载 Git Clone/SSH、Release、Raw、Code(ZIP) 等文件 (公益加速)、项目列表单文件快捷下载、添加 git clone 命令' desc: '油猴脚本:高速下载 Git Clone/SSH、Release、Raw、Code(ZIP) 等文件 (公益加速)、项目列表单文件快捷下载、添加 git clone 命令',
}, },
// 以下三项暂时先注释掉,因为已经有油猴脚本提供高速下载地址了。 // 以下三项暂时先注释掉,因为已经有油猴脚本提供高速下载地址了。
// '/.*/.*/releases/download/': { // '/.*/.*/releases/download/': {
@ -119,140 +119,140 @@ module.exports = {
// }, // },
'/fluidicon.png': { '/fluidicon.png': {
cacheDays: 365, cacheDays: 365,
desc: 'Github那只猫的图片,缓存1年' desc: 'Github那只猫的图片,缓存1年',
}, },
'^(/[^/]+){2}/pull/\\d+/open_with_menu.*$': { '^(/[^/]+){2}/pull/\\d+/open_with_menu.*$': {
cacheDays: 7, cacheDays: 7,
desc: 'PR详情页:标题右边那个Code按钮的HTML代码请求地址,感觉上应该可以缓存。暂时先设置为缓存7天' desc: 'PR详情页:标题右边那个Code按钮的HTML代码请求地址,感觉上应该可以缓存。暂时先设置为缓存7天',
}, },
'^((/[^/]+){2,})/raw((/[^/]+)+\\.(jpg|jpeg|png|gif))(\\?.*)?$': { '^((/[^/]+){2,})/raw((/[^/]+)+\\.(jpg|jpeg|png|gif))(\\?.*)?$': {
// eslint-disable-next-line no-template-curly-in-string // eslint-disable-next-line no-template-curly-in-string
proxy: 'https://raw.githubusercontent.com${m[1]}${m[3]}', proxy: 'https://raw.githubusercontent.com${m[1]}${m[3]}',
sni: 'baidu.com', sni: 'baidu.com',
cacheDays: 7, cacheDays: 7,
desc: '仓库内图片,重定向改为代理,并缓存7天。' desc: '仓库内图片,重定向改为代理,并缓存7天。',
}, },
'^((/[^/]+){2,})/raw((/[^/]+)+\\.js)(\\?.*)?$': { '^((/[^/]+){2,})/raw((/[^/]+)+\\.js)(\\?.*)?$': {
// eslint-disable-next-line no-template-curly-in-string // eslint-disable-next-line no-template-curly-in-string
proxy: 'https://raw.githubusercontent.com${m[1]}${m[3]}', proxy: 'https://raw.githubusercontent.com${m[1]}${m[3]}',
sni: 'baidu.com', sni: 'baidu.com',
responseReplace: { headers: { 'content-type': 'application/javascript; charset=utf-8' } }, responseReplace: { headers: { 'content-type': 'application/javascript; charset=utf-8' } },
desc: '仓库内脚本,重定向改为代理,并设置响应头Content-Type。作用:方便script拦截器直接使用,避免引起跨域问题和脚本内容限制问题。' desc: '仓库内脚本,重定向改为代理,并设置响应头Content-Type。作用:方便script拦截器直接使用,避免引起跨域问题和脚本内容限制问题。',
} },
}, },
'github-releases.githubusercontent.com': { 'github-releases.githubusercontent.com': {
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
} },
}, },
'github.githubassets.com': { 'github.githubassets.com': {
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
} },
}, },
'camo.githubusercontent.com': { 'camo.githubusercontent.com': {
'^[a-zA-Z0-9/]+(\\?.*)?$': { '^[a-zA-Z0-9/]+(\\?.*)?$': {
cacheDays: 365, cacheDays: 365,
desc: '图片,缓存1年' desc: '图片,缓存1年',
}, },
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
} },
}, },
'collector.github.com': { 'collector.github.com': {
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
} },
}, },
'customer-stories-feed.github.com': { 'customer-stories-feed.github.com': {
'.*': { proxy: 'customer-stories-feed.fastgit.org' } '.*': { proxy: 'customer-stories-feed.fastgit.org' },
}, },
'raw.githubusercontent.com': { 'raw.githubusercontent.com': {
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
} },
}, },
'user-images.githubusercontent.com': { 'user-images.githubusercontent.com': {
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
}, },
'^/.*\\.png(\\?.*)?$': { '^/.*\\.png(\\?.*)?$': {
cacheDays: 365, cacheDays: 365,
desc: '用户在PR或issue等内容中上传的图片,缓存1年。注:每张图片都有唯一的ID,不会重复,可以安心缓存' desc: '用户在PR或issue等内容中上传的图片,缓存1年。注:每张图片都有唯一的ID,不会重复,可以安心缓存',
} },
}, },
'private-user-images.githubusercontent.com': { 'private-user-images.githubusercontent.com': {
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
}, },
'^/.*\\.png(\\?.*)?$': { '^/.*\\.png(\\?.*)?$': {
cacheHours: 1, cacheHours: 1,
desc: '用户在PR或issue等内容中上传的图片,缓存1小时就够了,因为每次刷新页面都是不一样的链接。' desc: '用户在PR或issue等内容中上传的图片,缓存1小时就够了,因为每次刷新页面都是不一样的链接。',
} },
}, },
'avatars.githubusercontent.com': { 'avatars.githubusercontent.com': {
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
}, },
'^/u/\\d+(\\?.*)?$': { '^/u/\\d+(\\?.*)?$': {
cacheDays: 365, cacheDays: 365,
desc: '用户头像,缓存1年' desc: '用户头像,缓存1年',
} },
}, },
'api.github.com': { 'api.github.com': {
'^/_private/browser/stats$': { '^/_private/browser/stats$': {
success: true, success: true,
desc: 'github的访问速度分析上传,没有必要,直接返回成功' desc: 'github的访问速度分析上传,没有必要,直接返回成功',
}, },
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
} },
}, },
'*.docker.com': { '*.docker.com': {
'.*': { '.*': {
sni: 'baidu.com' sni: 'baidu.com',
} },
}, },
'login.docker.com': { 'login.docker.com': {
'/favicon.ico': { '/favicon.ico': {
proxy: 'hub.docker.com', proxy: 'hub.docker.com',
sni: 'baidu.com', sni: 'baidu.com',
desc: '登录页面的ico,采用hub.docker.com的' desc: '登录页面的ico,采用hub.docker.com的',
} },
}, },
// google cdn // google cdn
'www.google.com': { 'www.google.com': {
'/recaptcha/.*': { proxy: 'www.recaptcha.net' } '/recaptcha/.*': { proxy: 'www.recaptcha.net' },
// '.*': { // '.*': {
// proxy: 'gg.docmirror.top/_yxorp', // proxy: 'gg.docmirror.top/_yxorp',
// desc: '呀,被你发现了,偷偷的用,别声张' // desc: '呀,被你发现了,偷偷的用,别声张'
// } // }
}, },
'www.gstatic.com': { 'www.gstatic.com': {
'/recaptcha/.*': { proxy: 'www.recaptcha.net' } '/recaptcha/.*': { proxy: 'www.recaptcha.net' },
}, },
'ajax.googleapis.com': { 'ajax.googleapis.com': {
'.*': { '.*': {
proxy: 'ajax.lug.ustc.edu.cn', proxy: 'ajax.lug.ustc.edu.cn',
backup: ['gapis.geekzu.org'], backup: ['gapis.geekzu.org'],
test: 'ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js' test: 'ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js',
} },
}, },
'fonts.googleapis.com': { 'fonts.googleapis.com': {
'.*': { '.*': {
proxy: 'fonts.geekzu.org', proxy: 'fonts.geekzu.org',
backup: ['fonts.loli.net'], backup: ['fonts.loli.net'],
test: 'https://fonts.googleapis.com/css?family=Oswald' test: 'https://fonts.googleapis.com/css?family=Oswald',
} },
}, },
'themes.googleapis.com': { 'themes.googleapis.com': {
'.*': { '.*': {
proxy: 'themes.loli.net', proxy: 'themes.loli.net',
backup: ['themes.proxy.ustclug.org'] backup: ['themes.proxy.ustclug.org'],
} },
}, },
'themes.googleusercontent.com': { 'themes.googleusercontent.com': {
'.*': { proxy: 'google-themes.proxy.ustclug.org' } '.*': { proxy: 'google-themes.proxy.ustclug.org' },
}, },
// 'fonts.gstatic.com': { // 'fonts.gstatic.com': {
// '.*': { // '.*': {
@ -266,8 +266,8 @@ module.exports = {
// mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.0/napi-v3-win32-x64.tar.gz // mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.0/napi-v3-win32-x64.tar.gz
'*.s3.1amazonaws1.com': { '*.s3.1amazonaws1.com': {
'/sqlite3/.*': { '/sqlite3/.*': {
redirect: 'npm.taobao.org/mirrors' redirect: 'npm.taobao.org/mirrors',
} },
}, },
// 'packages.elastic.co': { '.*': { proxy: 'elastic.proxy.ustclug.org' } }, // 'packages.elastic.co': { '.*': { proxy: 'elastic.proxy.ustclug.org' } },
// 'ppa.launchpad.net': { '.*': { proxy: 'launchpad.proxy.ustclug.org' } }, // 'ppa.launchpad.net': { '.*': { proxy: 'launchpad.proxy.ustclug.org' } },
@ -278,15 +278,15 @@ module.exports = {
'*.carbonads.com': { '*.carbonads.com': {
'/carbon.*': { '/carbon.*': {
abort: true, abort: true,
desc: '广告拦截' desc: '广告拦截',
} },
}, },
'*.buysellads.com': { '*.buysellads.com': {
'/ads/.*': { '/ads/.*': {
abort: true, abort: true,
desc: '广告拦截' desc: '广告拦截',
} },
} },
}, },
// 预设置IP列表 // 预设置IP列表
preSetIpList: { preSetIpList: {
@ -303,7 +303,7 @@ module.exports = {
'140.82.116.3', '140.82.116.3',
'140.82.116.4', '140.82.116.4',
'140.82.121.3', '140.82.121.3',
'140.82.121.4' '140.82.121.4',
], ],
'api.github.com': [ 'api.github.com': [
'20.26.156.210', '20.26.156.210',
@ -316,7 +316,7 @@ module.exports = {
'140.82.112.5', '140.82.112.5',
'140.82.113.6', '140.82.113.6',
'140.82.116.6', '140.82.116.6',
'140.82.121.6' '140.82.121.6',
], ],
'codeload.github.com': [ 'codeload.github.com': [
'20.26.156.216', '20.26.156.216',
@ -329,26 +329,26 @@ module.exports = {
'140.82.113.9', '140.82.113.9',
'140.82.114.10', '140.82.114.10',
'140.82.116.10', '140.82.116.10',
'140.82.121.9' '140.82.121.9',
], ],
'*.githubusercontent.com': [ '*.githubusercontent.com': [
'185.199.108.133', '185.199.108.133',
'185.199.109.133', '185.199.109.133',
'185.199.110.133', '185.199.110.133',
'185.199.111.133' '185.199.111.133',
], ],
'github.githubassets.com': [ 'github.githubassets.com': [
'185.199.108.154', '185.199.108.154',
'185.199.109.154', '185.199.109.154',
'185.199.110.154', '185.199.110.154',
'185.199.111.154' '185.199.111.154',
], ],
'github.io': [ 'github.io': [
'185.199.108.153', '185.199.108.153',
'185.199.109.153', '185.199.109.153',
'185.199.110.153', '185.199.110.153',
'185.199.111.153' '185.199.111.153',
] ],
}, },
whiteList: { whiteList: {
'*.cn': true, '*.cn': true,
@ -360,35 +360,35 @@ module.exports = {
'*.alipay.com': true, '*.alipay.com': true,
'*.qq.com': true, '*.qq.com': true,
'*.baidu.com': true, '*.baidu.com': true,
'192.168.*': true '192.168.*': true,
}, },
dns: { dns: {
providers: { providers: {
aliyun: { aliyun: {
type: 'https', type: 'https',
server: 'https://dns.alidns.com/dns-query', server: 'https://dns.alidns.com/dns-query',
cacheSize: 1000 cacheSize: 1000,
}, },
cloudflare: { cloudflare: {
type: 'https', type: 'https',
server: 'https://1.1.1.1/dns-query', server: 'https://1.1.1.1/dns-query',
cacheSize: 1000 cacheSize: 1000,
}, },
quad9: { quad9: {
type: 'https', type: 'https',
server: 'https://9.9.9.9/dns-query', server: 'https://9.9.9.9/dns-query',
cacheSize: 1000 cacheSize: 1000,
}, },
safe360: { safe360: {
type: 'https', type: 'https',
server: 'https://doh.360.cn/dns-query', server: 'https://doh.360.cn/dns-query',
cacheSize: 1000 cacheSize: 1000,
}, },
rubyfish: { rubyfish: {
type: 'https', type: 'https',
server: 'https://rubyfish.cn/dns-query', server: 'https://rubyfish.cn/dns-query',
cacheSize: 1000 cacheSize: 1000,
} },
}, },
mapping: { mapping: {
'*.github.com': 'quad9', '*.github.com': 'quad9',
@ -407,16 +407,16 @@ module.exports = {
'*.v2ex.com': 'quad9', '*.v2ex.com': 'quad9',
'*.pypi.org': 'quad9', '*.pypi.org': 'quad9',
'*.jetbrains.com': 'quad9', '*.jetbrains.com': 'quad9',
'*.azureedge.net': 'quad9' '*.azureedge.net': 'quad9',
}, },
speedTest: { speedTest: {
enabled: true, enabled: true,
interval: 300000, interval: 300000,
hostnameList: ['github.com'], hostnameList: ['github.com'],
dnsProviders: ['cloudflare', 'safe360', 'rubyfish'] dnsProviders: ['cloudflare', 'safe360', 'rubyfish'],
} },
} },
}, },
proxy: {}, proxy: {},
plugin: {} plugin: {},
} }

2
packages/core/src/event.js

@ -34,6 +34,6 @@ function unregister (id) {
const EventHub = { const EventHub = {
register, register,
fire, fire,
unregister unregister,
} }
module.exports = EventHub module.exports = EventHub

19
packages/core/src/expose.js

@ -1,16 +1,17 @@
const status = require('./status') const lodash = require('lodash')
const config = require('./config') const config = require('./config')
const event = require('./event') const event = require('./event')
const shell = require('./shell')
const modules = require('./modules') const modules = require('./modules')
const lodash = require('lodash') const shell = require('./shell')
const status = require('./status')
const log = require('./utils/util.log') const log = require('./utils/util.log')
const context = { const context = {
config, config,
shell, shell,
status, status,
event, event,
log log,
} }
function setupPlugin (key, plugin, context, config) { function setupPlugin (key, plugin, context, config) {
@ -29,14 +30,14 @@ const proxy = setupPlugin('proxy', modules.proxy, context, config)
const plugin = {} const plugin = {}
for (const key in modules.plugin) { for (const key in modules.plugin) {
const target = modules.plugin[key] const target = modules.plugin[key]
const api = setupPlugin('plugin.' + key, target, context, config) const api = setupPlugin(`plugin.${key}`, target, context, config)
plugin[key] = api plugin[key] = api
} }
config.resetDefault() config.resetDefault()
const server = modules.server const server = modules.server
const serverStart = server.start const serverStart = server.start
const newServerStart = ({ mitmproxyPath }) => { function newServerStart({ mitmproxyPath }) {
return serverStart({ mitmproxyPath, plugins: plugin }) return serverStart({ mitmproxyPath, plugins: plugin })
} }
server.start = newServerStart server.start = newServerStart
@ -126,7 +127,7 @@ const api = {
status: { status: {
get () { get () {
return status return status
} },
}, },
config, config,
event, event,
@ -134,9 +135,9 @@ const api = {
server, server,
proxy, proxy,
plugin, plugin,
log log,
} }
module.exports = { module.exports = {
status, status,
api api,
} }

2
packages/core/src/index.js

@ -3,7 +3,7 @@ const log = require('./utils/util.log')
// process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' // process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
// 避免异常崩溃 // 避免异常崩溃
process.on('uncaughtException', function (err) { process.on('uncaughtException', (err) => {
if (err.code === 'ECONNABORTED') { if (err.code === 'ECONNABORTED') {
// console.error(err.errno) // console.error(err.errno)
return return

6
packages/core/src/merge.js

@ -75,13 +75,13 @@ function deleteNullItems (target) {
} }
module.exports = { module.exports = {
doMerge: function (oldObj, newObj) { doMerge (oldObj, newObj) {
return lodash.mergeWith(oldObj, newObj, function (objValue, srcValue) { return lodash.mergeWith(oldObj, newObj, (objValue, srcValue) => {
if (lodash.isArray(objValue)) { if (lodash.isArray(objValue)) {
return srcValue return srcValue
} }
}) })
}, },
doDiff, doDiff,
deleteNullItems deleteNullItems,
} }

12
packages/core/src/modules/index.js

@ -1,11 +1,5 @@
const server = require('./server')
const proxy = require('./proxy')
const plugin = require('./plugin')
module.exports = { module.exports = {
server, server: require('./server'),
proxy, proxy: require('./proxy'),
plugin plugin: require('./plugin')
} }

6
packages/core/src/modules/plugin/git/config.js

@ -7,7 +7,7 @@ module.exports = {
noProxyUrls: { noProxyUrls: {
'https://gitee.com': true, // 码云 'https://gitee.com': true, // 码云
'https://e.coding.net': true, // Coding(腾讯云) 'https://e.coding.net': true, // Coding(腾讯云)
'https://codeup.aliyun.com': true // 云效 Codeup (阿里云) 'https://codeup.aliyun.com': true, // 云效 Codeup (阿里云)
} },
} },
} }

9
packages/core/src/modules/plugin/git/index.js

@ -1,4 +1,5 @@
const pluginConfig = require('./config') const pluginConfig = require('./config')
const Plugin = function (context) { const Plugin = function (context) {
const { config, shell, event, log } = context const { config, shell, event, log } = context
const pluginApi = { const pluginApi = {
@ -29,7 +30,7 @@ const Plugin = function (context) {
async setProxy (ip, port) { async setProxy (ip, port) {
const cmds = [ const cmds = [
`git config --global http.proxy http://${ip}:${port} `, `git config --global http.proxy http://${ip}:${port} `,
`git config --global https.proxy http://${ip}:${port} ` `git config --global https.proxy http://${ip}:${port} `,
] ]
if (config.get().plugin.git.setting.sslVerify === true) { if (config.get().plugin.git.setting.sslVerify === true) {
@ -76,7 +77,7 @@ const Plugin = function (context) {
event.fire('status', { key: 'plugin.git.enabled', value: false }) event.fire('status', { key: 'plugin.git.enabled', value: false })
log.info('关闭【Git】代理成功') log.info('关闭【Git】代理成功')
return ret return ret
} },
} }
return pluginApi return pluginApi
} }
@ -85,7 +86,7 @@ module.exports = {
key: 'git', key: 'git',
config: pluginConfig, config: pluginConfig,
status: { status: {
enabled: false enabled: false,
}, },
plugin: Plugin plugin: Plugin,
} }

10
packages/core/src/modules/plugin/index.js

@ -1,8 +1,6 @@
const node = require('./node')
const git = require('./git')
const overwall = require('./overwall')
const pip = require('./pip')
module.exports = { module.exports = {
node, git, pip, overwall node: require('./node'),
git: require('./git'),
pip: require('./pip'),
overwall: require('./overwall'),
} }

18
packages/core/src/modules/plugin/node/config.js

@ -3,16 +3,16 @@ module.exports = {
enabled: false, enabled: false,
tip: '如果你没有安装nodejs则不需要启动它', tip: '如果你没有安装nodejs则不需要启动它',
startup: { startup: {
variables: true variables: true,
}, },
setting: { setting: {
command: 'npm', 'command': 'npm',
'strict-ssl': true, 'strict-ssl': true,
cafile: false, 'cafile': false,
NODE_EXTRA_CA_CERTS: false, 'NODE_EXTRA_CA_CERTS': false,
NODE_TLS_REJECT_UNAUTHORIZED: false, 'NODE_TLS_REJECT_UNAUTHORIZED': false,
yarnRegistry: 'null', 'yarnRegistry': 'null',
registry: 'https://registry.npmjs.org'// 可以选择切换官方或者淘宝镜像 'registry': 'https://registry.npmjs.org', // 可以选择切换官方或者淘宝镜像
}, },
// intercepts: { // intercepts: {
// 'cdn.cypress.io': [{ regexp: '/desktop/.*', proxy: 'http://npmmirror.com/mirrors/cypress/' }] // 'cdn.cypress.io': [{ regexp: '/desktop/.*', proxy: 'http://npmmirror.com/mirrors/cypress/' }]
@ -27,6 +27,6 @@ module.exports = {
CHROMEDRIVER_CDNURL: 'https://npmmirror.com/mirrors/chromedriver', CHROMEDRIVER_CDNURL: 'https://npmmirror.com/mirrors/chromedriver',
OPERADRIVER: 'https://npmmirror.com/mirrors/operadriver', OPERADRIVER: 'https://npmmirror.com/mirrors/operadriver',
ELECTRON_BUILDER_BINARIES_MIRROR: 'https://npmmirror.com/mirrors/electron-builder-binaries/', ELECTRON_BUILDER_BINARIES_MIRROR: 'https://npmmirror.com/mirrors/electron-builder-binaries/',
PYTHON_MIRROR: 'https://npmmirror.com/mirrors/python' PYTHON_MIRROR: 'https://npmmirror.com/mirrors/python',
} },
} }

17
packages/core/src/modules/plugin/node/index.js

@ -1,5 +1,6 @@
const nodeConfig = require('./config')
const jsonApi = require('@docmirror/mitmproxy/src/json') const jsonApi = require('@docmirror/mitmproxy/src/json')
const nodeConfig = require('./config')
const NodePlugin = function (context) { const NodePlugin = function (context) {
const { config, shell, event, log } = context const { config, shell, event, log } = context
const nodeApi = { const nodeApi = {
@ -95,7 +96,7 @@ const NodePlugin = function (context) {
value: map[key], value: map[key],
oldValue: currentMap[key], oldValue: currentMap[key],
exists, exists,
hadSet: currentMap[key] === map[key] hadSet: currentMap[key] === map[key],
}) })
} }
return list return list
@ -103,7 +104,7 @@ const NodePlugin = function (context) {
async setVariables () { async setVariables () {
const list = await nodeApi.getVariables() const list = await nodeApi.getVariables()
const noSetList = list.filter(item => { const noSetList = list.filter((item) => {
return !item.exists return !item.exists
}) })
if (noSetList.length > 0) { if (noSetList.length > 0) {
@ -125,7 +126,7 @@ const NodePlugin = function (context) {
const cmds = [ const cmds = [
`${command} config set proxy=http://${ip}:${port}`, `${command} config set proxy=http://${ip}:${port}`,
`${command} config set https-proxy=http://${ip}:${port}` `${command} config set https-proxy=http://${ip}:${port}`,
] ]
const env = [] const env = []
@ -172,13 +173,13 @@ const NodePlugin = function (context) {
`${command} config delete proxy`, `${command} config delete proxy`,
`${command} config delete https-proxy`, `${command} config delete https-proxy`,
`${command} config delete NODE_EXTRA_CA_CERTS`, `${command} config delete NODE_EXTRA_CA_CERTS`,
`${command} config delete strict-ssl` `${command} config delete strict-ssl`,
] ]
const ret = await shell.exec(cmds, { type: 'cmd' }) const ret = await shell.exec(cmds, { type: 'cmd' })
event.fire('status', { key: 'plugin.node.enabled', value: false }) event.fire('status', { key: 'plugin.node.enabled', value: false })
log.info('关闭【NPM】代理成功') log.info('关闭【NPM】代理成功')
return ret return ret
} },
} }
return nodeApi return nodeApi
} }
@ -187,7 +188,7 @@ module.exports = {
key: 'node', key: 'node',
config: nodeConfig, config: nodeConfig,
status: { status: {
enabled: false enabled: false,
}, },
plugin: NodePlugin plugin: NodePlugin,
} }

10
packages/core/src/modules/plugin/overwall/config.js

@ -6,8 +6,8 @@ module.exports = {
'ow-prod.docmirror.top': { 'ow-prod.docmirror.top': {
port: 443, port: 443,
path: 'X2dvX292ZXJfd2FsbF8', path: 'X2dvX292ZXJfd2FsbF8',
password: 'dev_sidecar_is_666' password: 'dev_sidecar_is_666',
} },
}, },
targets: { targets: {
'*.github.com': true, '*.github.com': true,
@ -36,13 +36,13 @@ module.exports = {
'*.intlify.dev': true, '*.intlify.dev': true,
'*.segment.io': true, '*.segment.io': true,
'*.shields.io': true, '*.shields.io': true,
'*.jsdelivr.net': true '*.jsdelivr.net': true,
}, },
pac: { pac: {
enabled: true, enabled: true,
autoUpdate: true, autoUpdate: true,
pacFileUpdateUrl: 'https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt', pacFileUpdateUrl: 'https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt',
pacFileAbsolutePath: null, // 自定义 pac.txt 文件位置,可以是本地文件路径 pacFileAbsolutePath: null, // 自定义 pac.txt 文件位置,可以是本地文件路径
pacFilePath: './extra/pac/pac.txt' // 内置 pac.txt 文件路径 pacFilePath: './extra/pac/pac.txt', // 内置 pac.txt 文件路径
} },
} }

12
packages/core/src/modules/plugin/overwall/index.js

@ -36,14 +36,12 @@ const Plugin = function (context) {
for (const key in conf.targets) { for (const key in conf.targets) {
serverConfig.intercepts[key] = { serverConfig.intercepts[key] = {
'.*': { '.*': {
// eslint-disable-next-line no-template-curly-in-string proxy: `${main}/\${host}`,
proxy: main + '/${host}', backup,
backup },
}
} }
} }
} },
} }
return api return api
} }
@ -51,5 +49,5 @@ const Plugin = function (context) {
module.exports = { module.exports = {
key: 'overwall', key: 'overwall',
config: pluginConfig, config: pluginConfig,
plugin: Plugin plugin: Plugin,
} }

4
packages/core/src/modules/plugin/pip/config.js

@ -8,6 +8,6 @@ module.exports = {
setting: { setting: {
command: 'pip', command: 'pip',
trustedHost: 'pypi.org', trustedHost: 'pypi.org',
registry: 'https://pypi.org/simple/'// 可以选择切换官方或者淘宝镜像 registry: 'https://pypi.org/simple/', // 可以选择切换官方或者淘宝镜像
} },
} }

9
packages/core/src/modules/plugin/pip/index.js

@ -1,4 +1,5 @@
const pipConfig = require('./config') const pipConfig = require('./config')
const PipPlugin = function (context) { const PipPlugin = function (context) {
const { config, shell, event, log } = context const { config, shell, event, log } = context
const api = { const api = {
@ -20,7 +21,7 @@ const PipPlugin = function (context) {
}, },
async getPipEnv () { async getPipEnv () {
const command = config.get().plugin.pip.setting.command const command = config.get().plugin.pip.setting.command
let ret = await shell.exec([command + ' config list'], { type: 'cmd' }) let ret = await shell.exec([`${command} config list`], { type: 'cmd' })
if (ret != null) { if (ret != null) {
ret = ret.trim() ret = ret.trim()
const lines = ret.split('\n') const lines = ret.split('\n')
@ -81,7 +82,7 @@ const PipPlugin = function (context) {
async unsetProxy () { async unsetProxy () {
} },
} }
return api return api
} }
@ -90,7 +91,7 @@ module.exports = {
key: 'pip', key: 'pip',
config: pipConfig, config: pipConfig,
status: { status: {
enabled: false enabled: false,
}, },
plugin: PipPlugin plugin: PipPlugin,
} }

12
packages/core/src/modules/proxy/index.js

@ -43,7 +43,7 @@ const ProxyPlugin = function (context) {
await shell.enableLoopback() await shell.enableLoopback()
log.info('打开EnableLoopback成功') log.info('打开EnableLoopback成功')
return true return true
} },
} }
return api return api
} }
@ -207,7 +207,7 @@ module.exports = {
// endregion // endregion
// 本地地址,无需代理 // 本地地址,无需代理
localhost: true, 'localhost': true,
'localhost.*': true, // 部分VPN会在host中添加这种格式的域名指向127.0.0.1,所以也排除掉 'localhost.*': true, // 部分VPN会在host中添加这种格式的域名指向127.0.0.1,所以也排除掉
'127.*.*.*': true, '127.*.*.*': true,
'test.*': true, // 本地开发时,测试用的虚拟域名格式,无需代理 'test.*': true, // 本地开发时,测试用的虚拟域名格式,无需代理
@ -232,12 +232,12 @@ module.exports = {
'172.31.*.*': true, '172.31.*.*': true,
// 局域网地址,无需代理 // 局域网地址,无需代理
'192.168.*.*': true '192.168.*.*': true,
} },
}, },
status: { status: {
enabled: false, enabled: false,
proxyTarget: '' proxyTarget: '',
}, },
plugin: ProxyPlugin plugin: ProxyPlugin,
} }

12
packages/core/src/modules/server/index.js

@ -1,19 +1,19 @@
const lodash = require('lodash')
const config = require('../../config') const config = require('../../config')
const event = require('../../event') const event = require('../../event')
const status = require('../../status') const status = require('../../status')
const lodash = require('lodash')
const fork = require('child_process').fork const fork = require('child_process').fork
const log = require('../../utils/util.log')
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const jsonApi = require('@docmirror/mitmproxy/src/json') const jsonApi = require('@docmirror/mitmproxy/src/json')
const log = require('../../utils/util.log')
let server = null let server = null
function fireStatus (status) { function fireStatus (status) {
event.fire('status', { key: 'server.enabled', value: status }) event.fire('status', { key: 'server.enabled', value: status })
} }
function sleep (time) { function sleep (time) {
return new Promise(resolve => { return new Promise((resolve) => {
setTimeout(() => { setTimeout(() => {
resolve() resolve()
}, time) }, time)
@ -84,7 +84,7 @@ const serverApi = {
process: serverProcess, process: serverProcess,
close () { close () {
serverProcess.send({ type: 'action', event: { key: 'close' } }) serverProcess.send({ type: 'action', event: { key: 'close' } })
} },
} }
serverProcess.on('beforeExit', (code) => { serverProcess.on('beforeExit', (code) => {
log.warn('server process beforeExit, code:', code) log.warn('server process beforeExit, code:', code)
@ -98,7 +98,7 @@ const serverApi = {
serverProcess.on('uncaughtException', (err, origin) => { serverProcess.on('uncaughtException', (err, origin) => {
log.error('server process uncaughtException:', err) log.error('server process uncaughtException:', err)
}) })
serverProcess.on('message', function (msg) { serverProcess.on('message', (msg) => {
log.info('收到子进程消息:', JSON.stringify(msg)) log.info('收到子进程消息:', JSON.stringify(msg))
if (msg.type === 'status') { if (msg.type === 'status') {
fireStatus(msg.event) fireStatus(msg.event)
@ -166,6 +166,6 @@ const serverApi = {
if (server) { if (server) {
server.process.send({ type: 'speed', event: { key: 'reTest' } }) server.process.send({ type: 'speed', event: { key: 'reTest' } })
} }
} },
} }
module.exports = serverApi module.exports = serverApi

17
packages/core/src/shell/index.js

@ -1,13 +1,14 @@
const shell = require('./shell') const enableLoopback = require('./scripts/enable-loopback')
const killByPort = require('./scripts/kill-by-port') const extraPath = require('./scripts/extra-path')
const setupCa = require('./scripts/setup-ca')
const getSystemEnv = require('./scripts/get-system-env')
const setSystemEnv = require('./scripts/set-system-env')
const getNpmEnv = require('./scripts/get-npm-env') const getNpmEnv = require('./scripts/get-npm-env')
const getSystemEnv = require('./scripts/get-system-env')
const killByPort = require('./scripts/kill-by-port')
const setNpmEnv = require('./scripts/set-npm-env') const setNpmEnv = require('./scripts/set-npm-env')
const setSystemEnv = require('./scripts/set-system-env')
const setSystemProxy = require('./scripts/set-system-proxy/index') const setSystemProxy = require('./scripts/set-system-proxy/index')
const enableLoopback = require('./scripts/enable-loopback') const setupCa = require('./scripts/setup-ca')
const extraPath = require('./scripts/extra-path') const shell = require('./shell')
module.exports = { module.exports = {
killByPort, killByPort,
setupCa, setupCa,
@ -21,5 +22,5 @@ module.exports = {
async exec (cmds, args) { async exec (cmds, args) {
return shell.getSystemShell().exec(cmds, args) return shell.getSystemShell().exec(cmds, args)
}, },
getSystemPlatform: shell.getSystemPlatform getSystemPlatform: shell.getSystemPlatform,
} }

8
packages/core/src/shell/scripts/enable-loopback.js

@ -2,7 +2,9 @@
*/ */
const Shell = require('../shell') const Shell = require('../shell')
const extraPath = require('./extra-path') const extraPath = require('./extra-path')
const execute = Shell.execute const execute = Shell.execute
const executor = { const executor = {
async windows (exec) { async windows (exec) {
const loopbackPath = extraPath.getEnableLoopbackPath() const loopbackPath = extraPath.getEnableLoopbackPath()
@ -10,11 +12,11 @@ const executor = {
await execFile(loopbackPath) await execFile(loopbackPath)
}, },
async linux (exec, { port }) { async linux (exec, { port }) {
throw Error('不支持此操作') throw new Error('不支持此操作')
}, },
async mac (exec, { port }) { async mac (exec, { port }) {
throw Error('不支持此操作') throw new Error('不支持此操作')
} },
} }
module.exports = async function (args) { module.exports = async function (args) {

4
packages/core/src/shell/scripts/extra-path/index.js

@ -1,5 +1,5 @@
const log = require('../../../utils/util.log')
const path = require('path') const path = require('path')
const log = require('../../../utils/util.log')
function getExtraPath () { function getExtraPath () {
let extraPath = process.env.DS_EXTRA_PATH let extraPath = process.env.DS_EXTRA_PATH
@ -27,5 +27,5 @@ function getEnableLoopbackPath () {
module.exports = { module.exports = {
getProxyExePath, getProxyExePath,
getEnableLoopbackPath, getEnableLoopbackPath,
getClearBatPath getClearBatPath,
} }

10
packages/core/src/shell/scripts/get-npm-env.js

@ -1,9 +1,11 @@
/** /**
* 获取环境变量 * 获取环境变量
*/ */
const Shell = require('../shell')
const jsonApi = require('@docmirror/mitmproxy/src/json') const jsonApi = require('@docmirror/mitmproxy/src/json')
const Shell = require('../shell')
const execute = Shell.execute const execute = Shell.execute
const executor = { const executor = {
async windows (exec) { async windows (exec) {
const ret = await exec(['npm config list --json'], { type: 'cmd' }) const ret = await exec(['npm config list --json'], { type: 'cmd' })
@ -14,11 +16,11 @@ const executor = {
return {} return {}
}, },
async linux (exec, { port }) { async linux (exec, { port }) {
throw Error('暂未实现此功能') throw new Error('暂未实现此功能')
}, },
async mac (exec, { port }) { async mac (exec, { port }) {
throw Error('暂未实现此功能') throw new Error('暂未实现此功能')
} },
} }
module.exports = async function (args) { module.exports = async function (args) {

8
packages/core/src/shell/scripts/get-system-env.js

@ -2,7 +2,9 @@
* 获取环境变量 * 获取环境变量
*/ */
const Shell = require('../shell') const Shell = require('../shell')
const execute = Shell.execute const execute = Shell.execute
const executor = { const executor = {
async windows (exec) { async windows (exec) {
const ret = await exec(['set'], { type: 'cmd' }) const ret = await exec(['set'], { type: 'cmd' })
@ -19,11 +21,11 @@ const executor = {
return map return map
}, },
async linux (exec, { port }) { async linux (exec, { port }) {
throw Error('暂未实现此功能') throw new Error('暂未实现此功能')
}, },
async mac (exec, { port }) { async mac (exec, { port }) {
throw Error('暂未实现此功能') throw new Error('暂未实现此功能')
} },
} }
module.exports = async function (args) { module.exports = async function (args) {

7
packages/core/src/shell/scripts/kill-by-port.js

@ -1,4 +1,5 @@
const Shell = require('../shell') const Shell = require('../shell')
const execute = Shell.execute const execute = Shell.execute
const executor = { const executor = {
@ -9,13 +10,13 @@ const executor = {
return true return true
}, },
async linux (exec, { port }) { async linux (exec, { port }) {
await exec('kill `lsof -i:' + port + " |grep 'dev-sidecar\\|electron\\|@docmirro' |awk '{print $2}'`") await exec(`kill \`lsof -i:${port} |grep 'dev-sidecar\\|electron\\|@docmirro' |awk '{print $2}'\``)
return true return true
}, },
async mac (exec, { port }) { async mac (exec, { port }) {
await exec('kill `lsof -i:' + port + " |grep 'dev-side\\|Elect' |awk '{print $2}'`") await exec(`kill \`lsof -i:${port} |grep 'dev-side\\|Elect' |awk '{print $2}'\``)
return true return true
} },
} }
module.exports = async function (args) { module.exports = async function (args) {

8
packages/core/src/shell/scripts/set-npm-env.js

@ -2,7 +2,9 @@
* 设置环境变量 * 设置环境变量
*/ */
const Shell = require('../shell') const Shell = require('../shell')
const execute = Shell.execute const execute = Shell.execute
const executor = { const executor = {
async windows (exec, { list }) { async windows (exec, { list }) {
const cmds = [] const cmds = []
@ -13,11 +15,11 @@ const executor = {
return ret return ret
}, },
async linux (exec, { port }) { async linux (exec, { port }) {
throw Error('暂未实现此功能') throw new Error('暂未实现此功能')
}, },
async mac (exec, { port }) { async mac (exec, { port }) {
throw Error('暂未实现此功能') throw new Error('暂未实现此功能')
} },
} }
module.exports = async function (args) { module.exports = async function (args) {

8
packages/core/src/shell/scripts/set-system-env.js

@ -2,7 +2,9 @@
* 设置环境变量 * 设置环境变量
*/ */
const Shell = require('../shell') const Shell = require('../shell')
const execute = Shell.execute const execute = Shell.execute
const executor = { const executor = {
async windows (exec, { list }) { async windows (exec, { list }) {
const cmds = [] const cmds = []
@ -22,11 +24,11 @@ const executor = {
return ret return ret
}, },
async linux (exec, { port }) { async linux (exec, { port }) {
throw Error('暂未实现此功能') throw new Error('暂未实现此功能')
}, },
async mac (exec, { port }) { async mac (exec, { port }) {
throw Error('暂未实现此功能') throw new Error('暂未实现此功能')
} },
} }
module.exports = async function (args) { module.exports = async function (args) {

33
packages/core/src/shell/scripts/set-system-proxy/index.js

@ -1,16 +1,16 @@
/** /**
* 获取环境变量 * 获取环境变量
*/ */
const Shell = require('../../shell')
const Registry = require('winreg') const Registry = require('winreg')
const Shell = require('../../shell')
const execute = Shell.execute
const execFile = Shell.execFile
const log = require('../../../utils/util.log')
const extraPath = require('../extra-path/index')
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const request = require('request') const request = require('request')
const log = require('../../../utils/util.log')
const extraPath = require('../extra-path/index')
const execute = Shell.execute
const execFile = Shell.execFile
let config = null let config = null
function loadConfig () { function loadConfig () {
@ -20,7 +20,6 @@ function loadConfig () {
} }
async function _winUnsetProxy (exec, setEnv) { async function _winUnsetProxy (exec, setEnv) {
// eslint-disable-next-line no-constant-condition
const proxyPath = extraPath.getProxyExePath() const proxyPath = extraPath.getProxyExePath()
await execFile(proxyPath, ['set', '1']) await execFile(proxyPath, ['set', '1'])
@ -28,7 +27,7 @@ async function _winUnsetProxy (exec, setEnv) {
await exec('echo \'删除环境变量 HTTPS_PROXY、HTTP_PROXY\'') await exec('echo \'删除环境变量 HTTPS_PROXY、HTTP_PROXY\'')
const regKey = new Registry({ // new operator is optional const regKey = new Registry({ // new operator is optional
hive: Registry.HKCU, // open registry hive HKEY_CURRENT_USER hive: Registry.HKCU, // open registry hive HKEY_CURRENT_USER
key: '\\Environment' // key containing autostart programs key: '\\Environment', // key containing autostart programs
}) })
regKey.get('HTTPS_PROXY', (err) => { regKey.get('HTTPS_PROXY', (err) => {
if (!err) { if (!err) {
@ -74,12 +73,12 @@ async function downloadDomesticDomainAllowListAsync () {
let fileTxt = body let fileTxt = body
try { try {
if (fileTxt.indexOf('*.') < 0) { if (!fileTxt.includes('*.')) {
fileTxt = Buffer.from(fileTxt, 'base64').toString('utf8') fileTxt = Buffer.from(fileTxt, 'base64').toString('utf8')
// log.debug('解析 base64 后的 domestic-domain-allowlist:', fileTxt) // log.debug('解析 base64 后的 domestic-domain-allowlist:', fileTxt)
} }
} catch (e) { } catch (e) {
if (fileTxt.indexOf('*.') < 0) { if (!fileTxt.includes('*.')) {
log.error(`远程 domestic-domain-allowlist.txt 文件内容即不是base64格式,也不是要求的格式,url: ${remoteFileUrl},body: ${body}`) log.error(`远程 domestic-domain-allowlist.txt 文件内容即不是base64格式,也不是要求的格式,url: ${remoteFileUrl},body: ${body}`)
return return
} }
@ -195,7 +194,7 @@ function getProxyExcludeIpStr (split) {
try { try {
let domesticDomainAllowList = getDomesticDomainAllowList() let domesticDomainAllowList = getDomesticDomainAllowList()
if (domesticDomainAllowList) { if (domesticDomainAllowList) {
domesticDomainAllowList = (domesticDomainAllowList + '\n').replaceAll(/[\r\n]+/g, '\n').replaceAll(/[^\n]*[^*.a-zA-Z\d-\n]+[^\n]*\r?\n/g, '').trim().replaceAll(/\s*\n+\s*/g, split) domesticDomainAllowList = (`${domesticDomainAllowList}\n`).replaceAll(/[\r\n]+/g, '\n').replaceAll(/[\d*\-.A-Z]*[^\d\n*\-.A-Z][^\n]*\n/gi, '').trim().replaceAll(/\s*\n\s*/g, split)
if (domesticDomainAllowList) { if (domesticDomainAllowList) {
excludeIpStr += domesticDomainAllowList excludeIpStr += domesticDomainAllowList
log.info('系统代理排除列表拼接国内域名') log.info('系统代理排除列表拼接国内域名')
@ -224,7 +223,7 @@ async function _winSetProxy (exec, ip, port, setEnv) {
let proxyAddr = `https=http://${ip}:${port}` let proxyAddr = `https=http://${ip}:${port}`
// http // http
if (config.get().proxy.proxyHttp) { if (config.get().proxy.proxyHttp) {
proxyAddr = `http=http://${ip}:${port - 1};` + proxyAddr proxyAddr = `http=http://${ip}:${port - 1};${proxyAddr}`
} }
// 读取排除域名 // 读取排除域名
@ -276,25 +275,25 @@ const executor = {
const setProxyCmd = [ const setProxyCmd = [
'gsettings set org.gnome.system.proxy mode manual', 'gsettings set org.gnome.system.proxy mode manual',
`gsettings set org.gnome.system.proxy.https host ${ip}`, `gsettings set org.gnome.system.proxy.https host ${ip}`,
`gsettings set org.gnome.system.proxy.https port ${port}` `gsettings set org.gnome.system.proxy.https port ${port}`,
] ]
// http // http
if (config.get().proxy.proxyHttp) { if (config.get().proxy.proxyHttp) {
setProxyCmd.push(`gsettings set org.gnome.system.proxy.http host ${ip}`) setProxyCmd.push(`gsettings set org.gnome.system.proxy.http host ${ip}`)
setProxyCmd.push(`gsettings set org.gnome.system.proxy.http port ${port - 1}`) setProxyCmd.push(`gsettings set org.gnome.system.proxy.http port ${port - 1}`)
} else { } else {
setProxyCmd.push("gsettings set org.gnome.system.proxy.http host ''") setProxyCmd.push('gsettings set org.gnome.system.proxy.http host \'\'')
setProxyCmd.push('gsettings set org.gnome.system.proxy.http port 0') setProxyCmd.push('gsettings set org.gnome.system.proxy.http port 0')
} }
// 设置排除域名(ignore-hosts) // 设置排除域名(ignore-hosts)
const excludeIpStr = getProxyExcludeIpStr("', '") const excludeIpStr = getProxyExcludeIpStr('\', \'')
setProxyCmd.push(`gsettings set org.gnome.system.proxy ignore-hosts "['${excludeIpStr}']"`) setProxyCmd.push(`gsettings set org.gnome.system.proxy ignore-hosts "['${excludeIpStr}']"`)
await exec(setProxyCmd) await exec(setProxyCmd)
} else { // 关闭代理 } else { // 关闭代理
const setProxyCmd = [ const setProxyCmd = [
'gsettings set org.gnome.system.proxy mode none' 'gsettings set org.gnome.system.proxy mode none',
] ]
await exec(setProxyCmd) await exec(setProxyCmd)
} }
@ -342,7 +341,7 @@ const executor = {
// ` // `
// await exec(removeEnv) // await exec(removeEnv)
} }
} },
} }
module.exports = async function (args) { module.exports = async function (args) {

8
packages/core/src/shell/scripts/setup-ca.js

@ -1,8 +1,10 @@
const Shell = require('../shell') const Shell = require('../shell')
const execute = Shell.execute const execute = Shell.execute
const executor = { const executor = {
async windows (exec, { certPath }) { async windows (exec, { certPath }) {
const cmds = ['start "" "' + certPath + '"'] const cmds = [`start "" "${certPath}"`]
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
const ret = await exec(cmds, { type: 'cmd' }) const ret = await exec(cmds, { type: 'cmd' })
return true return true
@ -14,11 +16,11 @@ const executor = {
return true return true
}, },
async mac (exec, { certPath }) { async mac (exec, { certPath }) {
const cmds = ['open "' + certPath + '"'] const cmds = [`open "${certPath}"`]
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
const ret = await exec(cmds, { type: 'cmd' }) const ret = await exec(cmds, { type: 'cmd' })
return true return true
} },
} }
module.exports = async function (args) { module.exports = async function (args) {

19
packages/core/src/shell/shell.js

@ -1,11 +1,14 @@
const os = require('os')
const childProcess = require('child_process') const childProcess = require('child_process')
const os = require('os')
const _execFile = childProcess.execFile const _execFile = childProcess.execFile
const PowerShell = require('node-powershell')
const log = require('../utils/util.log')
const fixPath = require('fix-path') const fixPath = require('fix-path')
const iconv = require('iconv-lite') const iconv = require('iconv-lite')
const PowerShell = require('node-powershell')
const log = require('../utils/util.log')
fixPath() fixPath()
class SystemShell { class SystemShell {
static async exec (cmds, args) { static async exec (cmds, args) {
throw new Error('You have to implement the method exec!') throw new Error('You have to implement the method exec!')
@ -46,7 +49,7 @@ class WindowsSystemShell extends SystemShell {
if (type === 'ps') { if (type === 'ps') {
const ps = new PowerShell({ const ps = new PowerShell({
executionPolicy: 'Bypass', executionPolicy: 'Bypass',
noProfile: true noProfile: true,
}) })
for (const cmd of cmds) { for (const cmd of cmds) {
@ -63,7 +66,7 @@ class WindowsSystemShell extends SystemShell {
} else { } else {
let compose = 'echo "test" ' // 'chcp 65001 ' let compose = 'echo "test" ' // 'chcp 65001 '
for (const cmd of cmds) { for (const cmd of cmds) {
compose += ' && ' + cmd compose += ` && ${cmd}`
} }
// compose += '&& exit' // compose += '&& exit'
const ret = await childExec(compose, args) const ret = await childExec(compose, args)
@ -77,7 +80,7 @@ function _childExec (composeCmds, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const childProcess = require('child_process') const childProcess = require('child_process')
log.info('shell:', composeCmds) log.info('shell:', composeCmds)
childProcess.exec(composeCmds, options, function (error, stdout, stderr) { childProcess.exec(composeCmds, options, (error, stdout, stderr) => {
if (error) { if (error) {
if (options.printErrorLog !== false) { if (options.printErrorLog !== false) {
log.error('cmd 命令执行错误:\n===>\ncommands:', composeCmds, '\n error:', error, '\n<===') log.error('cmd 命令执行错误:\n===>\ncommands:', composeCmds, '\n error:', error, '\n<===')
@ -100,7 +103,7 @@ function childExec (composeCmds, options = {}) {
const childProcess = require('child_process') const childProcess = require('child_process')
log.info('shell:', composeCmds) log.info('shell:', composeCmds)
childProcess.exec(composeCmds, { encoding: binaryEncoding }, function (error, stdout, stderr) { childProcess.exec(composeCmds, { encoding: binaryEncoding }, (error, stdout, stderr) => {
if (error) { if (error) {
// console.log('------', decoder.decode(stderr)) // console.log('------', decoder.decode(stderr))
const message = iconv.decode(Buffer.from(stderr, binaryEncoding), encoding) const message = iconv.decode(Buffer.from(stderr, binaryEncoding), encoding)
@ -175,5 +178,5 @@ module.exports = {
getSystemShell, getSystemShell,
getSystemPlatform, getSystemPlatform,
execute, execute,
execFile execFile,
} }

6
packages/core/src/shell/test.js

@ -34,13 +34,13 @@
// console.error(e) // console.error(e)
// }) // })
const request = require('request')
const fs = require('fs') const fs = require('fs')
const request = require('request')
request({ request({
url: 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', url: 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js',
proxy: 'http://127.0.0.1:31181', proxy: 'http://127.0.0.1:31181',
ca: fs.readFileSync('C:/Users/Administrator/.dev-sidecar/dev-sidecar.ca.crt') ca: fs.readFileSync('C:/Users/Administrator/.dev-sidecar/dev-sidecar.ca.crt'),
// eslint-disable-next-line handle-callback-err
}, (err, res, body) => { }, (err, res, body) => {
console.log(body) console.log(body)
}) })

5
packages/core/src/status.js

@ -1,10 +1,11 @@
const event = require('./event')
const lodash = require('lodash') const lodash = require('lodash')
const event = require('./event')
const log = require('./utils/util.log') const log = require('./utils/util.log')
const status = { const status = {
server: { enabled: false }, server: { enabled: false },
proxy: {}, proxy: {},
plugin: {} plugin: {},
} }
event.register('status', (event) => { event.register('status', (event) => {

9
packages/core/src/utils/util.log.js

@ -1,14 +1,17 @@
const log4js = require('log4js') const log4js = require('log4js')
const config = require('../config/index') const config = require('../config/index')
const path = require('path')
const level = process.env.NODE_ENV === 'development' ? 'debug' : 'info'
function getDefaultConfigBasePath () { function getDefaultConfigBasePath () {
return config.server.setting.userBasePath return config.server.setting.userBasePath
} }
const level = process.env.NODE_ENV === 'development' ? 'debug' : 'info'
const path = require('path')
const filename = path.join(getDefaultConfigBasePath(), '/logs/core.log') const filename = path.join(getDefaultConfigBasePath(), '/logs/core.log')
log4js.configure({ log4js.configure({
appenders: { std: { type: 'stdout' }, file: { type: 'file', pattern: 'yyyy-MM-dd', daysToKeep: 3, filename } }, appenders: { std: { type: 'stdout' }, file: { type: 'file', pattern: 'yyyy-MM-dd', daysToKeep: 3, filename } },
categories: { default: { appenders: ['file', 'std'], level: level } } categories: { default: { appenders: ['file', 'std'], level } },
}) })
const logger = log4js.getLogger('core') const logger = log4js.getLogger('core')
module.exports = logger module.exports = logger

2
packages/core/start/index.js

@ -1,6 +1,6 @@
const fs = require('fs')
const jsonApi = require('@docmirror/mitmproxy/src/json') const jsonApi = require('@docmirror/mitmproxy/src/json')
const DevSidecar = require('../index') const DevSidecar = require('../index')
const fs = require('fs')
const log = require('../src/utils/util.log') const log = require('../src/utils/util.log')
// 启动服务 // 启动服务

7
packages/core/start/mitmproxy.js

@ -1,9 +1,11 @@
const fs = require('fs')
const path = require('path')
const server = require('@docmirror/mitmproxy') const server = require('@docmirror/mitmproxy')
const jsonApi = require('@docmirror/mitmproxy/src/json') const jsonApi = require('@docmirror/mitmproxy/src/json')
const path = require('path')
const home = process.env.USER_HOME || process.env.HOME || 'C:/Users/Administrator/'
const log = require('../src/utils/util.log') const log = require('../src/utils/util.log')
const home = process.env.USER_HOME || process.env.HOME || 'C:/Users/Administrator/'
let configPath let configPath
if (process.argv && process.argv.length > 3) { if (process.argv && process.argv.length > 3) {
configPath = process.argv[2] configPath = process.argv[2]
@ -11,7 +13,6 @@ if (process.argv && process.argv.length > 3) {
configPath = path.join(home, '.dev-sidecar/running.json') configPath = path.join(home, '.dev-sidecar/running.json')
} }
const fs = require('fs')
const configJson = fs.readFileSync(configPath) const configJson = fs.readFileSync(configPath)
log.info('读取 running.json by core 成功:', configPath) log.info('读取 running.json by core 成功:', configPath)
const config = jsonApi.parse(configJson.toString()) const config = jsonApi.parse(configJson.toString())

64
packages/core/start/user_config.json5

@ -1,42 +1,42 @@
{ {
app: { "app": {
autoStart: { "autoStart": {
enabled: true, "enabled": true
}, },
mode: 'default', "mode": "default"
}, },
plugin: { "plugin": {
node: { "node": {
setting: { "setting": {
yarnRegistry: 'null', "yarnRegistry": "null"
}, }
},
git: {
enabled: true,
}, },
overwall: { "git": {
enabled: false, "enabled": true
targets: {
'*gagedigital.com': true,
'*yonsz.net': true,
'*bootstrapcdn.com': true,
'*cloudflare.com': true,
'help.yonsz.net': true,
},
}, },
"overwall": {
"enabled": false,
"targets": {
"*gagedigital.com": true,
"*yonsz.net": true,
"*bootstrapcdn.com": true,
"*cloudflare.com": true,
"help.yonsz.net": true
}
}
}, },
server: { "server": {
intercepts: { "intercepts": {
'dev-sidecar.docmirror.cn': { "dev-sidecar.docmirror.cn": {
'.*': { ".*": {
proxy: 'dev-sidecar-preview.docmirror.cn', "proxy": "dev-sidecar-preview.docmirror.cn"
}, }
}, },
'test1111.gagedigital.com': { "test1111.gagedigital.com": {
'.*': { ".*": {
proxy: 'test1.gagedigital.com', "proxy": "test1.gagedigital.com"
}, }
} }
}, }
} }
} }

13
packages/core/test/httpsVerifyTest.js

@ -1,5 +1,7 @@
const https = require('https') const https = require('https')
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '1' process.env.NODE_TLS_REJECT_UNAUTHORIZED = '1'
function request () { function request () {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const options = { const options = {
@ -7,7 +9,7 @@ function request () {
port: 443, port: 443,
path: '/ssltest.php', path: '/ssltest.php',
method: 'GET', method: 'GET',
rejectUnauthorized: true rejectUnauthorized: true,
} }
console.log('ssl test: gagedigital') console.log('ssl test: gagedigital')
const req = https.request(options, (res) => { const req = https.request(options, (res) => {
@ -28,12 +30,13 @@ function request () {
}) })
} }
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
describe('ssl.verify', function () { describe('ssl.verify', () => {
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
it('regex.test.js', async function () { it('regex.test.js', async () => {
// https.request('https://test1.gagedigital.com/ssltest.php') // https.request('https://test1.gagedigital.com/ssltest.php')
await request() await request()
// eslint-disable-next-line no-unused-expressions
// expect(ret).be.ok // expect(ret).be.ok
}) })
}) })

28
packages/core/test/mergeTest.js

@ -5,28 +5,28 @@ const mergeApi = require('../src/merge.js')
const defConfig = { const defConfig = {
a: { a: {
aa: { value: 1 }, aa: { value: 1 },
bb: { value: 2 } bb: { value: 2 },
}, },
b: { c: 2 }, b: { c: 2 },
c: 1, c: 1,
d: [1, 2, 3], d: [1, 2, 3],
e: { e: {
aa: 2, aa: 2,
ee: 5 ee: 5,
}, },
f: { f: {
x: 1 x: 1,
}, },
g: [1, 2], g: [1, 2],
h: null, h: null,
i: null i: null,
} }
// 自定义配置 // 自定义配置
const customConfig = { const customConfig = {
a: { a: {
bb: { value: 2 }, bb: { value: 2 },
cc: { value: 3 } cc: { value: 3 },
}, },
b: { c: 2 }, b: { c: 2 },
c: null, c: null,
@ -34,11 +34,11 @@ const customConfig = {
e: { e: {
aa: 2, aa: 2,
ee: 5, ee: 5,
ff: 6 ff: 6,
}, },
f: {}, f: {},
g: [1, 2], g: [1, 2],
h: null h: null,
} }
// doDiff // doDiff
@ -49,16 +49,16 @@ console.log('\r')
const doDiffExpect = { const doDiffExpect = {
a: { a: {
aa: null, aa: null,
cc: { value: 3 } cc: { value: 3 },
}, },
c: null, c: null,
d: [1, 2, 3, 4], d: [1, 2, 3, 4],
e: { e: {
ff: 6 ff: 6,
}, },
f: { f: {
x: null x: null,
} },
} }
console.log('check diff result:', lodash.isEqual(doDiffResult, doDiffExpect)) console.log('check diff result:', lodash.isEqual(doDiffResult, doDiffExpect))
console.log('\r') console.log('\r')
@ -72,17 +72,17 @@ console.log('running:', JSON.stringify(doMergeResult, null, 2))
const doMergeExpect = { const doMergeExpect = {
a: { a: {
bb: { value: 2 }, bb: { value: 2 },
cc: { value: 3 } cc: { value: 3 },
}, },
b: { c: 2 }, b: { c: 2 },
d: [1, 2, 3, 4], d: [1, 2, 3, 4],
e: { e: {
aa: 2, aa: 2,
ee: 5, ee: 5,
ff: 6 ff: 6,
}, },
f: {}, f: {},
g: [1, 2] g: [1, 2],
} }
console.log('check merge result:', lodash.isEqual(doMergeResult, doMergeExpect)) console.log('check merge result:', lodash.isEqual(doMergeResult, doMergeExpect))
console.log('\r') console.log('\r')

6
packages/core/test/regex.test.js

@ -1,13 +1,13 @@
const expect = require('chai').expect const expect = require('chai').expect
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
describe('test', function () { describe('test', () => {
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
it('regexp', function () { it('regexp', () => {
const test = '^/[^/]+/[^/]+(/releases(/.*)?)?$' const test = '^/[^/]+/[^/]+(/releases(/.*)?)?$'
const reg = new RegExp(test) const reg = new RegExp(test)
const ret = reg.test('/docmirror/dev-sidecar/releases/tag') const ret = reg.test('/docmirror/dev-sidecar/releases/tag')
// eslint-disable-next-line no-unused-expressions
expect(ret).be.ok expect(ret).be.ok
}) })
}) })

14
packages/core/test/requestTest.js

@ -1,5 +1,5 @@
const request = require('request')
const HttpsAgent = require('@docmirror/mitmproxy/src/lib/proxy/common/ProxyHttpsAgent') const HttpsAgent = require('@docmirror/mitmproxy/src/lib/proxy/common/ProxyHttpsAgent')
const request = require('request')
const options = { const options = {
url: 'https://raw.githubusercontent.com/docmirror/dev-sidecar/refs/heads/master/packages/core/src/config/remote_config.json5', url: 'https://raw.githubusercontent.com/docmirror/dev-sidecar/refs/heads/master/packages/core/src/config/remote_config.json5',
@ -9,8 +9,8 @@ const options = {
keepAlive: true, keepAlive: true,
timeout: 20000, timeout: 20000,
keepAliveTimeout: 30000, keepAliveTimeout: 30000,
rejectUnauthorized: false rejectUnauthorized: false,
}) }),
} }
if (options.agent.options) { if (options.agent.options) {
options.agent.options.rejectUnauthorized = false options.agent.options.rejectUnauthorized = false
@ -18,9 +18,7 @@ if (options.agent.options) {
} }
request(options, (error, response, body) => { request(options, (error, response, body) => {
console.info('error:', error, console.info('error:', error, '\n---------------------------------------------------------------------------\n'
'\n---------------------------------------------------------------------------\n' + + 'response:', response, '\n---------------------------------------------------------------------------\n'
'response:', response, + 'body:', body)
'\n---------------------------------------------------------------------------\n' +
'body:', body)
}) })

Loading…
Cancel
Save