@maiyunnet/kebab 9.29.5 → 10.0.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.
Files changed (64) hide show
  1. package/abox/proxy.js +24 -2
  2. package/abox/response.js +36 -17
  3. package/abox/session-login.js +1 -13
  4. package/abox/text.d.ts +2 -0
  5. package/abox/text.js +51 -0
  6. package/doc/kebab-rag.md +2700 -1270
  7. package/index.d.ts +12 -1
  8. package/index.js +1 -1
  9. package/lib/ai.d.ts +4 -0
  10. package/lib/ai.js +32 -16
  11. package/lib/cookie.d.ts +2 -0
  12. package/lib/cookie.js +47 -45
  13. package/lib/core.d.ts +26 -0
  14. package/lib/core.js +36 -13
  15. package/lib/cron.js +1 -8
  16. package/lib/crypto.js +20 -6
  17. package/lib/db/conn.d.ts +10 -1
  18. package/lib/db/conn.js +1 -5
  19. package/lib/db/pool.d.ts +10 -2
  20. package/lib/db/pool.js +0 -6
  21. package/lib/db/tran.d.ts +10 -1
  22. package/lib/db/tran.js +0 -5
  23. package/lib/db.d.ts +3 -3
  24. package/lib/fs.js +78 -31
  25. package/lib/kv.d.ts +216 -88
  26. package/lib/kv.js +520 -230
  27. package/lib/s3.d.ts +2 -0
  28. package/lib/s3.js +14 -27
  29. package/lib/session.d.ts +7 -0
  30. package/lib/session.js +23 -2
  31. package/lib/socket.d.ts +4 -1
  32. package/lib/socket.js +1 -0
  33. package/lib/sql.d.ts +0 -5
  34. package/lib/sql.js +48 -12
  35. package/lib/text.d.ts +32 -8
  36. package/lib/text.js +30 -17
  37. package/lib/turnstile.d.ts +6 -0
  38. package/lib/turnstile.js +16 -9
  39. package/lib/undici/response.d.ts +13 -3
  40. package/lib/undici/response.js +0 -1
  41. package/lib/undici.d.ts +33 -1
  42. package/lib/undici.js +72 -56
  43. package/lib/vector.d.ts +33 -19
  44. package/lib/vector.js +0 -1
  45. package/lib/ws.d.ts +1 -1
  46. package/lib/ws.js +85 -128
  47. package/lib/zip.js +46 -45
  48. package/package.json +2 -2
  49. package/sys/child.js +178 -146
  50. package/sys/cmd.js +196 -197
  51. package/sys/ctr.d.ts +14 -14
  52. package/sys/ctr.js +145 -59
  53. package/sys/master.js +111 -80
  54. package/sys/mod.d.ts +112 -51
  55. package/sys/mod.js +23 -51
  56. package/sys/monitor/files.d.ts +2 -1
  57. package/sys/monitor/files.js +77 -21
  58. package/sys/monitor/watchdog.d.ts +7 -0
  59. package/sys/monitor/watchdog.js +311 -203
  60. package/sys/monitor.d.ts +59 -54
  61. package/sys/monitor.js +742 -681
  62. package/sys/route.d.ts +4 -4
  63. package/sys/route.js +93 -52
  64. package/www/example/ctr/test.js +8 -8
package/lib/db/conn.js CHANGED
@@ -135,6 +135,7 @@ export class Connection {
135
135
  this.refreshLast();
136
136
  }
137
137
  try {
138
+ // --- 收窄 pg.Client 与 mysql2.Connection 的联合类型后再调用 query ---
138
139
  if (this._link instanceof pg.Client) {
139
140
  await this._link.query('SELECT 1');
140
141
  }
@@ -147,11 +148,6 @@ export class Connection {
147
148
  return false;
148
149
  }
149
150
  }
