@oipage/cli 0.3.0 → 1.0.0-alpha.1

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.
Files changed (92) hide show
  1. package/.github/FUNDING.yml +11 -11
  2. package/AUTHORS.txt +6 -6
  3. package/CHANGELOG +76 -47
  4. package/LICENSE +20 -20
  5. package/README.md +204 -132
  6. package/bin/WebSocket/decodeWsFrame.js +43 -43
  7. package/bin/WebSocket/encodeWsFrame.js +28 -28
  8. package/bin/WebSocket/headersToJSON.js +26 -26
  9. package/bin/WebSocket/index.js +106 -106
  10. package/bin/data/{mineTypes.json → mimeTypes.json} +108 -104
  11. package/bin/disk.js +42 -42
  12. package/bin/help.js +63 -55
  13. package/bin/intercept.js +15 -15
  14. package/bin/network.js +21 -21
  15. package/bin/notebook/data.js +185 -0
  16. package/bin/notebook/index.js +168 -9
  17. package/bin/proxy.js +82 -82
  18. package/bin/run +146 -146
  19. package/bin/serve.js +455 -318
  20. package/bin/template/404.html +184 -184
  21. package/bin/tools/deleteEmptyFolder.js +33 -33
  22. package/bin/tools/format.js +75 -75
  23. package/bin/tools/isBinary.js +83 -83
  24. package/bin/tools/moduleForm.js +548 -0
  25. package/bin/tools/network.js +42 -42
  26. package/bin/tools/openBrowser.js +34 -34
  27. package/bin/tools/resolve404.js +98 -98
  28. package/bin/tools/resolveImport.js +278 -97
  29. package/bin/tools/resolvePackage.js +412 -0
  30. package/bin/website-htmls/components/ui-select-file/index.html +8 -8
  31. package/bin/website-htmls/components/ui-select-file/index.js +42 -42
  32. package/bin/website-htmls/components/ui-select-file/index.scss +44 -44
  33. package/bin/website-htmls/dialogs/imageSize/index.html +54 -54
  34. package/bin/website-htmls/dialogs/imageSize/index.js +53 -53
  35. package/bin/website-htmls/dialogs/imageSize/index.scss +140 -140
  36. package/bin/website-htmls/dialogs/index.js +52 -52
  37. package/bin/website-htmls/images/addFile.svg +1 -1
  38. package/bin/website-htmls/images/img-to-pdf.svg +1 -1
  39. package/bin/website-htmls/index.html +17 -17
  40. package/bin/website-htmls/main.js +13 -13
  41. package/bin/website-htmls/pages/App/index.html +6 -6
  42. package/bin/website-htmls/pages/App/index.js +22 -22
  43. package/bin/website-htmls/pages/App/index.scss +43 -43
  44. package/bin/website-htmls/pages/appStore/index.html +7 -7
  45. package/bin/website-htmls/pages/appStore/index.js +19 -19
  46. package/bin/website-htmls/pages/appStore/index.scss +54 -54
  47. package/bin/website-htmls/pages/chart/index.html +8 -8
  48. package/bin/website-htmls/pages/chart/index.js +72 -72
  49. package/bin/website-htmls/pages/chart/index.scss +71 -71
  50. package/bin/website-htmls/pages/home/index.html +19 -19
  51. package/bin/website-htmls/pages/home/index.js +19 -19
  52. package/bin/website-htmls/pages/home/index.scss +87 -87
  53. package/bin/website-htmls/pages/image-editor/index.html +27 -27
  54. package/bin/website-htmls/pages/image-editor/index.js +106 -106
  55. package/bin/website-htmls/pages/image-editor/index.scss +69 -69
  56. package/bin/website-htmls/pages/img-to-pdf/index.html +3 -3
  57. package/bin/website-htmls/pages/img-to-pdf/index.js +44 -44
  58. package/bin/website-htmls/pages/img-to-pdf/index.scss +9 -9
  59. package/bin/website-htmls/pages/recorder-screen/index.html +15 -15
  60. package/bin/website-htmls/pages/recorder-screen/index.js +227 -227
  61. package/bin/website-htmls/pages/recorder-screen/index.scss +52 -52
  62. package/bin/website-htmls/router.config.js +29 -29
  63. package/bin/website-htmls/styles/common.css +44 -44
  64. package/bin/website-htmls/styles/normalize.css +94 -94
  65. package/bin/website-plugins/intercept/chart.js +33 -33
  66. package/bin/website-plugins/intercept/getPackage.js +17 -17
  67. package/bin/website-plugins/intercept/head.js +8 -8
  68. package/bin/website-plugins/intercept/index.js +4 -8
  69. package/bin/website-plugins/loader/index.js +11 -11
  70. package/bin/website-plugins/loader/oipage-html-loader.js +7 -7
  71. package/bin/website-plugins/loader/oipage-scss-loader.js +149 -149
  72. package/docs/css/base.css +122 -0
  73. package/docs/css/components.css +180 -0
  74. package/docs/css/layout.css +295 -0
  75. package/docs/css/responsive.css +49 -0
  76. package/docs/images/file-list.webp +0 -0
  77. package/docs/images/logo-topbar.svg +5 -0
  78. package/docs/images/logo.png +0 -0
  79. package/docs/images/logo.svg +6 -0
  80. package/docs/images/manual.webp +0 -0
  81. package/docs/images/terminal-serve.webp +0 -0
  82. package/docs/index.html +1392 -0
  83. package/docs/js/copy.js +37 -0
  84. package/docs/js/nav.js +111 -0
  85. package/docs/js/search.js +241 -0
  86. package/docs/js/theme.js +17 -0
  87. package/package.json +42 -42
  88. package/src/index.js +26 -29
  89. package/types/serve.d.ts +83 -83
  90. package/bin/website-plugins/intercept/oipage-vislite-intercept.js +0 -56
  91. package/bin/website-plugins/intercept/oipage-zipaper-intercept.js +0 -37
  92. package/docs/config.md +0 -107
