@oipage/cli 0.3.0-alpha.2 → 0.3.0-alpha.4

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 CHANGED
@@ -31,10 +31,17 @@ v0.3.0:
31
31
  * 加固阻止 Nmap 等扫描器的服务探测
32
32
  * 文件扩展名提取可能抛出 TypeError 问题
33
33
  * 路径匹配添加更多兼容,防止意外错误
34
+ * 修复对文件夹判断未考虑符号链接指向的目录问题导致import语句解析出错问题
35
+ * 兼容 "@oipage/browser.js" 类似的包
34
36
  2、修复错误读取导致服务器奔溃问题
37
+ 3、对于二进制文件,采用流式传输
35
38
  - 优化改造
36
39
  1、优化命令行相关文档优化,提高可读性
37
- 2、服务器proxy中decodeURIComponent捕获错误,方便调试
40
+ 2、优化服务器若干问题
41
+ * proxy中decodeURIComponent捕获错误,方便调试
42
+ * 打印访问IP,方便后续追踪攻击
38
43
  - 新增功能
39
44
  1、oipage-cli notebook
40
45
  快速笔记
46
+ 2、devServer
47
+ * 支持gzip
package/bin/help.js CHANGED
@@ -24,6 +24,8 @@ module.exports = function () {
24
24
  --proxy [转发前缀] [转发地址]
25
25
  (注意:转发前缀会被替换为空,相当于设置了 pathRewrite: { '^/myapi': '' })
26
26
  (eg: oipage-cli serve --open --proxy /myapi http://localhost:20000/myapi)
27
+ --gzip [true|false]
28
+ 是否开启gzip(默认true表示开启)
27
29
 
28
30
  【2】oipage-cli notebook 快速笔记
29
31
 
package/bin/run CHANGED
@@ -24,6 +24,7 @@ if (process.argv[2] === "serve") {
24
24
  baseUrl: "./",
25
25
  open: false,
26
26
  cache: true,
27
+ gzip: true,
27
28
  proxy: {},
28
29
  intercept: [],
29
30
  404: null,
@@ -53,11 +54,14 @@ if (process.argv[2] === "serve") {
53
54
  }
54
55
  }
55
56
 
56
- if (argvObj["--port"]) config.devServer.port = argvObj["--port"][0];
57
- if (argvObj["--baseUrl"]) config.devServer.baseUrl = argvObj["--baseUrl"][0];
58
- if (argvObj["--cache"]) config.devServer.cache = argvObj["--cache"][0] === "true";
59
- if (argvObj["--open"]) config.devServer.open = argvObj["--open"][0] || true;
60
- if (argvObj["--website"]) config.devServer.website = argvObj["--website"][0] === "true";
57
+ let resolveBoolean = input => input[0] !== "false";
58
+
59
+ if (argvObj["--port"]) config.devServer.port = resolveBoolean(argvObj["--port"]);
60
+ if (argvObj["--baseUrl"]) config.devServer.baseUrl = resolveBoolean(argvObj["--baseUrl"]);
61
+ if (argvObj["--cache"]) config.devServer.cache = resolveBoolean(argvObj["--cache"]);
62
+ if (argvObj["--gzip"]) config.devServer.gzip = resolveBoolean(argvObj["--gzip"]);
63
+ if (argvObj["--open"]) config.devServer.open = resolveBoolean(argvObj["--open"]);
64
+ if (argvObj["--website"]) config.devServer.website = resolveBoolean(argvObj["--website"]);
61
65
 
62
66
  require("./serve.js")(config);
63
67
  }
package/bin/serve.js CHANGED
@@ -1,6 +1,7 @@
1
1
  const { join, resolve, sep } = require("path");
2
2
  const { existsSync, lstatSync, statSync, createReadStream } = require("fs");
3
3
  const { createServer } = require('http');
4
+ const { gzipSync, createGzip } = require("zlib");
4
5
  const packageValue = require("../package.json");
5
6
  const network = require("./tools/network.js");
6
7
  const mineTypes = require("./data/mineTypes.json");
@@ -9,11 +10,51 @@ const openBrowser = require("./tools/openBrowser.js");
9
10
  const { doIntercept } = require("./intercept.js");
10
11
  const proxy = require("./proxy.js");
11
12
  const resolve404_default = require("./tools/resolve404.js");
13
+ const isBinary = require("./tools/isBinary.js");
12
14
  const websiteIntercept = require("./website-plugins/intercept/index.js");
13
15
  const websiteLoader = require("./website-plugins/loader/index.js");
14
16
 
15
17
  const WebSocketClass = require("./WebSocket/index.js");
16
18
 
19
+ // 可压缩的 MIME 类型集合(文本类资源,压缩收益大)
20
+ const compressibleTypes = new Set([
21
+ "text/html", "text/css", "text/plain", "text/xml", "text/mathml",
22
+ "text/vnd.sun.j2me.app-descriptor", "text/vnd.wap.wml", "text/x-component",
23
+ "application/javascript", "application/json", "application/xml",
24
+ "application/xhtml+xml", "application/atom+xml", "application/rss+xml",
25
+ "application/xspf+xml", "application/x-tcl", "application/x-perl",
26
+ "image/svg+xml"
27
+ ]);
28
+
29
+ // 需要设置 charset 的 MIME 类型前缀/精确匹配集合
30
+ // 文本类资源需要 charset 告知浏览器字符编码,二进制资源不需要
31
+ const charsetPrefixes = ["text/"];
32
+ const charsetTypes = new Set([
33
+ "application/javascript", "application/json", "application/xml",
34
+ "application/xhtml+xml", "application/atom+xml", "application/rss+xml",
35
+ "application/xspf+xml", "application/x-tcl", "application/x-perl",
36
+ "application/rtf", "application/postscript",
37
+ "application/vnd.google-earth.kml+xml", "application/x-javascript",
38
+ "image/svg+xml"
39
+ ]);
40
+
41
+ /**
42
+ * 根据 MIME 类型构建 Content-Type 值
43
+ * 文本类型追加 charset=utf-8,二进制类型不追加
44
+ * @param {string} mimeType MIME 类型
45
+ * @returns {string} 完整的 Content-Type 值
46
+ */
47
+ function buildContentType(mimeType) {
48
+ if (!mimeType) return "text/plain;charset=utf-8";
49
+ if (charsetPrefixes.some(prefix => mimeType.startsWith(prefix))) {
50
+ return mimeType + ";charset=utf-8";
51
+ }
52
+ if (charsetTypes.has(mimeType)) {
53
+ return mimeType + ";charset=utf-8";
54
+ }
55
+ return mimeType;
56
+ }
57
+
17
58
  // 开发服务器
18
59
  module.exports = function (config) {
19
60
  let startTime = new Date().valueOf();
@@ -21,6 +62,7 @@ module.exports = function (config) {
21
62
  const resolve404 = config.devServer["404"] || resolve404_default;
22
63
  const cache = "cache" in config.devServer ? config.devServer.cache : true;
23
64
  const website = "website" in config.devServer ? config.devServer.website : true;
65
+ const gzip = "gzip" in config.devServer ? config.devServer.gzip : false;
24
66
  const port = +config.devServer.port; // 端口号
25
67
  const basePath = resolve((/^\./.test(config.devServer.baseUrl)) ? join(process.cwd(), config.devServer.baseUrl) : config.devServer.baseUrl); // 服务器根路径
26
68
 
@@ -42,7 +84,7 @@ module.exports = function (config) {
42
84
  let Server = createServer(function (request, response) {
43
85
  let headers = request.headers;
44
86
 
45
- const rawIp = request.socket.remoteAddress;
87
+ const rawIp = (request.socket.remoteAddress || '').replace(/^::ffff:/, "").replace(/^::1/, "127.0.0.1");
46
88
 
47
89
  let url;
48
90
  try {
@@ -57,7 +99,7 @@ module.exports = function (config) {
57
99
  // 虽然被 uncaughtException 捕获,但会导致当前请求处理中断且无响应返回,客户端会挂起等待
58
100
  // 2026年8月9日 于南宁
59
101
  response.writeHead(400, {
60
- 'Content-Type': 'text/plain',
102
+ 'Content-Type': buildContentType('text/plain'),
61
103
  'Access-Control-Allow-Origin': '*',
62
104
  'Server': 'Powered by ' + name + '@' + version
63
105
  });
@@ -106,7 +148,7 @@ module.exports = function (config) {
106
148
  !(filePath.startsWith(process.cwd() + sep) || filePath === process.cwd())
107
149
  ) || filePath.includes('\0')) {
108
150
  response.writeHead(403, {
109
- 'Content-Type': "text/plain;charset=utf-8",
151
+ 'Content-Type': buildContentType("text/plain"),
110
152
  'Access-Control-Allow-Origin': '*',
111
153
  'Server': 'Powered by ' + name + '@' + version
112
154
  });
@@ -130,7 +172,7 @@ module.exports = function (config) {
130
172
  let fileModifiedTime = new Date(fileInfo.mtime).toGMTString();
131
173
 
132
174
  let responseHeader = {
133
- 'Content-Type': (fileType || "text/plain") + ";charset=utf-8",
175
+ 'Content-Type': buildContentType(fileType || "text/plain"),
134
176
  'Access-Control-Allow-Origin': '*',
135
177
  'Server': 'Powered by ' + name + '@' + version,
136
178
  'Cache-Control': 'no-cache',
@@ -140,7 +182,11 @@ module.exports = function (config) {
140
182
  'Last-Modified': fileModifiedTime,
141
183
 
142
184
  // 与if-none-match配合使用,做缓存验证
143
- // 'ETag': basePath + "-" + new Date(fileInfo.mtime).toString()
185
+ // ETag 包含 gzip 标志,确保 gzip 配置变化时缓存正确失效
186
+ 'ETag': '"' + fileInfo.mtime.getTime() + (gzip ? '-gz' : '') + '"',
187
+
188
+ // 告知代理/缓存:响应内容会根据 Accept-Encoding 不同而变化
189
+ 'Vary': 'Accept-Encoding'
144
190
  };
145
191
 
146
192
  if (cache && headers["if-modified-since"]) {
@@ -152,10 +198,16 @@ module.exports = function (config) {
152
198
  // 2、作为开发服务器,可能同一个url地址对应的文件不同,被误判为未修改
153
199
  // 2025年12月29日 于南京
154
200
  // if (lastModified <= ifModifiedSince) {}
155
- if (lastModified === ifModifiedSince) {
201
+
202
+ // 同时检查 ETag(If-None-Match),确保 gzip 配置变化时不会错误返回 304
203
+ // 比如:gzip 从关闭改为开启,响应内容从原始变为压缩,ETag 不同,必须重新传输
204
+ // 2026年08月15日 于南宁
205
+ let etagMatch = !headers["if-none-match"] || headers["if-none-match"] === responseHeader['ETag'];
206
+
207
+ if (lastModified === ifModifiedSince && etagMatch) {
156
208
  response.writeHead(304, responseHeader);
157
209
  response.end();
158
- console.log("<i> \x1b[1m\x1b[32m[" + name + "] Cache File: " + url + "\x1b[0m " + new Date().toLocaleString() + "\x1b[33m\x1b[1m 304" + (isXHR ? " " + request.method : "") + "\x1b[0m " + rawIp);
210
+ console.log("<i> \x1b[1m\x1b[32m[" + name + "] Cache File: " + url + "\x1b[0m " + new Date().toLocaleString() + " \x1b[33m\x1b[1m304\x1b[0m" + (isXHR ? " \x1b[33m\x1b[1m" + request.method + "\x1b[0m" : "") + " " + rawIp);
159
211
  return;
160
212
  }
161
213
  }
@@ -163,8 +215,13 @@ module.exports = function (config) {
163
215
  let sendType = "";
164
216
  let entry = headers.accept !== "*/*";
165
217
 
166
- // 如果文件小于10M,认为不大,直接读取
167
- if (fileInfo.size < 10 * 1024 * 1024) {
218
+ // 判断是否需要 gzip 压缩:配置开启 && 客户端支持 && 文件类型可压缩
219
+ let acceptEncoding = headers["accept-encoding"] || "";
220
+ let shouldGzip = gzip && /\bgzip\b/.test(acceptEncoding) && compressibleTypes.has(fileType);
221
+
222
+ // 如果文件小于1M且不是二进制,认为不大,直接读取
223
+ // 如果是二进制文件,即使小于10M也使用流(避免不必要的加载器处理和import解析)
224
+ if (fileInfo.size < 10 * 1024 * 1024 && !isBinary(filePath)) {
168
225
  let { source, resolveImport } = resolveImportFactory(basePath, filePath, entry, isWebsite ? websiteIntercept : config.devServer.intercept, urlArray[1] === "download", isWebsite)
169
226
 
170
227
  // 只处理非下载文件
@@ -181,7 +238,7 @@ module.exports = function (config) {
181
238
  entry, // 是否是浏览器地址栏直接访问
182
239
  setFileType(_fileType) { // 设置文件类型
183
240
  fileType = _fileType;
184
- responseHeader['Content-Type'] = _fileType + ";charset=utf-8";
241
+ responseHeader['Content-Type'] = buildContentType(_fileType);
185
242
  }
186
243
  }, source);
187
244
  break;
@@ -191,8 +248,16 @@ module.exports = function (config) {
191
248
  }
192
249
 
193
250
  sendType = "Read";
251
+ let body = isXHR ? source : resolveImport(source, fileType !== "application/javascript");
252
+
253
+ // gzip 压缩后发送(需要重新判断 fileType,因为 loader 可能修改了它)
254
+ if (shouldGzip && compressibleTypes.has(fileType)) {
255
+ responseHeader['Content-Encoding'] = 'gzip';
256
+ body = gzipSync(Buffer.from(body));
257
+ }
258
+
194
259
  response.writeHead(200, responseHeader);
195
- response.write(isXHR ? source : resolveImport(source, fileType !== "application/javascript"));
260
+ response.write(body);
196
261
  response.end();
197
262
  }
198
263
 
@@ -200,19 +265,26 @@ module.exports = function (config) {
200
265
  else {
201
266
  sendType = "Stream";
202
267
 
203
- responseHeader['Content-Length'] = fileInfo.size
268
+ if (shouldGzip) {
269
+ // gzip 流式压缩:文件大小变化,不能设置 Content-Length
270
+ responseHeader['Content-Encoding'] = 'gzip';
271
+ response.writeHead(200, responseHeader);
272
+ createReadStream(filePath).pipe(createGzip()).pipe(response);
273
+ } else {
274
+ responseHeader['Content-Length'] = fileInfo.size
204
275
 
205
- response.writeHead(200, responseHeader);
206
- createReadStream(filePath).pipe(response);
276
+ response.writeHead(200, responseHeader);
277
+ createReadStream(filePath).pipe(response);
278
+ }
207
279
  }
208
280
 
209
- console.log("<i> \x1b[1m\x1b[32m[" + name + "] " + sendType + " File: " + url + '\x1b[0m ' + new Date().toLocaleString() + "\x1b[33m\x1b[1m" + (isXHR ? " " + request.method : "") + "\x1b[0m " + rawIp);
281
+ console.log("<i> \x1b[1m\x1b[32m[" + name + "] " + sendType + " File: " + url + '\x1b[0m ' + new Date().toLocaleString() + (shouldGzip ? " \x1b[33m\x1b[1mgzip\x1b[0m" : "") + (isXHR ? " \x1b[33m\x1b[1m" + request.method + "\x1b[0m" : "") + " " + rawIp);
210
282
  }
211
283
 
212
284
  // 否则就是404
213
285
  else {
214
286
  response.writeHead(404, {
215
- 'Content-Type': "text/html;charset=utf-8",
287
+ 'Content-Type': buildContentType("text/html"),
216
288
  'Access-Control-Allow-Origin': '*',
217
289
  'Server': 'Powered by ' + name + '@' + version
218
290
  });
@@ -242,5 +314,6 @@ module.exports = function (config) {
242
314
  }
243
315
 
244
316
  if (!cache) console.log('<i> \x1b[1m\x1b[32m[' + name + '] Cancel 304 Cache!\x1b[0m');
317
+ if (gzip) console.log('<i> \x1b[1m\x1b[32m[' + name + '] Gzip Compression: \x1b[36menabled\x1b[0m');
245
318
  console.log('\n' + (config.name || "OIPage") + ' ' + version + ' compiled \x1b[1m\x1b[32msuccessfully\x1b[0m in ' + (new Date().valueOf() - startTime) + ' ms\n');
246
319
  };
@@ -0,0 +1,83 @@
1
+ const { openSync, readSync, closeSync } = require("fs");
2
+ const mineTypes = require("../data/mineTypes.json");
3
+
4
+ // 读取文件头部用于判断的字节数
5
+ const CHECK_BYTES = 4096;
6
+
7
+ // 文本类型白名单(即使 Content-Type 是 application/* 也视为文本)
8
+ // 仅在文件内容读取失败时作为回退判断依据
9
+ const TEXT_TYPES = new Set([
10
+ "application/javascript",
11
+ "application/json",
12
+ "application/xml",
13
+ "application/xhtml+xml",
14
+ "application/rss+xml",
15
+ "application/atom+xml",
16
+ "image/svg+xml",
17
+ "application/xspf+xml",
18
+ "application/vnd.google-earth.kml+xml"
19
+ ]);
20
+
21
+ /**
22
+ * 通过后缀名回退判断(仅在文件内容读取失败时使用)
23
+ * @param {string} filepath 文件路径
24
+ * @returns {boolean} 是否为二进制文件
25
+ */
26
+ function isBinaryByExtension(filepath) {
27
+ const dotName = (filepath.match(/\.([^.]+)$/) || [])[1] || "";
28
+ const fileType = mineTypes[dotName];
29
+
30
+ if (!fileType) {
31
+ // 未知类型默认视为二进制
32
+ return true;
33
+ }
34
+
35
+ if (fileType.startsWith("text/")) {
36
+ return false;
37
+ }
38
+
39
+ if (TEXT_TYPES.has(fileType)) {
40
+ return false;
41
+ }
42
+
43
+ return true;
44
+ }
45
+
46
+ /**
47
+ * 判断文件是否是二进制文件
48
+ * 通过读取文件前若干字节,检查是否包含 NULL 字节(\0)来判断
49
+ * 文本文件(UTF-8/ASCII)通常不包含 NULL 字节,而二进制文件通常包含
50
+ * 如果文件读取失败,回退到后缀名判断
51
+ * @param {string} filepath 文件路径
52
+ * @returns {boolean} 是否为二进制文件
53
+ */
54
+ module.exports = function isBinary(filepath) {
55
+ let fd;
56
+ try {
57
+ fd = openSync(filepath, 'r');
58
+ const buffer = Buffer.alloc(CHECK_BYTES);
59
+ const bytesRead = readSync(fd, buffer, 0, CHECK_BYTES, 0);
60
+
61
+ // 检查是否包含 NULL 字节
62
+ // NULL 字节是二进制文件的可靠标志,文本文件(UTF-8/ASCII)不会包含
63
+ for (let i = 0; i < bytesRead; i++) {
64
+ if (buffer[i] === 0) {
65
+ return true;
66
+ }
67
+ }
68
+
69
+ return false;
70
+ } catch (e) {
71
+ // 文件读取失败时,回退到后缀名判断
72
+ console.log(e);
73
+ return isBinaryByExtension(filepath);
74
+ } finally {
75
+ if (fd !== undefined) {
76
+ try {
77
+ closeSync(fd);
78
+ } catch (e) {
79
+ // 关闭失败不影响判断结果
80
+ }
81
+ }
82
+ }
83
+ };
@@ -1,11 +1,11 @@
1
- const { readFileSync, existsSync, lstatSync } = require("fs");
1
+ const { readFileSync, existsSync, statSync } = require("fs");
2
2
  const { join } = require("path");
3
3
  const { testIntercept } = require("../intercept.js");
4
4
 
5
5
  module.exports = function (basePath, filePath, entry, intercept, isDownload, isWebsite) {
6
6
  basePath = join(basePath, "./");
7
7
 
8
- if (lstatSync(filePath).isDirectory()) { return { source: "", resolveImport: content => content }; }
8
+ if (statSync(filePath).isDirectory()) { return { source: "", resolveImport: content => content }; }
9
9
  let source = readFileSync(filePath);
10
10
  let resolveImport = content => content;
11
11
 
@@ -26,12 +26,16 @@ module.exports = function (basePath, filePath, entry, intercept, isDownload, isW
26
26
  let npmBundlePath = join(node_modulesRootPath, "./node_modules/", npmName);
27
27
 
28
28
  // 如果存在
29
- if (existsSync(npmBundlePath) && lstatSync(npmBundlePath).isDirectory()) {
29
+ if (existsSync(npmBundlePath) && statSync(npmBundlePath).isDirectory()) {
30
30
  let npmNameValue = npmName;
31
31
 
32
32
  // 对于类似 import VISLite from "vislite"
33
33
  // 需要把包名解析成具体的文件
34
- if (!/\//.test(_importUrl)) {
34
+ if (!/\//.test(_importUrl
35
+
36
+ // 兼容 "@oipage/browser.js" 类似的包
37
+ // 2026年09月11日 于南宁
38
+ .replace(/@[^/]+\//, ""))) {
35
39
  let bundlePackage = require(join(npmBundlePath, "./package.json"));
36
40
  npmNameValue = npmName + "/" + bundlePackage.main;
37
41
  }
@@ -43,7 +47,10 @@ module.exports = function (basePath, filePath, entry, intercept, isDownload, isW
43
47
 
44
48
  // 如果命令行根目录是一个项目
45
49
  let packagePath = join(basePath, "./package.json");
46
- if (existsSync(packagePath) && !lstatSync(packagePath).isDirectory()) {
50
+
51
+ // statSync代替lstatSync,修复符号链接指向文件夹时无法正确判断文件
52
+ // 2026年09月10日 于南宁
53
+ if (existsSync(packagePath) && !statSync(packagePath).isDirectory()) {
47
54
  let bundlePackage = require(packagePath);
48
55
  if (!/\//.test(_importUrl)) {
49
56
  return "/" + bundlePackage.main;
package/docs/config.md CHANGED
@@ -18,6 +18,28 @@
18
18
 
19
19
  是否开启304缓存,默认true,表示开启。
20
20
 
21
+ ### gzip
22
+
23
+ > 始于 v0.3.0
24
+
25
+ 是否开启 gzip 压缩,默认true,表示开启。
26
+
27
+ 开启后,服务器会对支持 gzip 的客户端请求,自动压缩可压缩类型的文本资源(如 HTML、CSS、JS、JSON、SVG 等),可以有效减少传输体积,加快页面加载速度。
28
+
29
+ 使用 Node.js 内置 `zlib` 模块实现,无需安装额外依赖。可通过命令行参数控制:
30
+
31
+ ```shell
32
+ oipage-cli serve --gzip true
33
+ ```
34
+
35
+ 或在配置文件中开启:
36
+
37
+ ```js
38
+ devServer: {
39
+ gzip: true
40
+ }
41
+ ```
42
+
21
43
  ### port
22
44
 
23
45
  端口,默认8080。此外,可以在执行的时候,通过命令参数覆盖(下同):
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@oipage/cli",
3
- "version": "0.3.0-alpha.2",
3
+ "version": "0.3.0-alpha.4",
4
4
  "description": "开发快速助手,一个包含常用功能的命令行工具,旨在提升开发效率",
5
5
  "sideEffects": false,
6
6
  "main": "./src/index.js",
7
7
  "typings": "./types/index.d.ts",
8
8
  "scripts": {
9
- "serve": "node ./bin/run serve --config ./oipage.config.js --open -p 20000"
9
+ "serve": "node ./bin/run serve --config ./oipage.config.js"
10
10
  },
11
11
  "bin": {
12
12
  "oipage-cli": "bin/run"
package/src/index.js CHANGED
@@ -8,6 +8,7 @@ exports.serve = function (config) {
8
8
  baseUrl: "./",
9
9
  open: false,
10
10
  cache: true,
11
+ gzip: true,
11
12
  proxy: {},
12
13
  intercept: [],
13
14
  404: null,
package/types/serve.d.ts CHANGED
@@ -23,6 +23,13 @@ interface DevServerType {
23
23
  */
24
24
  cache: boolean
25
25
 
26
+ /**
27
+ * 是否开启 gzip 压缩,默认不开启
28
+ *
29
+ * 开启后,对支持 gzip 的客户端请求,自动压缩可压缩类型的文本资源(如 HTML、CSS、JS、JSON、SVG 等)
30
+ */
31
+ gzip?: boolean
32
+
26
33
  /**
27
34
  * 是否开启应用市场,默认true表示开启
28
35
  */