150
- /**
151
- * --- 执行一条 SQL 并获得返回数据 ---
152
- * @param sql 执行的 SQL 字符串
153
- * @param values 要替换的 data 数据
154
- */
155
151
  async query(sql, values) {
156
152
  const rtn = {
157
153
  'rows': null,
package/lib/db/pool.d.ts CHANGED
@@ -38,10 +38,18 @@ export declare class Pool {
38
38
  /**
39
39
  * --- 执行一条 SQL,无视顺序和相同连接,随用随取 ---
40
40
  * @param sql 执行的 SQL 字符串
41
- * @param values 要替换的 data 数据
42
- * @returns error.errno = -500 表示系统错误
41
+ * @param values SQL 占位符绑定的值
42
+ * @returns 查询结果,result = -500 表示系统错误
43
43
  */
44
44
  query(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData>;
45
+ /**
46
+ * --- 执行一条 SQL,按指定类型返回数据行 ---
47
+ * @typeParam TRow SQL 返回的行结构,由调用方根据查询字段指定
48
+ * @param sql 执行的 SQL 字符串
49
+ * @param values SQL 占位符绑定的值
50
+ * @returns 查询结果,result = -500 表示系统错误
51
+ */
52
+ query<TRow extends object>(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData<TRow>>;
45
53
  /**
46
54
  * --- 执行一条 SQL 并获得影响行数对象 packet,连接失败抛出错误 ---
47
55
  * @param sql 执行的 SQL 字符串
package/lib/db/pool.js CHANGED
@@ -117,12 +117,6 @@ export class Pool {
117
117
  getName() {
118
118
  return this._etc.name ?? '';
119
119
  }
120
- /**
121
- * --- 执行一条 SQL,无视顺序和相同连接,随用随取 ---
122
- * @param sql 执行的 SQL 字符串
123
- * @param values 要替换的 data 数据
124
- * @returns error.errno = -500 表示系统错误
125
- */
126
120
  async query(sql, values) {
127
121
  ++this._queries;
128
122
  // --- 获取并自动 using ---
package/lib/db/tran.d.ts CHANGED
@@ -19,9 +19,18 @@ export declare class Transaction {
19
19
  /**
20
20
  * --- 在事务连接中执行一条 SQL ---
21
21
  * @param sql 执行的 SQL 字符串
22
- * @param values 要替换的 data 数据
22
+ * @param values SQL 占位符绑定的值
23
+ * @returns 查询结果,result = -500 表示事务已关闭或查询失败
23
24
  */
24
25
  query(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData>;
26
+ /**
27
+ * --- 在事务连接中执行一条 SQL,按指定类型返回数据行 ---
28
+ * @typeParam TRow SQL 返回的行结构,由调用方根据查询字段指定
29
+ * @param sql 执行的 SQL 字符串
30
+ * @param values SQL 占位符绑定的值
31
+ * @returns 查询结果,result = -500 表示事务已关闭或查询失败
32
+ */
33
+ query<TRow extends object>(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData<TRow>>;
25
34
  /**
26
35
  * --- 执行一条 SQL 并获得影响行数对象 packet,连接失败抛出错误 ---
27
36
  * @param sql 执行的 SQL 字符串
package/lib/db/tran.js CHANGED
@@ -34,11 +34,6 @@ export class Transaction {
34
34
  getService() {
35
35
  return this._conn?.getService() ?? null;
36
36
  }
37
- /**
38
- * --- 在事务连接中执行一条 SQL ---
39
- * @param sql 执行的 SQL 字符串
40
- * @param values 要替换的 data 数据
41
- */
42
37
  async query(sql, values) {
43
38
  if (!this._conn) {
44
39
  // --- 当前连接已不可用 ---
package/lib/db.d.ts CHANGED
@@ -13,9 +13,9 @@ export declare enum ESERVICE {
13
13
  'MYSQL' = 0,
14
14
  'PGSQL' = 1
15
15
  }
16
- /** --- query 返回的数据 --- */
17
- export interface IData {
18
- 'rows': Array<Record<string, any>> | null;
16
+ /** --- query 返回的数据,未指定行类型时保留动态列访问 --- */
17
+ export interface IData<TRow extends object = Record<string, any>> {
18
+ 'rows': TRow[] | null;
19
19
  'fields': Array<{
20
20
  /** --- 字段名 --- */
21
21
  'name': string;
package/lib/fs.js CHANGED
@@ -3,11 +3,14 @@
3
3
  * Date: 2019-3-29 23:03:07
4
4
  * Last: 2020-3-11 22:21:51, 2022-12-29 01:18:25, 2023-12-13 20:50:09
5
5
  */
6
+ // --- 系统 ---
6
7
  import * as fs from 'fs';
7
8
  import * as crypto from 'crypto';
8
9
  import * as http2 from 'http2';
9
10
  import * as stream from 'stream';
11
+ // --- 第三方 ---
10
12
  import * as mime from '@litert/mime';
13
+ // --- 库和定义 ---
11
14
  import * as lText from './text.js';
12
15
  import * as lCore from './core.js';
13
16
  import * as lZlib from './zlib.js';
@@ -21,10 +24,10 @@ export async function getContent(path, options) {
21
24
  const { encoding, start, end } = typeof options === 'string' ? { 'encoding': options } : options ?? {};
22
25
  try {
23
26
  if (start === undefined && end === undefined) {
24
- return await fs.promises.readFile(path, { encoding });
27
+ return await fs.promises.readFile(path, { 'encoding': encoding });
25
28
  }
26
29
  const data = [];
27
- for await (const chunk of createReadStream(path, { start, end })) {
30
+ for await (const chunk of createReadStream(path, { 'start': start, 'end': end })) {
28
31
  data.push(chunk);
29
32
  }
30
33
  const content = Buffer.concat(data);
@@ -236,8 +239,8 @@ export async function readDir(path, encoding) {
236
239
  */
237
240
  export async function copyFolder(from, to, ignore = []) {
238
241
  let num = 0;
239
- // --- 如果源目录不存在或不是目录,则直接成功 :) ---
240
- if (!await isDir(from)) {
242
+ // --- 如果源目录不存在、不是目录或为符号链接,则直接返回 0 ---
243
+ if (!await isDir(from.replace(/\/+$/, '') || from)) {
241
244
  return 0;
242
245
  }
243
246
  // --- 遍历源目录文件和文件夹,准备复制 ---
@@ -323,14 +326,15 @@ export function createWriteStream(path, options) {
323
326
  * @returns 区间列表;false 表示全部越界或区间过多;null 表示忽略请求头
324
327
  */
325
328
  function parseFileRanges(value, size) {
329
+ // --- 校验单位与分段上限,防止客户端利用大量小区间放大读取开销 ---
326
330
  if (!/^bytes=/i.test(value) || size === 0 || !Number.isSafeInteger(size)) {
327
331
  return null;
328
332
  }
329
333
  const values = value.slice(6).split(',');
330
- // --- 防止客户端利用大量小区间放大文件读取与响应开销 ---
331
334
  if (value.length > 8192 || values.length > 16) {
332
335
  return false;
333
336
  }
337
+ // --- 逐段解析字节区间(用 BigInt 避免超大偏移被浮点取整) ---
334
338
  const total = BigInt(size);
335
339
  const ranges = [];
336
340
  let count = 0;
@@ -340,11 +344,10 @@ function parseFileRanges(value, size) {
340
344
  continue;
341
345
  }
342
346
  const match = /^(\d*)-(\d*)$/.exec(part);
343
- if (!match || match[1] === '' && match[2] === '') {
347
+ if (!match || (match[1] === '' && match[2] === '')) {
344
348
  return null;
345
349
  }
346
350
  ++count;
347
- // --- 先以 BigInt 解析,避免超大偏移被浮点取整后读错字节 ---
348
351
  const start = match[1] !== '' ? BigInt(match[1]) : total - BigInt(match[2]);
349
352
  const end = match[1] !== '' && match[2] !== '' ? BigInt(match[2]) : total - 1n;
350
353
  if (match[1] !== '' && match[2] !== '' && end < start) {
@@ -356,7 +359,7 @@ function parseFileRanges(value, size) {
356
359
  ranges.push({
357
360
  'start': Number(start < 0n ? 0n : start),
358
361
  'end': Number(end >= total ? total - 1n : end),
359
- 'order': count
362
+ 'order': count,
360
363
  });
361
364
  }
362
365
  if (count === 0) {
@@ -365,6 +368,7 @@ function parseFileRanges(value, size) {
365
368
  if (ranges.length === 0) {
366
369
  return false;
367
370
  }
371
+ // --- 合并重叠或相邻区间,并按客户端请求顺序返回 ---
368
372
  ranges.sort((a, b) => a.start - b.start);
369
373
  const merged = [];
370
374
  for (const range of ranges) {
@@ -413,7 +417,7 @@ async function* readFileRanges(path, ranges, headers, footer) {
413
417
  */
414
418
  export async function readToResponse(path, req, res, stat) {
415
419
  stat ??= await stats(path);
416
- if (!stat) {
420
+ if (!stat?.isFile()) {
417
421
  const content = '<h1>404 Not found</h1>';
418
422
  res.setHeader('content-length', Buffer.byteLength(content));
419
423
  lCore.writeHead(res, 404);
@@ -436,13 +440,14 @@ export async function readToResponse(path, req, res, stat) {
436
440
  res.setHeader('accept-ranges', 'bytes');
437
441
  if (canCompress) {
438
442
  const vary = res.getHeader('vary');
439
- const values = (Array.isArray(vary) ? vary.join(',') : String(vary ?? '')).split(',').map((item) => item.trim()).filter(Boolean);
443
+ const rawVary = Array.isArray(vary) ? vary.join(',') : String(vary ?? '');
444
+ const values = rawVary.split(',').map((item) => item.trim()).filter(Boolean);
440
445
  if (!values.some((item) => item === '*' || item.toLowerCase() === 'accept-encoding')) {
441
446
  values.push('Accept-Encoding');
442
447
  res.setHeader('vary', values.join(', '));
443
448
  }
444
449
  }
445
- // --- 这些文件可能需要缓存 ---
450
+ // --- 设置静态文件缓存策略 ---
446
451
  if (['htm', 'html', 'css', 'js', 'mjs', 'xml', 'jpg', 'jpeg', 'svg', 'gif', 'png', 'json'].includes(mimeData.extension)) {
447
452
  /** --- 静态文件默认缓存秒数 --- */
448
453
  const cacheTTL = 600;
@@ -452,20 +457,31 @@ export async function readToResponse(path, req, res, stat) {
452
457
  else {
453
458
  res.setHeader('cache-control', 'no-cache, must-revalidate');
454
459
  }
455
- // --- 条件请求优先于 Range;弱 ETag 只能用于缓存验证,不能用于 If-Match ---
460
+ // --- 条件请求校验(优先于 Range;弱 ETag 只能用于缓存验证,不能用于 If-Match) ---
456
461
  const match = req.headers['if-match'];
457
462
  const unmodifiedSince = req.headers['if-unmodified-since'];
458
- if (match !== undefined ? match.trim() !== '*' : unmodifiedSince !== undefined && modifiedTime > Date.parse(unmodifiedSince)) {
463
+ const failedPrecondition = match !== undefined
464
+ ? match.trim() !== '*'
465
+ : (unmodifiedSince !== undefined && modifiedTime > Date.parse(unmodifiedSince));
466
+ if (failedPrecondition) {
459
467
  res.setHeader('content-length', 0);
460
468
  lCore.writeHead(res, 412);
461
469
  res.end();
462
470
  return;
463
471
  }
472
+ // --- 缓存未变更校验(If-None-Match / If-Modified-Since) ---
464
473
  const noneMatch = req.headers['if-none-match'];
465
474
  const modifiedSince = req.headers['if-modified-since'];
466
475
  const isRead = req.method === 'GET' || req.method === 'HEAD';
467
- const unchanged = noneMatch !== undefined ? noneMatch.trim() === '*' || noneMatch.split(',').some((item) => item.trim().replace(/^W\//, '') === hash.slice(2)) :
468
- isRead && modifiedSince !== undefined && modifiedTime <= Date.parse(modifiedSince);
476
+ let unchanged = false;
477
+ if (noneMatch !== undefined) {
478
+ const tag = hash.slice(2);
479
+ unchanged = noneMatch.trim() === '*' ||
480
+ noneMatch.split(',').some((item) => item.trim().replace(/^W\//, '') === tag);
481
+ }
482
+ else if (isRead && modifiedSince !== undefined) {
483
+ unchanged = modifiedTime <= Date.parse(modifiedSince);
484
+ }
469
485
  if (unchanged) {
470
486
  if (!isRead) {
471
487
  res.setHeader('content-length', 0);
@@ -474,15 +490,21 @@ export async function readToResponse(path, req, res, stat) {
474
490
  res.end();
475
491
  return;
476
492
  }
493
+ // --- 解析 Range 与 If-Range ---
477
494
  const contentType = mimeData.mime + charset;
478
495
  res.setHeader('content-type', contentType);
479
496
  const rangeHeader = req.headers['range'];
480
497
  const ifRange = req.headers['if-range'];
481
498
  // --- 日期必须精确匹配且至少早一秒;压缩与原始字节共享的日期不能作强校验,避免跨编码续传 ---
482
- const rangeMatches = ifRange === undefined || typeof ifRange === 'string' && !ifRange.includes('"') &&
483
- Date.parse(ifRange) === modifiedTime && modifiedTime <= Date.now() - 1_000 && !canCompress;
484
- const ranges = req.method === 'GET' && rangeHeader !== undefined &&
485
- rangeMatches ? parseFileRanges(rangeHeader, stat.size) : null;
499
+ const rangeMatches = ifRange === undefined || (typeof ifRange === 'string' &&
500
+ !ifRange.includes('"') &&
501
+ Date.parse(ifRange) === modifiedTime &&
502
+ modifiedTime <= Date.now() - 1_000 &&
503
+ !canCompress);
504
+ let ranges = null;
505
+ if (req.method === 'GET' && rangeHeader !== undefined && rangeMatches) {
506
+ ranges = parseFileRanges(rangeHeader, stat.size);
507
+ }
486
508
  if (ranges === false) {
487
509
  res.setHeader('content-range', `bytes */${stat.size}`);
488
510
  res.setHeader('content-length', 0);
@@ -490,19 +512,41 @@ export async function readToResponse(path, req, res, stat) {
490
512
  res.end();
491
513
  return;
492
514
  }
493
- // --- 判断客户端支持的压缩模式 ---
515
+ // --- 判断客户端支持的压缩模式(2 MiB 内缓冲压缩保留精确 Content-Length;大文件走流式压缩防 OOM) ---
494
516
  const encoding = req.headers['accept-encoding'] ?? '';
495
517
  if (ranges === null && canCompress && encoding !== '') {
496
- // --- 压缩 ---
497
- const compress = await lZlib.compress(encoding, await getContent(path));
498
- if (compress) {
499
- res.setHeader('content-encoding', compress.type);
500
- res.setHeader('content-length', Buffer.byteLength(compress.buffer));
501
- lCore.writeHead(res, 200);
502
- res.end(req.method === 'HEAD' ? '' : compress.buffer);
503
- return;
518
+ if (stat.size <= 2 * 1024 * 1024) {
519
+ const compress = await lZlib.compress(encoding, await getContent(path));
520
+ if (compress) {
521
+ res.setHeader('content-encoding', compress.type);
522
+ res.setHeader('content-length', Buffer.byteLength(compress.buffer));
523
+ lCore.writeHead(res, 200);
524
+ res.end(req.method === 'HEAD' ? '' : compress.buffer);
525
+ return;
526
+ }
527
+ }
528
+ else {
529
+ const compress = lZlib.createCompress(encoding);
530
+ if (compress) {
531
+ res.setHeader('content-encoding', compress.type);
532
+ res.removeHeader('content-length');
533
+ lCore.writeHead(res, 200);
534
+ if (req.method === 'HEAD') {
535
+ compress.compress.destroy();
536
+ res.end();
537
+ return;
538
+ }
539
+ try {
540
+ await stream.promises.pipeline(createReadStream(path), compress.compress, res instanceof http2.Http2ServerResponse ? (res.stream ?? res) : res);
541
+ }
542
+ catch {
543
+ res.destroy();
544
+ }
545
+ return;
546
+ }
504
547
  }
505
548
  }
549
+ // --- 设置完整响应或 206 部分响应头 ---
506
550
  let headers = [];
507
551
  let footer = Buffer.alloc(0);
508
552
  if (ranges !== null && ranges.length > 1) {
@@ -510,7 +554,8 @@ export async function readToResponse(path, req, res, stat) {
510
554
  headers = ranges.map((range) => Buffer.from(`--${boundary}\r\nContent-Type: ${contentType}\r\nContent-Range: bytes ${range.start}-${range.end}/${stat.size}\r\n\r\n`));
511
555
  footer = Buffer.from(`--${boundary}--\r\n`);
512
556
  res.setHeader('content-type', `multipart/byteranges; boundary=${boundary}`);
513
- res.setHeader('content-length', ranges.reduce((length, range, i) => length + headers[i].length + (range.end - range.start + 1) + 2, footer.length));
557
+ const totalLength = ranges.reduce((length, range, i) => length + headers[i].length + (range.end - range.start + 1) + 2, footer.length);
558
+ res.setHeader('content-length', totalLength);
514
559
  }
515
560
  else if (ranges !== null) {
516
561
  res.setHeader('content-range', `bytes ${ranges[0].start}-${ranges[0].end}/${stat.size}`);
@@ -524,8 +569,10 @@ export async function readToResponse(path, req, res, stat) {
524
569
  res.end();
525
570
  return;
526
571
  }
527
- const source = ranges !== null && ranges.length > 1 ?
528
- stream.Readable.from(readFileRanges(path, ranges, headers, footer)) : createReadStream(path, ranges?.[0]);
572
+ // --- 流式输出文件内容 ---
573
+ const source = ranges !== null && ranges.length > 1
574
+ ? stream.Readable.from(readFileRanges(path, ranges, headers, footer))
575
+ : createReadStream(path, ranges?.[0]);
529
576
  try {
530
577
  await stream.promises.pipeline(source, res instanceof http2.Http2ServerResponse ? (res.stream ?? res) : res);
531
578
  }