package/bin/serve.js CHANGED
@@ -1,319 +1,456 @@
1
- const { join, resolve, sep } = require("path");
2
- const { existsSync, lstatSync, statSync, createReadStream } = require("fs");
3
- const { createServer } = require('http');
4
- const { gzipSync, createGzip } = require("zlib");
5
- const packageValue = require("../package.json");
6
- const network = require("./tools/network.js");
7
- const mineTypes = require("./data/mineTypes.json");
8
- const resolveImportFactory = require("./tools/resolveImport.js");
9
- const openBrowser = require("./tools/openBrowser.js");
10
- const { doIntercept } = require("./intercept.js");
11
- const proxy = require("./proxy.js");
12
- const resolve404_default = require("./tools/resolve404.js");
13
- const isBinary = require("./tools/isBinary.js");
14
- const websiteIntercept = require("./website-plugins/intercept/index.js");
15
- const websiteLoader = require("./website-plugins/loader/index.js");
16
-
17
- const WebSocketClass = require("./WebSocket/index.js");
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
-
58
- // 开发服务器
59
- module.exports = function (config) {
60
- let startTime = new Date().valueOf();
61
-
62
- const resolve404 = config.devServer["404"] || resolve404_default;
63
- const cache = "cache" in config.devServer ? config.devServer.cache : true;
64
- const website = "website" in config.devServer ? config.devServer.website : true;
65
- const gzip = "gzip" in config.devServer ? config.devServer.gzip : false;
66
- const port = +config.devServer.port; // 端口号
67
- const basePath = resolve((/^\./.test(config.devServer.baseUrl)) ? join(process.cwd(), config.devServer.baseUrl) : config.devServer.baseUrl); // 服务器根路径
68
-
69
- const name = (config.name || "OIPage") + "-http-server";
70
- const version = config.version || packageValue.version;
71
-
72
- const wsHandler = WebSocketClass(port + 1, (config.name || "OIPage") + "-ws-server", version, website);
73
-
74
- // 全局错误捕获,防止服务器因任何未捕获的错误而停机
75
- // 2026年8月8日 于南宁
76
- process.on('uncaughtException', function (err) {
77
- console.log("<i> \x1b[1m\x1b[31m[" + name + "] uncaughtException: " + err.message + "\x1b[0m " + new Date().toLocaleString());
78
- console.log(err.stack);
79
- });
80
- process.on('unhandledRejection', function (reason) {
81
- console.log("<i> \x1b[1m\x1b[31m[" + name + "] unhandledRejection: " + (reason && reason.message || reason) + "\x1b[0m " + new Date().toLocaleString());
82
- });
83
-
84
- let Server = createServer(function (request, response) {
85
- let headers = request.headers;
86
-
87
- const rawIp = (request.socket.remoteAddress || '').replace(/^::ffff:/, "").replace(/^::1/, "127.0.0.1");
88
-
89
- let url;
90
- try {
91
-
92
- // 上游网关二次解码的架构层面风险(%252e 双重编码),导致文件路径被二次解码,导致路径穿越漏洞
93
- // 后续处理中,对url不要再decodeURIComponent进行解码,防止路径穿越漏洞
94
- // 2026年8月9日 于南宁
95
- url = decodeURIComponent(request.url);
96
- } catch (e) {
97
-
98
- // 如果 URL 包含无效的百分号编码(如 %ZZ),decodeURIComponent 会抛出 URIError
99
- // 虽然被 uncaughtException 捕获,但会导致当前请求处理中断且无响应返回,客户端会挂起等待
100
- // 2026年8月9日 于南宁
101
- response.writeHead(400, {
102
- 'Content-Type': buildContentType('text/plain'),
103
- 'Access-Control-Allow-Origin': '*',
104
- 'Server': 'Powered by ' + name + '@' + version
105
- });
106
- response.end('Bad Request');
107
- return;
108
- }
109
-
110
- let urlArray = url.split("?");
111
- url = urlArray[0];
112
-
113
- // 请求的文件路径
114
- let filePath;
115
-
116
- let isWebsite = website && /^\/@website\//.test(url);
117
- if (isWebsite) {
118
- filePath = join(__dirname, "./website-htmls/", url.replace(/^\/@website\//, ""));
119
- } else {
120
- filePath = join(basePath, url == "/" ? "index.html" : url.replace(/^\//, ""));
121
- }
122
-
123
- filePath = resolve(filePath);
124
-
125
- let proxyIntercept = proxy({
126
- name,
127
- version
128
- }, config.devServer.proxy || {});
129
- delete config.devServer.proxy;
130
- for (let i = 0; i < proxyIntercept.length; i++) {
131
- config.devServer.intercept.push(proxyIntercept[i]);
132
- }
133
-
134
- // 请求拦截
135
- if (doIntercept(url.replace(/^\/@website/, "").replace(/^\/@modules\//, ""), isWebsite ? websiteIntercept : config.devServer.intercept, request, response, wsHandler)) {
136
- console.log("<i> \x1b[1m\x1b[32m[" + name + "] intercept: " + url + '\x1b[0m ' + new Date().toLocaleString() + " " + rawIp);
137
- } else {
138
-
139
- // 对应前置都没有找到的,默认去当前命令行找
140
- // 2026年4月13日 于南京
141
- if (/^\/@modules\//.test(url)) {
142
- filePath = join(process.cwd(), url.replace(/^\/@modules\//, "node_modules/"))
143
- }
144
-
145
- // 禁止访问沙箱外文件,路径穿越拦截
146
- // 2026年8月8日 于南宁
147
- if ((!(filePath.startsWith(basePath + sep) || filePath === basePath) &&
148
- !(filePath.startsWith(process.cwd() + sep) || filePath === process.cwd())
149
- ) || filePath.includes('\0')) {
150
- response.writeHead(403, {
151
- 'Content-Type': buildContentType("text/plain"),
152
- 'Access-Control-Allow-Origin': '*',
153
- 'Server': 'Powered by ' + name + '@' + version
154
- });
155
- response.write("Path Traversal attack");
156
- response.end();
157
- console.log("<i> \x1b[1m\x1b[31m[" + name + "] Path Traversal attack, path: " + url + "\x1b[0m " + new Date().toLocaleString() + " " + rawIp);
158
- return;
159
- }
160
-
161
- // 如果存在且是文件
162
- if (existsSync(filePath) && !lstatSync(filePath).isDirectory()) {
163
-
164
- // 判断是否是请求而无需进一步解析
165
- // 2025年12月5日 于南京
166
- let isXHR = headers["sec-fetch-dest"] === "empty";
167
-
168
- let dotName = (filePath.match(/\.([^.]+)$/) || [])[1] || "";
169
- let fileType = mineTypes[dotName]; // 文件类型
170
- let fileInfo = statSync(filePath);
171
-
172
- let fileModifiedTime = new Date(fileInfo.mtime).toGMTString();
173
-
174
- let responseHeader = {
175
- 'Content-Type': buildContentType(fileType || "text/plain"),
176
- 'Access-Control-Allow-Origin': '*',
177
- 'Server': 'Powered by ' + name + '@' + version,
178
- 'Cache-Control': 'no-cache',
179
- // 'Content-Length': fileInfo.size, // 会导致拦截修改的文本内容不对
180
-
181
- // 与if-modified-since配合使用,做缓存验证
182
- 'Last-Modified': fileModifiedTime,
183
-
184
- // 与if-none-match配合使用,做缓存验证
185
- // ETag 包含 gzip 标志,确保 gzip 配置变化时缓存正确失效
186
- 'ETag': '"' + fileInfo.mtime.getTime() + (gzip ? '-gz' : '') + '"',
187
-
188
- // 告知代理/缓存:响应内容会根据 Accept-Encoding 不同而变化
189
- 'Vary': 'Accept-Encoding'
190
- };
191
-
192
- if (cache && headers["if-modified-since"]) {
193
- let ifModifiedSince = new Date(headers["if-modified-since"]).valueOf()
194
- let lastModified = new Date(fileModifiedTime).valueOf()
195
-
196
- // 注意这里不能使用<=,否则
197
- // 1、会出现时区问题
198
- // 2、作为开发服务器,可能同一个url地址对应的文件不同,被误判为未修改
199
- // 2025年12月29日 于南京
200
- // 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) {
208
- response.writeHead(304, responseHeader);
209
- response.end();
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);
211
- return;
212
- }
213
- }
214
-
215
- let sendType = "";
216
- let entry = headers.accept !== "*/*";
217
-
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)) {
225
- let { source, resolveImport } = resolveImportFactory(basePath, filePath, entry, isWebsite ? websiteIntercept : config.devServer.intercept, urlArray[1] === "download", isWebsite)
226
-
227
- // 只处理非下载文件
228
- // 过大的也不进行处理
229
- // (对website无效)
230
- if (urlArray[1] !== "download") {
231
- let loaders = isWebsite ? websiteLoader : config.module;
232
-
233
- for (let i = 0; i < loaders.rules.length; i++) {
234
- if (loaders.rules[i].test.test(filePath)) {
235
- source = loaders.rules[i].use.call({
236
- root: basePath, // 服务器根路径
237
- path: filePath.replace(basePath, ""), // 文件相对路径
238
- entry, // 是否是浏览器地址栏直接访问
239
- setFileType(_fileType) { // 设置文件类型
240
- fileType = _fileType;
241
- responseHeader['Content-Type'] = buildContentType(_fileType);
242
- }
243
- }, source);
244
- break;
245
- }
246
- }
247
-
248
- }
249
-
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
-
259
- response.writeHead(200, responseHeader);
260
- response.write(body);
261
- response.end();
262
- }
263
-
264
- // 对于大文件,使用流读取
265
- else {
266
- sendType = "Stream";
267
-
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
275
-
276
- response.writeHead(200, responseHeader);
277
- createReadStream(filePath).pipe(response);
278
- }
279
- }
280
-
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);
282
- }
283
-
284
- // 否则就是404
285
- else {
286
- response.writeHead(404, {
287
- 'Content-Type': buildContentType("text/html"),
288
- 'Access-Control-Allow-Origin': '*',
289
- 'Server': 'Powered by ' + name + '@' + version
290
- });
291
- response.write(resolve404(filePath, url, website, config.name || "OIPage", rawIp));
292
- response.end();
293
- }
294
- }
295
-
296
- });
297
-
298
- Server.listen(port);
299
-
300
- // 获取网络信息
301
- let networkValue = network();
302
-
303
- // 打印成功提示
304
- console.log('<i> \x1b[1m\x1b[32m[' + name + '] Project is running at:\x1b[0m');
305
- console.log('<i> \x1b[1m\x1b[32m[' + name + '] Loopback: \x1b[36mhttp://localhost:' + port + '/\x1b[0m');
306
- for (let ipv4Item of networkValue.IPv4) console.log('<i> \x1b[1m\x1b[32m[' + name + '] On Your Network (IPv4):\x1b[36m http://' + ipv4Item.address + ':' + port + '/\x1b[0m');
307
- for (let ipv6Item of networkValue.IPv6) console.log('<i> \x1b[1m\x1b[32m[' + name + '] On Your Network (IPv6): \x1b[36mhttp://[' + ipv6Item.address + ']:' + port + '/\x1b[0m');
308
- console.log('<i> \x1b[1m\x1b[32m[' + name + '] Content not from ' + (config.name || "OIPage") + ' is served from \x1b[36m"' + basePath + '" \x1b[0mdirectory');
309
-
310
- if (typeof config.devServer.open === "string" || config.devServer.open) {
311
- let url = 'http://localhost:' + port + "/" + (typeof config.devServer.open === "string" ? config.devServer.open : "");
312
- openBrowser(url);
313
- console.log('<i> \x1b[1m\x1b[32m[' + name + '] Open: \x1b[36m' + url + '\x1b[0m');
314
- }
315
-
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');
318
- console.log('\n' + (config.name || "OIPage") + ' ' + version + ' compiled \x1b[1m\x1b[32msuccessfully\x1b[0m in ' + (new Date().valueOf() - startTime) + ' ms\n');
1
+ const { join, resolve, sep } = require("path");
2
+ const { existsSync, statSync, createReadStream, readFileSync } = require("fs");
3
+ const { createServer } = require('http');
4
+ const { gzipSync, createGzip } = require("zlib");
5
+ const packageValue = require("../package.json");
6
+ const network = require("./tools/network.js");
7
+ const mimeTypes = require("./data/mimeTypes.json");
8
+ const resolveImportFactory = require("./tools/resolveImport.js");
9
+ const { replaceInCode } = require("./tools/moduleForm.js");
10
+ const openBrowser = require("./tools/openBrowser.js");
11
+ const { doIntercept } = require("./intercept.js");
12
+ const proxy = require("./proxy.js");
13
+ const resolve404_default = require("./tools/resolve404.js");
14
+ const isBinary = require("./tools/isBinary.js");
15
+ const websiteIntercept = require("./website-plugins/intercept/index.js");
16
+ const websiteLoader = require("./website-plugins/loader/index.js");
17
+
18
+ const WebSocketClass = require("./WebSocket/index.js");
19
+
20
+ // 可压缩的 MIME 类型集合(文本类资源,压缩收益大)
21
+ const compressibleTypes = new Set([
22
+ "text/html", "text/css", "text/plain", "text/xml", "text/mathml",
23
+ "text/vnd.sun.j2me.app-descriptor", "text/vnd.wap.wml", "text/x-component",
24
+ "application/javascript", "application/json", "application/xml",
25
+ "application/xhtml+xml", "application/atom+xml", "application/rss+xml",
26
+ "application/xspf+xml", "application/x-tcl", "application/x-perl",
27
+ "image/svg+xml"
28
+ ]);
29
+
30
+ // 需要设置 charset 的 MIME 类型前缀/精确匹配集合
31
+ // 文本类资源需要 charset 告知浏览器字符编码,二进制资源不需要
32
+ const charsetPrefixes = ["text/"];
33
+ const charsetTypes = new Set([
34
+ "application/javascript", "application/json", "application/xml",
35
+ "application/xhtml+xml", "application/atom+xml", "application/rss+xml",
36
+ "application/xspf+xml", "application/x-tcl", "application/x-perl",
37
+ "application/rtf", "application/postscript",
38
+ "application/vnd.google-earth.kml+xml", "application/x-javascript",
39
+ "image/svg+xml"
40
+ ]);
41
+
42
+ /**
43
+ * 根据 MIME 类型构建 Content-Type 值
44
+ * 文本类型追加 charset=utf-8,二进制类型不追加
45
+ * @param {string} mimeType MIME 类型
46
+ * @returns {string} 完整的 Content-Type 值
47
+ */
48
+ function buildContentType(mimeType) {
49
+ if (!mimeType) return "text/plain;charset=utf-8";
50
+ if (charsetPrefixes.some(prefix => mimeType.startsWith(prefix))) {
51
+ return mimeType + ";charset=utf-8";
52
+ }
53
+ if (charsetTypes.has(mimeType)) {
54
+ return mimeType + ";charset=utf-8";
55
+ }
56
+ return mimeType;
57
+ }
58
+
59
+ // 开发服务器
60
+ module.exports = function (config) {
61
+ let startTime = new Date().valueOf();
62
+
63
+ const resolve404 = config.devServer["404"] || resolve404_default;
64
+ const cache = "cache" in config.devServer ? config.devServer.cache : true;
65
+ const website = "website" in config.devServer ? config.devServer.website : true;
66
+ const gzip = "gzip" in config.devServer ? config.devServer.gzip : false;
67
+ const port = +config.devServer.port; // 端口号
68
+ const basePath = resolve((/^\./.test(config.devServer.baseUrl)) ? join(process.cwd(), config.devServer.baseUrl) : config.devServer.baseUrl); // 服务器根路径
69
+
70
+ // 允许访问的根目录:服务器根目录、命令行当前目录、命令行工具自身的 node_modules
71
+ const cliRoot = resolve(__dirname, "..");
72
+ const cliModules = join(cliRoot, "node_modules");
73
+
74
+ // /@modules/ 的候选根目录(先工程,再命令行工具自身,保证内置网站能拿到自带依赖)
75
+ const moduleRoots = [join(process.cwd(), "node_modules"), cliModules];
76
+
77
+ // 模块导出条件(对齐打包器的默认顺序)
78
+ const conditions = Array.isArray(config.devServer.conditions) && config.devServer.conditions.length
79
+ ? config.devServer.conditions
80
+ : ["browser", "import", "default"];
81
+
82
+ // 类似 webpack DefinePlugin 的文本替换,false 表示关闭
83
+ const define = config.devServer.define === false ? {} : Object.assign({
84
+ "process.env.NODE_ENV": "\"development\""
85
+ }, config.devServer.define || {});
86
+
87
+ // 只在代码区替换,不误伤字符串与注释
88
+ const applyDefine = content => {
89
+ const keys = Object.keys(define);
90
+ if (!keys.length) return content;
91
+
92
+ let result = content;
93
+ for (const key of keys) result = replaceInCode(result, key, define[key] + "");
94
+ return result;
95
+ };
96
+
97
+ resolveImportFactory.configure({ conditions });
98
+
99
+ const name = (config.name || "OIPage") + "-http-server";
100
+ const version = config.version || packageValue.version;
101
+
102
+ const wsHandler = WebSocketClass(port + 1, (config.name || "OIPage") + "-ws-server", version, website);
103
+
104
+ // 全局错误捕获,防止服务器因任何未捕获的错误而停机
105
+ // 2026年8月8日 于南宁
106
+ process.on('uncaughtException', function (err) {
107
+ console.log("\x1b[1m\x1b[31m[" + name + "] uncaughtException: " + err.message + "\x1b[0m " + new Date().toLocaleString());
108
+ console.log(err.stack);
109
+ });
110
+ process.on('unhandledRejection', function (reason) {
111
+ console.log("\x1b[1m\x1b[31m[" + name + "] unhandledRejection: " + (reason && reason.message || reason) + "\x1b[0m " + new Date().toLocaleString());
112
+ });
113
+
114
+ let Server = createServer(function (request, response) {
115
+ let headers = request.headers;
116
+
117
+ const rawIp = (request.socket.remoteAddress || '').replace(/^::ffff:/, "").replace(/^::1/, "127.0.0.1");
118
+
119
+ let url;
120
+ try {
121
+
122
+ // 上游网关二次解码的架构层面风险(%252e 双重编码),导致文件路径被二次解码,导致路径穿越漏洞
123
+ // 后续处理中,对url不要再decodeURIComponent进行解码,防止路径穿越漏洞
124
+ // 2026年8月9日 于南宁
125
+ url = decodeURIComponent(request.url);
126
+ } catch (e) {
127
+
128
+ // 如果 URL 包含无效的百分号编码(如 %ZZ),decodeURIComponent 会抛出 URIError
129
+ // 虽然被 uncaughtException 捕获,但会导致当前请求处理中断且无响应返回,客户端会挂起等待
130
+ // 2026年8月9日 于南宁
131
+ response.writeHead(400, {
132
+ 'Content-Type': buildContentType('text/plain'),
133
+ 'Access-Control-Allow-Origin': '*',
134
+ 'Server': 'Powered by ' + name + '@' + version
135
+ });
136
+ response.end('Bad Request');
137
+ return;
138
+ }
139
+
140
+ let urlArray = url.split("?");
141
+ url = urlArray[0];
142
+
143
+ // 查询串:CJS 门面标记、下载标记等都走这里
144
+ const query = urlArray.slice(1).join("?");
145
+
146
+ // 请求的文件路径
147
+ let filePath;
148
+
149
+ let isWebsite = website && /^\/@website\//.test(url);
150
+ if (isWebsite) {
151
+ filePath = join(__dirname, "./website-htmls/", url.replace(/^\/@website\//, ""));
152
+ } else {
153
+ filePath = join(basePath, url == "/" ? "index.html" : url.replace(/^\//, ""));
154
+ }
155
+
156
+ filePath = resolve(filePath);
157
+
158
+ let proxyIntercept = proxy({
159
+ name,
160
+ version
161
+ }, config.devServer.proxy || {});
162
+ delete config.devServer.proxy;
163
+ for (let i = 0; i < proxyIntercept.length; i++) {
164
+ config.devServer.intercept.push(proxyIntercept[i]);
165
+ }
166
+
167
+ // 请求拦截
168
+ if (doIntercept(url.replace(/^\/@website/, "").replace(/^\/@modules\//, ""), isWebsite ? websiteIntercept : config.devServer.intercept, request, response, wsHandler)) {
169
+ console.log("\x1b[1m\x1b[32m[" + name + "] intercept: " + url + '\x1b[0m ' + new Date().toLocaleString() + " " + rawIp);
170
+ } else {
171
+
172
+ // 对应前置都没有找到的,默认去 node_modules 里找
173
+ // 默认先找命令行当前目录,再找命令行工具自身
174
+ // 带 oipage=cli 标记时反过来:内置网站的依赖必须取命令行工具自带的那一份
175
+ // 2026年4月13日 于南京 / 2026年11月25日 于南京
176
+ if (/^\/@modules\//.test(url)) {
177
+ const modulePath = url.replace(/^\/@modules\//, "");
178
+ const preferCliModule = /(^|&)oipage=cli($|&)/.test(query);
179
+ const roots = preferCliModule ? [cliModules].concat(moduleRoots) : moduleRoots;
180
+
181
+ filePath = null;
182
+ for (const root of roots) {
183
+ const candidate = resolve(join(root, modulePath));
184
+ if (existsSync(candidate)) {
185
+ filePath = candidate;
186
+ break;
187
+ }
188
+ }
189
+
190
+ // 都没找到时保留一个候选,交给后面的 404 逻辑
191
+ if (!filePath) filePath = resolve(join(roots[0], modulePath));
192
+ }
193
+
194
+ // 禁止访问沙箱外文件,路径穿越拦截
195
+ // 2026年8月8日 于南宁
196
+ const allowedRoots = [basePath, process.cwd(), cliModules];
197
+ const isAllowed = allowedRoots.some(root => filePath === root || filePath.startsWith(root + sep));
198
+
199
+ if (!isAllowed || filePath.includes('\0')) {
200
+ response.writeHead(403, {
201
+ 'Content-Type': buildContentType("text/plain"),
202
+ 'Access-Control-Allow-Origin': '*',
203
+ 'Server': 'Powered by ' + name + '@' + version
204
+ });
205
+ response.write("Path Traversal attack");
206
+ response.end();
207
+ console.log("\x1b[1m\x1b[31m[" + name + "] Path Traversal attack, path: " + url + "\x1b[0m " + new Date().toLocaleString() + " " + rawIp);
208
+ return;
209
+ }
210
+
211
+ // 目录请求:先尝试目录下的 index,再走 404(不能直接按文件流读取)
212
+ // 2026年11月25日 于南京
213
+ let fileStat = existsSync(filePath) ? statSync(filePath) : null;
214
+
215
+ if (fileStat && fileStat.isDirectory()) {
216
+ let indexFile = null;
217
+
218
+ for (const indexName of ["index.html", "index.js"]) {
219
+ const candidate = join(filePath, indexName);
220
+ if (existsSync(candidate) && statSync(candidate).isFile()) {
221
+ indexFile = candidate;
222
+ break;
223
+ }
224
+ }
225
+
226
+ filePath = indexFile;
227
+ fileStat = indexFile ? statSync(filePath) : null;
228
+ }
229
+
230
+ // 如果存在且是文件
231
+ if (fileStat && fileStat.isFile()) {
232
+
233
+ // 判断是否是请求而无需进一步解析
234
+ // 2025年12月5日 于南京
235
+ let isXHR = headers["sec-fetch-dest"] === "empty";
236
+
237
+ // 是否是 CommonJS / UMD 门面请求(由 import 改写时追加)
238
+ // 2026年11月25日 于南京
239
+ const isCjsShim = /(^|&)oipage=cjs($|&)/.test(query);
240
+
241
+ let dotName = (filePath.match(/\.([^.]+)$/) || [])[1] || "";
242
+ let fileType = mimeTypes[dotName]; // 文件类型
243
+ let fileInfo = statSync(filePath);
244
+
245
+ let fileModifiedTime = new Date(fileInfo.mtime).toGMTString();
246
+
247
+ let responseHeader = {
248
+ 'Content-Type': buildContentType(fileType || "text/plain"),
249
+ 'Access-Control-Allow-Origin': '*',
250
+ 'Server': 'Powered by ' + name + '@' + version,
251
+ 'Cache-Control': 'no-cache',
252
+ // 'Content-Length': fileInfo.size, // 会导致拦截修改的文本内容不对
253
+
254
+ // 与if-modified-since配合使用,做缓存验证
255
+ 'Last-Modified': fileModifiedTime,
256
+
257
+ // 与if-none-match配合使用,做缓存验证
258
+ // ETag 包含 gzip 标志,确保 gzip 配置变化时缓存正确失效
259
+ // 同时包含 CJS 门面标志,避免门面与原文件共用缓存
260
+ 'ETag': '"' + fileInfo.mtime.getTime() + (gzip ? '-gz' : '') + (isCjsShim ? '-cjs' : '') + '"',
261
+
262
+ // 告知代理/缓存:响应内容会根据 Accept-Encoding 不同而变化
263
+ 'Vary': 'Accept-Encoding'
264
+ };
265
+
266
+ if (cache && headers["if-modified-since"]) {
267
+ let ifModifiedSince = new Date(headers["if-modified-since"]).valueOf()
268
+ let lastModified = new Date(fileModifiedTime).valueOf()
269
+
270
+ // 注意这里不能使用<=,否则
271
+ // 1、会出现时区问题
272
+ // 2、作为开发服务器,可能同一个url地址对应的文件不同,被误判为未修改
273
+ // 2025年12月29日 于南京
274
+ // if (lastModified <= ifModifiedSince) {}
275
+
276
+ // 同时检查 ETag(If-None-Match),确保 gzip 配置变化时不会错误返回 304
277
+ // 比如:gzip 从关闭改为开启,响应内容从原始变为压缩,ETag 不同,必须重新传输
278
+ // 2026年08月15日 于南宁
279
+ let etagMatch = !headers["if-none-match"] || headers["if-none-match"] === responseHeader['ETag'];
280
+
281
+ if (lastModified === ifModifiedSince && etagMatch) {
282
+ response.writeHead(304, responseHeader);
283
+ response.end();
284
+ console.log("\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);
285
+ return;
286
+ }
287
+ }
288
+
289
+ let sendType = "";
290
+ let entry = headers.accept !== "*/*";
291
+
292
+ // 判断是否需要 gzip 压缩:配置开启 && 客户端支持 && 文件类型可压缩
293
+ let acceptEncoding = headers["accept-encoding"] || "";
294
+ let shouldGzip = gzip && /\bgzip\b/.test(acceptEncoding) && compressibleTypes.has(fileType);
295
+
296
+ // CommonJS / UMD 门面:把 module.exports 包成 ESM 的默认导出
297
+ // 这样 `import { x } from "pkg"` 在改写后可以从默认导出上解构
298
+ // 2026年11月25日 于南京
299
+ if (isCjsShim) {
300
+ sendType = "Read";
301
+
302
+ let code = readFileSync(filePath, "utf8");
303
+ code = applyDefine(code);
304
+
305
+ let body = "let module = { exports: {} };\nlet exports = module.exports;\n" + code + "\nexport default module.exports;\n";
306
+
307
+ if (shouldGzip && compressibleTypes.has(fileType)) {
308
+ responseHeader['Content-Encoding'] = 'gzip';
309
+ body = gzipSync(Buffer.from(body));
310
+ }
311
+
312
+ response.writeHead(200, responseHeader);
313
+ response.write(body);
314
+ response.end();
315
+
316
+ console.log("\x1b[1m\x1b[32m[" + name + "] " + sendType + " CJS File: " + url + '\x1b[0m ' + new Date().toLocaleString() + (shouldGzip ? " \x1b[33m\x1b[1mgzip\x1b[0m" : "") + " " + rawIp);
317
+ return;
318
+ }
319
+
320
+ // 如果文件小于1M且不是二进制,认为不大,直接读取
321
+ // 如果是二进制文件,即使小于10M也使用流(避免不必要的加载器处理和import解析)
322
+ if (fileInfo.size < 10 * 1024 * 1024 && !isBinary(filePath)) {
323
+ const isDownload = query.split("&").includes("download");
324
+
325
+ try {
326
+ let { source, resolveImport } = resolveImportFactory(basePath, filePath, entry, isWebsite ? websiteIntercept : config.devServer.intercept, isDownload, isWebsite)
327
+
328
+ // 只处理非下载文件
329
+ // 过大的也不进行处理
330
+ // (对website无效)
331
+ if (!isDownload) {
332
+ let loaders = isWebsite ? websiteLoader : config.module;
333
+
334
+ for (let i = 0; i < loaders.rules.length; i++) {
335
+ if (loaders.rules[i].test.test(filePath)) {
336
+ source = loaders.rules[i].use.call({
337
+ root: basePath, // 服务器根路径
338
+ path: filePath.replace(basePath, ""), // 文件相对路径
339
+ entry, // 是否是浏览器地址栏直接访问
340
+ setFileType(_fileType) { // 设置文件类型
341
+ fileType = _fileType;
342
+ responseHeader['Content-Type'] = buildContentType(_fileType);
343
+ }
344
+ }, source);
345
+ break;
346
+ }
347
+ }
348
+
349
+ }
350
+
351
+ // 类似 DefinePlugin 的替换,只对 js 文本生效
352
+ if (fileType === "application/javascript") {
353
+ source = applyDefine(source + "");
354
+ }
355
+
356
+ sendType = "Read";
357
+ let body = isXHR ? source : resolveImport(source, fileType !== "application/javascript");
358
+
359
+ // gzip 压缩后发送(需要重新判断 fileType,因为 loader 可能修改了它)
360
+ if (shouldGzip && compressibleTypes.has(fileType)) {
361
+ responseHeader['Content-Encoding'] = 'gzip';
362
+ body = gzipSync(Buffer.from(body));
363
+ }
364
+
365
+ response.writeHead(200, responseHeader);
366
+ response.write(body);
367
+ response.end();
368
+ } catch (error) {
369
+ // 解析失败时给出可读的 500,而不是让客户端一直等待
370
+ // 2026年11月25日 于南京
371
+ response.writeHead(500, {
372
+ 'Content-Type': buildContentType("text/plain"),
373
+ 'Access-Control-Allow-Origin': '*',
374
+ 'Server': 'Powered by ' + name + '@' + version
375
+ });
376
+ response.end("Module resolve error: " + (error && error.message || error));
377
+ console.log("\x1b[1m\x1b[31m[" + name + "] resolve error: " + url + " -> " + (error && error.message || error) + "\x1b[0m " + new Date().toLocaleString() + " " + rawIp);
378
+ return;
379
+ }
380
+ }
381
+
382
+ // 对于大文件,使用流读取
383
+ else {
384
+ sendType = "Stream";
385
+
386
+ const stream = createReadStream(filePath);
387
+
388
+ // 读流出错(文件被删除、符号链接指向目录等)时结束响应,避免客户端悬挂
389
+ // 2026年11月25日 于南京
390
+ stream.on("error", error => {
391
+ console.log("\x1b[1m\x1b[31m[" + name + "] stream error: " + url + " -> " + error.message + "\x1b[0m");
392
+
393
+ if (!response.headersSent) {
394
+ response.writeHead(500, {
395
+ 'Content-Type': buildContentType("text/plain"),
396
+ 'Access-Control-Allow-Origin': '*',
397
+ 'Server': 'Powered by ' + name + '@' + version
398
+ });
399
+ response.end("Stream error: " + error.message);
400
+ } else {
401
+ response.destroy();
402
+ }
403
+ });
404
+
405
+ if (shouldGzip) {
406
+ // gzip 流式压缩:文件大小变化,不能设置 Content-Length
407
+ responseHeader['Content-Encoding'] = 'gzip';
408
+ response.writeHead(200, responseHeader);
409
+ stream.pipe(createGzip()).pipe(response);
410
+ } else {
411
+ responseHeader['Content-Length'] = fileInfo.size
412
+
413
+ response.writeHead(200, responseHeader);
414
+ stream.pipe(response);
415
+ }
416
+ }
417
+
418
+ console.log("\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);
419
+ }
420
+
421
+ // 否则就是404
422
+ else {
423
+ response.writeHead(404, {
424
+ 'Content-Type': buildContentType("text/html"),
425
+ 'Access-Control-Allow-Origin': '*',
426
+ 'Server': 'Powered by ' + name + '@' + version
427
+ });
428
+ response.write(resolve404(filePath, url, website, config.name || "OIPage", rawIp));
429
+ response.end();
430
+ }
431
+ }
432
+
433
+ });
434
+
435
+ Server.listen(port);
436
+
437
+ // 获取网络信息
438
+ let networkValue = network();
439
+
440
+ // 打印成功提示
441
+ console.log('\x1b[1m\x1b[32m[' + name + '] Project is running at:\x1b[0m');
442
+ console.log('\x1b[1m\x1b[32m[' + name + '] Loopback: \x1b[36mhttp://localhost:' + port + '/\x1b[0m');
443
+ for (let ipv4Item of networkValue.IPv4) console.log('\x1b[1m\x1b[32m[' + name + '] On Your Network (IPv4):\x1b[36m http://' + ipv4Item.address + ':' + port + '/\x1b[0m');
444
+ for (let ipv6Item of networkValue.IPv6) console.log('\x1b[1m\x1b[32m[' + name + '] On Your Network (IPv6): \x1b[36mhttp://[' + ipv6Item.address + ']:' + port + '/\x1b[0m');
445
+ console.log('\x1b[1m\x1b[32m[' + name + '] Content not from ' + (config.name || "OIPage") + ' is served from \x1b[36m"' + basePath + '" \x1b[0mdirectory');
446
+
447
+ if (typeof config.devServer.open === "string" || config.devServer.open) {
448
+ let url = 'http://localhost:' + port + "/" + (typeof config.devServer.open === "string" ? config.devServer.open : "");
449
+ openBrowser(url);
450
+ console.log('\x1b[1m\x1b[32m[' + name + '] Open: \x1b[36m' + url + '\x1b[0m');
451
+ }
452
+
453
+ if (!cache) console.log('\x1b[1m\x1b[32m[' + name + '] Cancel 304 Cache!\x1b[0m');
454
+ if (gzip) console.log('\x1b[1m\x1b[32m[' + name + '] Gzip Compression: \x1b[36menabled\x1b[0m');
455
+ console.log('\n' + (config.name || "OIPage") + ' ' + version + ' compiled \x1b[1m\x1b[32msuccessfully\x1b[0m in ' + (new Date().valueOf() - startTime) + ' ms\n');
319
456
  };