@oipage/cli 0.3.0-alpha.5 → 1.0.0-alpha.0

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.
@@ -0,0 +1,548 @@
1
+ const { readFileSync, statSync } = require("fs");
2
+ const { join, dirname, extname } = require("path");
3
+
4
+ // 允许出现正则字面量的前一个记号(用于区分除号和正则)
5
+ const REGEX_ALLOWED_AFTER_PUNCT = new Set([
6
+ "(", "{", "[", ",", ";", "=", ":", "!", "&", "|", "?", "+", "-", "*", "%", "^", "~", "<", ">"
7
+ ]);
8
+
9
+ // 允许出现正则字面量的前一个关键字
10
+ const REGEX_ALLOWED_AFTER_WORD = new Set([
11
+ "return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "case", "do", "else", "yield", "await", "throw"
12
+ ]);
13
+
14
+ // 判定模块形态时的缓存:文件路径 + 修改时间 + 体积
15
+ const formCache = new Map();
16
+
17
+ /**
18
+ * 把注释、字符串、模板字符串的内容替换为等长空白(保留换行)
19
+ *
20
+ * 目的:在“代码区”做判断与替换,既不会误伤字符串和注释,
21
+ * 也不会改变原文长度,方便按偏移位置回写。
22
+ * @param {string} code 源码
23
+ * @returns {string} 等长空白化后的源码
24
+ */
25
+ function stripCode(code) {
26
+ let out = [];
27
+ let i = 0;
28
+ const n = code.length;
29
+ const blank = ch => (ch === "\n" ? "\n" : " ");
30
+
31
+ while (i < n) {
32
+ const ch = code[i];
33
+
34
+ // 行注释
35
+ if (ch === "/" && code[i + 1] === "/") {
36
+ out.push(" ");
37
+ i += 2;
38
+ while (i < n && code[i] !== "\n") { out.push(" "); i++; }
39
+ continue;
40
+ }
41
+
42
+ // 块注释
43
+ if (ch === "/" && code[i + 1] === "*") {
44
+ out.push(" ");
45
+ i += 2;
46
+ while (i < n && !(code[i] === "*" && code[i + 1] === "/")) { out.push(blank(code[i])); i++; }
47
+ if (i < n) { out.push(" "); i += 2; }
48
+ continue;
49
+ }
50
+
51
+ // 字符串
52
+ if (ch === '"' || ch === "'") {
53
+ const quote = ch;
54
+ out.push(" ");
55
+ i++;
56
+ while (i < n) {
57
+ if (code[i] === "\\") { out.push(" "); i += 2; continue; }
58
+ if (code[i] === quote) { out.push(" "); i++; break; }
59
+ out.push(blank(code[i]));
60
+ i++;
61
+ }
62
+ continue;
63
+ }
64
+
65
+ // 模板字符串(整体空白化,${} 内部同样处理,保守但安全)
66
+ if (ch === "`") {
67
+ out.push(" ");
68
+ i++;
69
+ while (i < n) {
70
+ if (code[i] === "\\") { out.push(" "); i += 2; continue; }
71
+ if (code[i] === "`") { out.push(" "); i++; break; }
72
+ out.push(blank(code[i]));
73
+ i++;
74
+ }
75
+ continue;
76
+ }
77
+
78
+ out.push(ch);
79
+ i++;
80
+ }
81
+
82
+ return out.join("");
83
+ }
84
+
85
+ /**
86
+ * 轻量词法器,只产出我们需要的记号
87
+ * @param {string} code 源码
88
+ * @returns {Array} 记号列表
89
+ */
90
+ function tokenize(code) {
91
+ const tokens = [];
92
+ let i = 0;
93
+ const n = code.length;
94
+ let prev = null;
95
+
96
+ const push = token => {
97
+ tokens.push(token);
98
+ prev = token;
99
+ };
100
+
101
+ const regexAllowed = () => {
102
+ if (!prev) return true;
103
+ if (prev.type === "punct") return REGEX_ALLOWED_AFTER_PUNCT.has(prev.value);
104
+ if (prev.type === "ident") return REGEX_ALLOWED_AFTER_WORD.has(prev.value);
105
+ return false;
106
+ };
107
+
108
+ while (i < n) {
109
+ const ch = code[i];
110
+
111
+ if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") { i++; continue; }
112
+
113
+ if (ch === "/" && code[i + 1] === "/") {
114
+ const end = code.indexOf("\n", i + 2);
115
+ i = end < 0 ? n : end;
116
+ continue;
117
+ }
118
+
119
+ if (ch === "/" && code[i + 1] === "*") {
120
+ const end = code.indexOf("*/", i + 2);
121
+ i = end < 0 ? n : end + 2;
122
+ continue;
123
+ }
124
+
125
+ if (ch === '"' || ch === "'") {
126
+ const start = i;
127
+ const quote = ch;
128
+ i++;
129
+ while (i < n) {
130
+ if (code[i] === "\\") { i += 2; continue; }
131
+ if (code[i] === quote) { i++; break; }
132
+ i++;
133
+ }
134
+ push({ type: "string", value: code.slice(start + 1, i - 1), start, end: i, quote });
135
+ continue;
136
+ }
137
+
138
+ if (ch === "`") {
139
+ const start = i;
140
+ i++;
141
+ while (i < n) {
142
+ if (code[i] === "\\") { i += 2; continue; }
143
+ if (code[i] === "`") { i++; break; }
144
+ i++;
145
+ }
146
+ push({ type: "template", value: code.slice(start, i), start, end: i });
147
+ continue;
148
+ }
149
+
150
+ if (ch === "/" && regexAllowed() && code[i + 1] !== "/" && code[i + 1] !== "*") {
151
+ const start = i;
152
+ let inClass = false;
153
+ i++;
154
+ while (i < n) {
155
+ if (code[i] === "\\") { i += 2; continue; }
156
+ if (code[i] === "[") { inClass = true; i++; continue; }
157
+ if (code[i] === "]") { inClass = false; i++; continue; }
158
+ if (code[i] === "/" && !inClass) { i++; break; }
159
+ if (code[i] === "\n") break;
160
+ i++;
161
+ }
162
+ while (i < n && /[a-z]/i.test(code[i])) i++;
163
+ push({ type: "regex", value: code.slice(start, i), start, end: i });
164
+ continue;
165
+ }
166
+
167
+ if (/[A-Za-z_$]/.test(ch)) {
168
+ const start = i;
169
+ i++;
170
+ while (i < n && /[A-Za-z0-9_$]/.test(code[i])) i++;
171
+ push({ type: "ident", value: code.slice(start, i), start, end: i });
172
+ continue;
173
+ }
174
+
175
+ if (/[0-9]/.test(ch)) {
176
+ const start = i;
177
+ i++;
178
+ while (i < n && /[0-9a-zA-Z._]/.test(code[i])) i++;
179
+ push({ type: "number", value: code.slice(start, i), start, end: i });
180
+ continue;
181
+ }
182
+
183
+ push({ type: "punct", value: ch, start: i, end: i + 1 });
184
+ i++;
185
+ }
186
+
187
+ return tokens;
188
+ }
189
+
190
+ /**
191
+ * 解析 { a, b as c } 里的成对关系
192
+ */
193
+ function parsePairs(tokens, start, end) {
194
+ const pairs = [];
195
+ let i = start;
196
+
197
+ while (i < end) {
198
+ const tk = tokens[i];
199
+
200
+ if (tk.type === "punct" && tk.value === ",") { i++; continue; }
201
+
202
+ if (tk.type === "string") { pairs.push({ name: tk.value, alias: null }); i++; continue; }
203
+
204
+ if (tk.type === "ident") {
205
+ const name = tk.value;
206
+ let alias = null;
207
+
208
+ if (tokens[i + 1] && tokens[i + 1].type === "ident" && tokens[i + 1].value === "as" &&
209
+ tokens[i + 2] && tokens[i + 2].type === "ident") {
210
+ alias = tokens[i + 2].value;
211
+ i += 3;
212
+ } else {
213
+ i++;
214
+ }
215
+
216
+ pairs.push({ name, alias });
217
+ continue;
218
+ }
219
+
220
+ i++;
221
+ }
222
+
223
+ return pairs;
224
+ }
225
+
226
+ /**
227
+ * 从指定位置起寻找 “from” 关键字(且紧跟字符串),找不到返回 -1
228
+ */
229
+ function findFrom(tokens, start) {
230
+ for (let j = start; j < tokens.length; j++) {
231
+ const tk = tokens[j];
232
+
233
+ if (tk.type === "string") return -1;
234
+ if (tk.type === "punct" && (tk.value === ";" || tk.value === ")")) return -1;
235
+ if (tk.type === "ident" && tk.value === "from" && tokens[j + 1] && tokens[j + 1].type === "string") return j;
236
+ }
237
+
238
+ return -1;
239
+ }
240
+
241
+ /**
242
+ * 计算语句结束位置(把 with / assert 属性块一起算进去)
243
+ */
244
+ function endWithAttributes(tokens, nextIndex, specEnd) {
245
+ let end = specEnd;
246
+ const tk = tokens[nextIndex];
247
+
248
+ if (tk && tk.type === "ident" && (tk.value === "with" || tk.value === "assert")) {
249
+ for (let j = nextIndex + 1; j < tokens.length; j++) {
250
+ const t2 = tokens[j];
251
+ if (t2.type === "punct" && t2.value === "{") {
252
+ let depth = 0;
253
+ for (; j < tokens.length; j++) {
254
+ if (tokens[j].type === "punct" && tokens[j].value === "{") depth++;
255
+ else if (tokens[j].type === "punct" && tokens[j].value === "}") { depth--; if (depth === 0) { end = tokens[j].end; break; } }
256
+ }
257
+ break;
258
+ }
259
+ }
260
+ }
261
+
262
+ return end;
263
+ }
264
+
265
+ /**
266
+ * 扫描源码里的模块语句(import / export / 动态 import)
267
+ *
268
+ * 返回每一项都带有精确偏移,供调用方只替换“说明符”或整条语句。
269
+ * @param {string} code 源码
270
+ * @returns {Array} 语句列表
271
+ */
272
+ function scanSites(code) {
273
+ const tokens = tokenize(code);
274
+ const sites = [];
275
+
276
+ for (let i = 0; i < tokens.length; i++) {
277
+ const t = tokens[i];
278
+ if (t.type !== "ident") continue;
279
+
280
+ if (t.value === "import") {
281
+ const nx = tokens[i + 1];
282
+ if (!nx) continue;
283
+
284
+ // import.meta
285
+ if (nx.type === "punct" && nx.value === ".") continue;
286
+
287
+ // 动态 import()
288
+ if (nx.type === "punct" && nx.value === "(") {
289
+ const arg = tokens[i + 2];
290
+ if (arg && arg.type === "string") {
291
+ sites.push({
292
+ kind: "dynamic",
293
+ specifier: arg.value,
294
+ specStart: arg.start,
295
+ specEnd: arg.end,
296
+ stmtStart: arg.start,
297
+ stmtEnd: arg.end
298
+ });
299
+ }
300
+ continue;
301
+ }
302
+
303
+ // 纯副作用导入:import "x"
304
+ if (nx.type === "string") {
305
+ sites.push({
306
+ kind: "import",
307
+ form: "sideEffect",
308
+ specifier: nx.value,
309
+ specStart: nx.start,
310
+ specEnd: nx.end,
311
+ stmtStart: t.start,
312
+ stmtEnd: endWithAttributes(tokens, i + 2, nx.end)
313
+ });
314
+ continue;
315
+ }
316
+
317
+ // 带子句的导入
318
+ const fromIndex = findFrom(tokens, i + 1);
319
+ if (fromIndex < 0) continue;
320
+
321
+ const spec = tokens[fromIndex + 1];
322
+ if (!spec || spec.type !== "string") continue;
323
+
324
+ const bindings = { defaults: [], named: [], ns: [] };
325
+ let j = i + 1;
326
+
327
+ // 默认导入
328
+ if (tokens[j] && tokens[j].type === "ident" && tokens[j].value !== "from") {
329
+ bindings.defaults.push(tokens[j].value);
330
+ j++;
331
+ if (tokens[j] && tokens[j].type === "punct" && tokens[j].value === ",") j++;
332
+ }
333
+
334
+ if (tokens[j] && tokens[j].type === "punct" && tokens[j].value === "*") {
335
+ if (tokens[j + 1] && tokens[j + 1].value === "as" && tokens[j + 2] && tokens[j + 2].type === "ident") {
336
+ bindings.ns.push(tokens[j + 2].value);
337
+ }
338
+ } else if (tokens[j] && tokens[j].type === "punct" && tokens[j].value === "{") {
339
+ let close = j;
340
+ let depth = 0;
341
+ for (; close < fromIndex; close++) {
342
+ if (tokens[close].type === "punct" && tokens[close].value === "{") depth++;
343
+ else if (tokens[close].type === "punct" && tokens[close].value === "}") { depth--; if (depth === 0) break; }
344
+ }
345
+ bindings.named = parsePairs(tokens, j + 1, close);
346
+ }
347
+
348
+ sites.push({
349
+ kind: "import",
350
+ form: "clause",
351
+ specifier: spec.value,
352
+ specStart: spec.start,
353
+ specEnd: spec.end,
354
+ stmtStart: t.start,
355
+ stmtEnd: endWithAttributes(tokens, fromIndex + 2, spec.end),
356
+ bindings
357
+ });
358
+
359
+ continue;
360
+ }
361
+
362
+ if (t.value === "export") {
363
+ const nx = tokens[i + 1];
364
+ if (!nx) continue;
365
+
366
+ // export * from / export * as ns from
367
+ if (nx.type === "punct" && nx.value === "*") {
368
+ let j = i + 2;
369
+ let starAs = null;
370
+
371
+ if (tokens[j] && tokens[j].type === "ident" && tokens[j].value === "as") {
372
+ starAs = tokens[j + 1] && tokens[j + 1].type === "ident" ? tokens[j + 1].value : null;
373
+ j += 2;
374
+ }
375
+
376
+ if (tokens[j] && tokens[j].type === "ident" && tokens[j].value === "from") {
377
+ const spec = tokens[j + 1];
378
+ if (spec && spec.type === "string") {
379
+ sites.push({
380
+ kind: "export-star",
381
+ starAs,
382
+ specifier: spec.value,
383
+ specStart: spec.start,
384
+ specEnd: spec.end,
385
+ stmtStart: t.start,
386
+ stmtEnd: endWithAttributes(tokens, j + 2, spec.end)
387
+ });
388
+ }
389
+ }
390
+
391
+ continue;
392
+ }
393
+
394
+ // export { ... } from
395
+ if (nx.type === "punct" && nx.value === "{") {
396
+ let close = i + 1;
397
+ let depth = 0;
398
+ for (; close < tokens.length; close++) {
399
+ if (tokens[close].type === "punct" && tokens[close].value === "{") depth++;
400
+ else if (tokens[close].type === "punct" && tokens[close].value === "}") { depth--; if (depth === 0) break; }
401
+ }
402
+
403
+ const fromTok = tokens[close + 1];
404
+ if (!(fromTok && fromTok.type === "ident" && fromTok.value === "from")) continue;
405
+
406
+ const spec = tokens[close + 2];
407
+ if (!spec || spec.type !== "string") continue;
408
+
409
+ sites.push({
410
+ kind: "export-named",
411
+ pairs: parsePairs(tokens, i + 2, close),
412
+ specifier: spec.value,
413
+ specStart: spec.start,
414
+ specEnd: spec.end,
415
+ stmtStart: t.start,
416
+ stmtEnd: endWithAttributes(tokens, close + 3, spec.end)
417
+ });
418
+ }
419
+
420
+ continue;
421
+ }
422
+ }
423
+
424
+ return sites;
425
+ }
426
+
427
+ /**
428
+ * 在代码区替换文本(跳过字符串与注释)
429
+ * @param {string} content 原文
430
+ * @param {string} search 待替换内容
431
+ * @param {string} replacement 替换内容
432
+ * @returns {string} 替换结果
433
+ */
434
+ function replaceInCode(content, search, replacement) {
435
+ if (!search) return content;
436
+
437
+ const blank = stripCode(content);
438
+ const result = [];
439
+ let cursor = 0;
440
+ let index = content.indexOf(search);
441
+
442
+ while (index >= 0) {
443
+ // 只有“代码区”的命中才替换:空白化后的同一位置仍应等于 search
444
+ if (blank.slice(index, index + search.length) === search) {
445
+ result.push(content.slice(cursor, index), replacement);
446
+ cursor = index + search.length;
447
+ }
448
+ index = content.indexOf(search, index + 1);
449
+ }
450
+
451
+ result.push(content.slice(cursor));
452
+ return result.join("");
453
+ }
454
+
455
+ /**
456
+ * 判断文件是不是 ESM(出现 import/export 声明)
457
+ *
458
+ * 注意:这里只看关键字本身的上下文,不依赖“是否有 from”,
459
+ * 否则 `export { a }`、`export const a = 1` 这类会被漏判。
460
+ */
461
+ function hasEsmSyntax(code) {
462
+ const tokens = tokenize(code);
463
+
464
+ for (let i = 0; i < tokens.length; i++) {
465
+ const t = tokens[i];
466
+ if (t.type !== "ident") continue;
467
+
468
+ const nx = tokens[i + 1];
469
+ if (!nx) continue;
470
+
471
+ if (t.value === "export") {
472
+ if (nx.type === "punct" && (nx.value === "{" || nx.value === "*")) return true;
473
+ if (nx.type === "ident" && !["from", "as"].includes(nx.value)) return true;
474
+ continue;
475
+ }
476
+
477
+ if (t.value === "import") {
478
+ if (nx.type === "punct" && (nx.value === "." || nx.value === "(")) continue;
479
+ if (nx.type === "string") return true;
480
+ if (nx.type === "punct" && (nx.value === "{" || nx.value === "*")) return true;
481
+ if (nx.type === "ident" && nx.value !== "from") return true;
482
+ }
483
+ }
484
+
485
+ return false;
486
+ }
487
+
488
+ /**
489
+ * 判断是否为 CommonJS / UMD 特征
490
+ */
491
+ function hasCjsMarkers(code) {
492
+ const blank = stripCode(code);
493
+ return /module\.exports|define\.amd|\bexports\.[A-Za-z_$]/.test(blank);
494
+ }
495
+
496
+ /**
497
+ * 读取源码并判断模块形态
498
+ * @param {string} filePath 文件路径
499
+ * @param {object} packageJson 所属包的 package.json(可选)
500
+ * @returns {"esm"|"cjs"}
501
+ */
502
+ function getForm(filePath, packageJson) {
503
+ const stat = statSync(filePath);
504
+ const key = filePath + "|" + stat.mtimeMs + "|" + stat.size;
505
+ const cached = formCache.get(key);
506
+ if (cached) return cached;
507
+
508
+ let code = "";
509
+
510
+ try {
511
+ code = readFileSync(filePath, "utf8");
512
+ } catch (e) {
513
+ formCache.set(key, "cjs");
514
+ return "cjs";
515
+ }
516
+
517
+ let form;
518
+
519
+ // 1、有顶层 import/export 语句,一律按 ESM 处理
520
+ if (hasEsmSyntax(code)) {
521
+ form = "esm";
522
+
523
+ // 2、.cjs 固定是 CJS
524
+ } else if (extname(filePath) === ".cjs") {
525
+ form = "cjs";
526
+
527
+ // 3、包没有声明 type: module 且是 .js,按 CommonJS 处理
528
+ } else if (extname(filePath) === ".js" && !(packageJson && packageJson.type === "module")) {
529
+ form = "cjs";
530
+
531
+ // 4、兜底看特征
532
+ } else {
533
+ form = hasCjsMarkers(code) ? "cjs" : "esm";
534
+ }
535
+
536
+ formCache.set(key, form);
537
+ return form;
538
+ }
539
+
540
+ module.exports = {
541
+ stripCode,
542
+ tokenize,
543
+ scanSites,
544
+ replaceInCode,
545
+ hasEsmSyntax,
546
+ hasCjsMarkers,
547
+ getForm
548
+ };
@@ -33,9 +33,9 @@ module.exports = function (filePath, url, website, name, rawIp) {
33
33
 
34
34
  try {
35
35
  subItems = readdirSync(filePath);
36
- console.log("<i> \x1b[1m\x1b[32m[" + name + "-http-server] Read Folder: " + url + '\x1b[0m ' + new Date().toLocaleString() + " " + rawIp);
36
+ console.log("\x1b[1m\x1b[32m[" + name + "-http-server] Read Folder: " + url + '\x1b[0m ' + new Date().toLocaleString() + " " + rawIp);
37
37
  } catch (e) {
38
- console.log("<i> \x1b[1m\x1b[32m[" + name + "-http-server] Read " + (/\/$/.test(url) ? "Folder" : "File") + ": \x1b[35m" + url + ' 404 Not Found\x1b[0m ' + new Date().toLocaleString() + " " + rawIp);
38
+ console.log("\x1b[1m\x1b[32m[" + name + "-http-server] Read " + (/\/$/.test(url) ? "Folder" : "File") + ": \x1b[35m" + url + ' 404 Not Found\x1b[0m ' + new Date().toLocaleString() + " " + rawIp);
39
39
  try {
40
40
  if (!/\/$/.test(url) || url === "/") {
41
41
  filePath = join(filePath, "../");