@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/sys/master.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * Date: 2019-5-2 21:03:42
4
4
  * Last: 2020-3-7 10:33:17, 2022-07-22 13:40:10, 2022-09-06 22:40:58, 2024-2-7 01:44:59, 2024-7-2 15:17:09, 2025-6-13 13:06:43, 2025-12-5 13:15:03, 2026-3-22 00:00:00, 2026-4-30 13:49:44
5
5
  */
6
+ // --- 系统 ---
6
7
  import cluster from 'cluster';
7
8
  import * as os from 'os';
8
9
  import * as fs from 'fs';
@@ -41,6 +42,29 @@ const replaceVhost = masterVhost.replace;
41
42
  * @returns true 表示所有文件可写入;false 表示整批拒绝,不修改旧配置
42
43
  */
43
44
  const isVhostFiles = masterVhost.isFiles;
45
+ /** --- kebab 子项目中仅允许部署的子文件夹名集合 --- */
46
+ const KEBAB_ALLOWED_DIRS = new Set(['ctr', 'data', 'stc', 'view', 'lib', 'abox']);
47
+ /** --- 常见开发、依赖、缓存、构建产物目录不参与部署 --- */
48
+ const DEPLOY_EXCLUDE_DIRS = new Set([
49
+ '.git',
50
+ '.svn',
51
+ '.hg',
52
+ '.vscode',
53
+ '.idea',
54
+ '.history',
55
+ 'node_modules',
56
+ 'bower_components',
57
+ '.cache',
58
+ '.parcel-cache',
59
+ '.turbo',
60
+ '.next',
61
+ '.nuxt',
62
+ '.vite',
63
+ 'coverage',
64
+ '.nyc_output',
65
+ 'tmp',
66
+ 'temp',
67
+ ]);
44
68
  /** --- 当前运行中的子进程列表 --- */
45
69
  const workerList = {};
46
70
  /** --- 是否已开始停止整个服务 --- */
@@ -101,6 +125,27 @@ async function resolvePathInside(rootPath, inputPath) {
101
125
  }
102
126
  }
103
127
  }
128
+ /**
129
+ * --- 解析并校验目标目录是否位于根目录内(同时兼容相对路径与根目录内的绝对路径) ---
130
+ * @param rootPath 限定的根目录
131
+ * @param inputPath 待校验目录路径
132
+ */
133
+ async function resolveDirInside(rootPath, inputPath) {
134
+ if ((typeof inputPath !== 'string') || inputPath.includes('\0')) {
135
+ return null;
136
+ }
137
+ const rootReal = await fs.promises.realpath(rootPath);
138
+ if (path.isAbsolute(inputPath)) {
139
+ try {
140
+ const targetReal = await fs.promises.realpath(inputPath);
141
+ return isPathInside(rootReal, targetReal) ? targetReal : null;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ return resolvePathInside(rootReal, inputPath);
148
+ }
104
149
  /**
105
150
  * --- 统一 ZIP 文件路径中的斜杠,并拒绝 .. 等不安全写法 ---
106
151
  * @param archivePath ZIP 内的原始路径
@@ -304,6 +349,10 @@ function createRpcListener() {
304
349
  break;
305
350
  }
306
351
  case 'global': {
352
+ if (typeof msg.key !== 'string' || msg.key === '__proto__' || msg.key === 'constructor' || msg.key === 'prototype') {
353
+ res.end('Invalid key');
354
+ return;
355
+ }
307
356
  // --- 为所有子进程更新 global 变量 ---
308
357
  for (const pid in workerList) {
309
358
  workerList[pid].worker.send({
@@ -350,12 +399,17 @@ function createRpcListener() {
350
399
  return;
351
400
  }
352
401
  case 'npm': {
353
- // --- 执行 npm install 操作 ---
402
+ // --- 执行 npm install 操作(路径必须位于项目根目录内) ---
354
403
  if (!msg.path || typeof msg.path !== 'string') {
355
404
  res.end('Invalid path');
356
405
  return;
357
406
  }
358
- if (!await lFs.isDir(msg.path)) {
407
+ const npmPath = await resolveDirInside(kebab.ROOT_CWD, msg.path);
408
+ if (!npmPath) {
409
+ res.end('Invalid path');
410
+ return;
411
+ }
412
+ if (!await lFs.isDir(npmPath)) {
359
413
  res.end('Path not found');
360
414
  return;
361
415
  }
@@ -363,7 +417,7 @@ function createRpcListener() {
363
417
  const npmTimeout = 300_000;
364
418
  const npmDeadline = Date.now() + npmTimeout;
365
419
  let rtn = await lCore.exec('npm i --omit=dev', {
366
- 'cwd': msg.path,
420
+ 'cwd': npmPath,
367
421
  'timeout': npmTimeout,
368
422
  });
369
423
  if (rtn === false) {
@@ -371,7 +425,7 @@ function createRpcListener() {
371
425
  const remaining = npmDeadline - Date.now();
372
426
  if (remaining > 0) {
373
427
  rtn = await lCore.exec('npm i --omit=dev --legacy-peer-deps', {
374
- 'cwd': msg.path,
428
+ 'cwd': npmPath,
375
429
  'timeout': remaining,
376
430
  });
377
431
  }
@@ -433,6 +487,11 @@ function createRpcListener() {
433
487
  res.end('Invalid content');
434
488
  return;
435
489
  }
490
+ const parsedPkg = lText.parseJson(msg.content);
491
+ if (!parsedPkg || typeof parsedPkg !== 'object' || Array.isArray(parsedPkg)) {
492
+ res.end('Invalid content');
493
+ return;
494
+ }
436
495
  const packageFile = kebab.ROOT_CWD + 'package.json';
437
496
  if (!await lFs.isFile(packageFile)) {
438
497
  res.end('package.json not found');
@@ -522,35 +581,28 @@ function createRpcListener() {
522
581
  ls[normalizedPath] = rawList[archivePath];
523
582
  }
524
583
  // --- 预扫描:收集 .cga 锁定目录和 kebab 子项目目录 ---
525
- /** --- .cga 锁定的目录集合,key 格式为"父路径/目录名/"(不含开头/,含尾部/),例如 "www/pika/" --- */
584
+ /** --- .cga 锁定的目录集合,格式如 "www/pika/" --- */
526
585
  const cgaLockedDirs = new Set();
527
- /** --- 含有 kebab.json 的目录路径集合(不含开头/,含尾部/,根目录为空字符串) --- */
586
+ /** --- 含有 kebab.json 的目录集合,格式如 "www/pika/",根目录为空字符串 --- */
528
587
  const kebabProjectDirs = new Set();
529
- /** --- 本次部署涉及到的目录路径集合(不含开头/,含尾部/,根目录为空字符串) --- */
588
+ /** --- 本次部署涉及的目录集合 --- */
530
589
  const touchedDirs = new Set();
531
590
  for (const scanPath in ls) {
532
- /** --- 纯路径中最后一个 / 的位置索引 --- */
533
591
  const scanLio = scanPath.lastIndexOf('/');
534
- /** --- 纯路径,不以 / 开头,以 / 结尾,若是根路径就是空字符串,例如 "www/pika/" --- */
535
592
  const scanPat = scanPath.slice(1, scanLio + 1);
536
- /** --- 纯文件名,例如 "index.ts" 或 "pika.cga" --- */
537
593
  const scanFname = scanPath.slice(scanLio + 1);
538
594
  touchedDirs.add(scanPat);
539
- if (scanFname.endsWith('.cga')) {
540
- // --- 记录 .cga 锁定的同级目录(去掉 .cga 后缀的名字即为被锁定的目录名)---
541
- cgaLockedDirs.add(scanPat + scanFname.slice(0, -4) + '/');
595
+ if (scanFname.toLowerCase().endsWith('.cga')) {
596
+ cgaLockedDirs.add((scanPat + scanFname.slice(0, -4) + '/').toLowerCase());
542
597
  }
543
- if (scanFname === 'kebab.json') {
544
- // --- 记录含有 kebab.json 的目录(即 kebab 子项目根目录)---
598
+ if (scanFname.toLowerCase() === 'kebab.json') {
545
599
  kebabProjectDirs.add(scanPat);
546
600
  }
547
601
  }
548
602
  // --- 补充扫描目标目录中现存的 kebab.json,兼容压缩包未携带 kebab.json 的情况 ---
549
603
  for (const dir of touchedDirs) {
550
- /** --- 把目录拆成各级目录名,先检查当前目录,再一层层往上找 --- */
551
604
  const dirs = dir ? dir.split('/').filter(Boolean) : [];
552
605
  for (let i = dirs.length; i >= 0; --i) {
553
- /** --- 当前要检查的目录路径,不含开头/,含尾部/,根目录为空字符串 --- */
554
606
  const currentDir = i ? dirs.slice(0, i).join('/') + '/' : '';
555
607
  if (kebabProjectDirs.has(currentDir)) {
556
608
  break;
@@ -561,68 +613,42 @@ function createRpcListener() {
561
613
  }
562
614
  }
563
615
  }
564
- /** --- kebab 子项目中仅允许部署的子文件夹名集合 --- */
565
- const KEBAB_ALLOWED_DIRS = new Set(['ctr', 'data', 'stc', 'view', 'lib', 'abox']);
566
- /** --- 常见开发、依赖、缓存、构建产物目录不参与部署 --- */
567
- const DEPLOY_EXCLUDE_DIRS = new Set([
568
- '.git',
569
- '.svn',
570
- '.hg',
571
- '.vscode',
572
- '.idea',
573
- '.history',
574
- 'node_modules',
575
- 'bower_components',
576
- '.cache',
577
- '.parcel-cache',
578
- '.turbo',
579
- '.next',
580
- '.nuxt',
581
- '.vite',
582
- 'coverage',
583
- '.nyc_output',
584
- 'tmp',
585
- 'temp',
586
- ]);
616
+ // --- 按安全与过滤规则逐项写入文件(统一小写比对防止大小写绕过) ---
587
617
  for (const archivePath in ls) {
588
- /** --- 纯路径中最后一个 / 的位置索引 --- */
589
618
  const lio = archivePath.lastIndexOf('/');
590
- /** --- 纯路径,不以 / 开头,以 / 结尾,若是根路径就是空字符串,例如 "www/pika/ctr/" --- */
591
619
  const pat = archivePath.slice(1, lio + 1);
592
- /** --- 纯文件名,例如 "api.js" --- */
593
620
  const fname = archivePath.slice(lio + 1);
621
+ const fnameLower = fname.toLowerCase();
594
622
  const dirs = archivePath.slice(1).split('/').slice(0, -1);
595
- if (dirs.some(seg => DEPLOY_EXCLUDE_DIRS.has(seg))) {
596
- // --- 开发、依赖、缓存、构建产物目录不覆盖 ---
623
+ const dirsLower = dirs.map(seg => seg.toLowerCase());
624
+ if (dirsLower.some(seg => DEPLOY_EXCLUDE_DIRS.has(seg))) {
597
625
  continue;
598
626
  }
599
- if (dirs.some((seg, index) => seg === 'abox' && ['test', 'tests'].includes(dirs[index + 1]))) {
627
+ if (dirsLower.some((seg, index) => seg === 'abox' && ['test', 'tests'].includes(dirsLower[index + 1]))) {
600
628
  // --- abox 运行代码参与部署,测试目录不进入线上目录 ---
601
629
  continue;
602
630
  }
603
- if (fname === 'kebab.json' && hasSensitiveConfig(ls[archivePath])) {
604
- // --- 包含密码或密钥的 kebab.json 不覆盖,避免部署包覆盖现有敏感配置 ---
605
- continue;
606
- }
607
- if (pat === 'conf/' && fname === 'config.json') {
608
- // --- 全局配置文件不能覆盖 ---
631
+ if (fnameLower === 'kebab.json' && hasSensitiveConfig(ls[archivePath])) {
632
+ // --- 包含密码或密钥的 kebab.json 不覆盖 ---
609
633
  continue;
610
634
  }
611
- if (fname.endsWith('.js.map') || fname.endsWith('.ts') || fname.endsWith('.tsx') || fname.endsWith('.scss') || fname.endsWith('.gitignore') || fname.endsWith('.DS_Store')) {
612
- // --- 测试或开发文件不覆盖 ---
635
+ if (pat.toLowerCase() === 'conf/' && fnameLower === 'config.json') {
613
636
  continue;
614
637
  }
615
- if (fname === 'AGENTS.md') {
616
- // --- 排除文件不部署 ---
638
+ if (fnameLower.endsWith('.js.map') ||
639
+ fnameLower.endsWith('.ts') ||
640
+ fnameLower.endsWith('.tsx') ||
641
+ fnameLower.endsWith('.scss') ||
642
+ fnameLower.endsWith('.gitignore') ||
643
+ fnameLower.endsWith('.ds_store') ||
644
+ fnameLower === 'agents.md') {
617
645
  continue;
618
646
  }
619
- // --- 规则 1:若同级目录存在 xxx.cga,则 xxx 目录下所有内容不部署 ---
647
+ // --- 规则 1:若同级或上级目录存在 xxx.cga,则 xxx 目录下所有内容不部署 ---
620
648
  if (pat) {
621
- /** --- 当前目录或上级目录是否有同名 .cga 文件 --- */
622
649
  let cgaBlocked = false;
623
- /** --- 逐层拼出的目录路径,如 a/、a/b/,检查是否有同名 .cga 文件 --- */
624
650
  let accumulated = '';
625
- for (const seg of pat.split('/').filter(Boolean)) {
651
+ for (const seg of pat.toLowerCase().split('/').filter(Boolean)) {
626
652
  accumulated += seg + '/';
627
653
  if (cgaLockedDirs.has(accumulated)) {
628
654
  cgaBlocked = true;
@@ -633,26 +659,20 @@ function createRpcListener() {
633
659
  continue;
634
660
  }
635
661
  }
636
- // --- 规则 2:kebab 子项目目录中,仅允许部署 ctr/data/stc/view/lib/abox 子文件夹内的内容 ---
662
+ // --- 规则 2:kebab 子项目目录中,仅允许部署 ctr/data/stc/view/lib/abox 子目录 ---
637
663
  if (kebabProjectDirs.size > 0) {
638
- // --- 同时属于多个 Kebab 项目时,按最外层项目的部署规则检查 ---
639
- // --- 例如根项目不允许 backup/,backup/ 自带 kebab.json 也不能绕过 ---
640
- /** --- 当前文件所属的最外层 Kebab 项目目录,找不到时为 null --- */
664
+ // --- 同时属于多个 Kebab 项目时,按最外层项目规则检查 ---
641
665
  let shortestMatch = null;
642
666
  for (const kdir of kebabProjectDirs) {
643
- /** --- kdir 是否比已选的项目目录更靠外(路径更短)--- */
644
- const isShallower = shortestMatch === null || kdir.length < shortestMatch.length;
645
- if (pat.startsWith(kdir) && isShallower) {
667
+ if (pat.startsWith(kdir) &&
668
+ (shortestMatch === null || kdir.length < shortestMatch.length)) {
646
669
  shortestMatch = kdir;
647
670
  }
648
671
  }
649
672
  if (shortestMatch !== null) {
650
- // --- 取相对于 kebab 项目目录的路径,检查第一级子目录 ---
651
- /** --- 相对路径,例如若 pat 为 "www/pika/ctr/" 且 shortestMatch 为 "www/pika/",则 relPath 为 "ctr/" --- */
652
673
  const relPath = pat.slice(shortestMatch.length);
653
674
  if (relPath) {
654
- /** --- 路径的第一级子目录名,例如 "ctr" 或 "data",用于判断是否在允许列表中 --- */
655
- const firstSeg = relPath.split('/')[0];
675
+ const firstSeg = relPath.split('/')[0].toLowerCase();
656
676
  if (!KEBAB_ALLOWED_DIRS.has(firstSeg)) {
657
677
  continue;
658
678
  }
@@ -783,11 +803,7 @@ function createRpcListener() {
783
803
  const list = [];
784
804
  let total = 0;
785
805
  let skipHeader = format === 'csv';
786
- /**
787
- * --- 统计匹配行数并取出当前页,跳过 CSV 表头 ---
788
- * @param line 不含换行符的日志行
789
- * @returns 无返回值
790
- */
806
+ // --- 统计匹配行数并取出当前页,跳过 CSV 表头 ---
791
807
  const consumeLine = (line) => {
792
808
  if (skipHeader) {
793
809
  skipHeader = false;
@@ -840,21 +856,30 @@ function createRpcListener() {
840
856
  return;
841
857
  }
842
858
  case 'monitor-events': {
859
+ // --- 按天分页查询监控事件摘要 ---
843
860
  const result = await sMonitorFiles.getEvents(path.join(kebab.LOG_CWD, 'monitor'), msg.path ?? lTime.format(null, 'Y/m/d'), msg.offset ?? 0, msg.limit ?? 20);
844
861
  res.setHeader('cache-control', 'no-store');
845
- res.end(lText.stringifyJson(result === false ? { 'result': 0 } : { 'result': 1, ...result }));
862
+ res.end(lText.stringifyJson(result === false ? { 'result': 0 } : {
863
+ 'result': 1,
864
+ ...result,
865
+ }));
846
866
  return;
847
867
  }
848
868
  case 'monitor-event': {
869
+ // --- 查询单条监控事件详情与文件清单 ---
849
870
  const data = await sMonitorFiles.getEvent(path.join(kebab.LOG_CWD, 'monitor'), msg.path);
850
871
  res.setHeader('cache-control', 'no-store');
851
- res.end(lText.stringifyJson(data === false ? { 'result': 0 } : { 'result': 1, data }));
872
+ res.end(lText.stringifyJson(data === false ? { 'result': 0 } : {
873
+ 'result': 1,
874
+ 'data': data,
875
+ }));
852
876
  return;
853
877
  }
854
878
  case 'monitor-file': {
879
+ // --- 校验目标诊断文件及预览权限 ---
855
880
  const file = await sMonitorFiles.getFile(path.join(kebab.LOG_CWD, 'monitor'), msg.path);
856
881
  res.setHeader('cache-control', 'no-store');
857
- if (file === false || msg.preview !== undefined && typeof msg.preview !== 'boolean') {
882
+ if (file === false || (msg.preview !== undefined && typeof msg.preview !== 'boolean')) {
858
883
  res.writeHead(400);
859
884
  res.end();
860
885
  return;
@@ -869,9 +894,12 @@ function createRpcListener() {
869
894
  res.end();
870
895
  return;
871
896
  }
897
+ // --- 设置响应头并流式输出文件 ---
872
898
  let contentType = 'application/octet-stream';
873
899
  if (msg.preview) {
874
- contentType = file.info.preview === 'json' ? 'application/json; charset=utf-8' : 'text/plain; charset=utf-8';
900
+ contentType = file.info.preview === 'json'
901
+ ? 'application/json; charset=utf-8'
902
+ : 'text/plain; charset=utf-8';
875
903
  }
876
904
  res.setHeader('content-type', contentType);
877
905
  res.setHeader('x-content-type-options', 'nosniff');
@@ -1120,6 +1148,9 @@ async function createChildProcess(cpu) {
1120
1148
  break;
1121
1149
  }
1122
1150
  case 'global': {
1151
+ if (typeof msg.key !== 'string' || msg.key === '__proto__' || msg.key === 'constructor' || msg.key === 'prototype') {
1152
+ break;
1153
+ }
1123
1154
  // --- 为所有子进程更新 global 变量 ---
1124
1155
  for (const pid in workerList) {
1125
1156
  workerList[pid].worker.send({
package/sys/mod.d.ts CHANGED
@@ -11,8 +11,27 @@ import * as kebab from '#kebab/index.js';
11
11
  export type TOnlyProperties<T> = {
12
12
  [K in keyof T as T[K] extends (...args: any[]) => any ? never : K]: T[K];
13
13
  };
14
+ /** --- 由 SELECT 决定字段的原生查询行 --- */
15
+ export type TModRow = Record<string, kebab.Json>;
16
+ /** --- 按条件查询单条记录的选项 --- */
17
+ export interface IModOneOptions {
18
+ /** --- 所属控制器,用于错误日志 --- */
19
+ 'ctr'?: sCtr.Ctr;
20
+ /** --- 加锁时确保 WHERE 条件命中索引,以免锁定过多记录 --- */
21
+ 'lock'?: boolean;
22
+ /** --- MySQL 表前缀或 PostgreSQL Schema 名 --- */
23
+ 'pre'?: string;
24
+ /** --- 分表后缀 --- */
25
+ 'index'?: string | string[];
26
+ /** --- 指定查询字段 --- */
27
+ 'select'?: string | string[];
28
+ /** --- 排序字段与方向 --- */
29
+ 'by'?: [string | string[], 'DESC' | 'ASC'];
30
+ /** --- SQL 优化提示 --- */
31
+ 'hint'?: string;
32
+ }
14
33
  /** --- 一批游标查询结果,hasMore 表示扫描方向上还有记录 --- */
15
- export interface ICursorPage<T extends Record<string, unknown> = Record<string, unknown>> {
34
+ export interface ICursorPage<T extends object = Record<string, unknown>> {
16
35
  'list': T[];
17
36
  'hasMore': boolean;
18
37
  'next': lSql.TCursorValue[] | null;
@@ -26,8 +45,10 @@ export declare class Rows<T extends Mod> implements IRows<T> {
26
45
  get length(): number;
27
46
  /** --- 通过索引获取一个对象 --- */
28
47
  item(index: number): T;
29
- /** --- 转换为数组对象,获取的是新创建的数组 --- */
30
- toArray(): Array<Record<string, any>>;
48
+ /** --- 将模型转换为普通对象数组 --- */
49
+ toArray(): TModRow[];
50
+ /** --- 将模型转换为指定行类型的普通对象数组 --- */
51
+ toArray<TRow extends object>(): TRow[];
31
52
  /** --- 根据规则筛掉项,predicate 返回 true 代表保留 --- */
32
53
  filter(predicate: (value: T, index: number) => boolean): Rows<T>;
33
54
  /** --- 重塑对象内容为数组 --- */
@@ -227,7 +248,7 @@ export default class Mod {
227
248
  'list': string[];
228
249
  };
229
250
  'hint'?: string;
230
- }): T & Record<string, any>;
251
+ }): T;
231
252
  /**
232
253
  * --- 通过 where 条件获取模型 ---
233
254
  * @param db 数据库对象
@@ -244,7 +265,7 @@ export default class Mod {
244
265
  'list': string[];
245
266
  };
246
267
  'hint'?: string;
247
- }): T & Record<string, any>;
268
+ }): T;
248
269
  /**
249
270
  * --- 获取创建对象,通常用于新建数据库条目 ---
250
271
  * @param db 数据库对象
@@ -270,40 +291,28 @@ export default class Mod {
270
291
  'key'?: boolean;
271
292
  'hint'?: string;
272
293
  }): Promise<false | null | (T & Record<string, any>)>;
273
- static one(db: lDb.Pool | lDb.Transaction, s: string | kebab.Json, opt: {
274
- 'ctr'?: sCtr.Ctr;
275
- 'lock'?: boolean;
276
- 'pre'?: string;
277
- 'index'?: string | string[];
278
- 'select'?: string | string[];
279
- 'by'?: [string | string[], 'DESC' | 'ASC'];
280
- 'hint'?: string;
294
+ /** --- 按条件读取一条原生记录,查询失败返回 false,未找到返回 null --- */
295
+ static one(db: lDb.Pool | lDb.Transaction, s: string | kebab.Json, opt: IModOneOptions & {
281
296
  'array': true;
282
- }): Promise<false | null | Record<string, any>>;
283
- static one<T extends Mod>(db: lDb.Pool | lDb.Transaction, s: string | kebab.Json, opt?: {
284
- 'ctr'?: sCtr.Ctr;
285
- 'lock'?: boolean;
286
- 'pre'?: string;
287
- 'index'?: string | string[];
288
- 'select'?: string | string[];
289
- 'by'?: [string | string[], 'DESC' | 'ASC'];
290
- 'hint'?: string;
297
+ }): Promise<false | null | TModRow>;
298
+ /** --- 按条件读取一个模型实例,查询失败返回 false,未找到返回 null --- */
299
+ static one<T extends Mod>(db: lDb.Pool | lDb.Transaction, s: string | kebab.Json, opt?: IModOneOptions & {
291
300
  'array'?: false;
292
- }): Promise<false | null | (T & Record<string, any>)>;
301
+ }): Promise<false | null | (T & TModRow)>;
302
+ /** --- 按条件读取一条指定类型的原生记录,查询失败返回 false,未找到返回 null --- */
303
+ static one<TRow extends object>(db: lDb.Pool | lDb.Transaction, s: string | kebab.Json, opt: IModOneOptions & {
304
+ 'array': true;
305
+ }): Promise<false | null | TRow>;
293
306
  /**
294
307
  * --- 通过 where 条件筛选单条数据返回原生对象 ---
295
308
  * @param db 数据库对象
296
309
  * @param s 筛选条件数组或字符串
297
- * @param opt 选项(opt.pre: MySQL 表前缀/PostgreSQL Schema 名)
310
+ * @param opt 查询和加锁选项
311
+ * @returns 原生对象,查询失败返回 false,未找到返回 null
298
312
  */
299
- static oneArray(db: lDb.Pool | lDb.Transaction, s: string | kebab.Json, opt?: {
300
- 'ctr'?: sCtr.Ctr;
301
- 'lock'?: boolean;
302
- 'pre'?: string;
303
- 'index'?: string | string[];
304
- 'select'?: string | string[];
305
- 'hint'?: string;
306
- }): Promise<false | null | Record<string, any>>;
313
+ static oneArray(db: lDb.Pool | lDb.Transaction, s: string | kebab.Json, opt?: Omit<IModOneOptions, 'by'>): Promise<false | null | TModRow>;
314
+ /** --- 按条件读取一条指定类型的原生记录,查询失败返回 false,未找到返回 null --- */
315
+ static oneArray<TRow extends object>(db: lDb.Pool | lDb.Transaction, s: string | kebab.Json, opt?: Omit<IModOneOptions, 'by'>): Promise<false | null | TRow>;
307
316
  /**
308
317
  * --- 根据 where 条件获取主键值列表 ---
309
318
  * @param db 数据库对象
@@ -316,10 +325,13 @@ export default class Mod {
316
325
  'index'?: string;
317
326
  }): Promise<any[] | false>;
318
327
  /**
319
- * --- 将 key val 组成的数据列表转换为原生对象模式,获取的是新创建的数组 ---
320
- * @param obj 要转换的 kv 数据列表
328
+ * --- 将模型字典转换为普通对象字典,沿用原有键 ---
329
+ * @param obj 要转换的模型字典
330
+ * @returns 转换后的普通对象字典
321
331
  */
322
- static toArrayByRecord<T extends Mod>(obj: Record<string, T>): Record<string, Record<string, any>>;
332
+ static toArrayByRecord<T extends Mod>(obj: Record<string, T>): Record<string, TModRow>;
333
+ /** --- 将模型字典转换为指定行类型的普通对象字典 --- */
334
+ static toArrayByRecord<TRow extends object>(obj: Record<string, Mod>): Record<string, TRow>;
323
335
  /**
324
336
  * --- 构造包含主键和分区字段的 WHERE 条件 ---
325
337
  * @returns 主键及分区字段条件,缺少字段时返回 false
@@ -334,10 +346,13 @@ export default class Mod {
334
346
  set<T extends this, TK extends keyof T>(n: Record<TK, T[TK] | undefined>): void;
335
347
  set<T extends this, TK extends keyof T>(n: TK, v: T[TK]): void;
336
348
  /**
337
- * --- 获取一个字段值
349
+ * --- 获取一个已加载的字段值 ---
338
350
  * @param n 字段名
351
+ * @returns 字段值,未加载时返回 undefined
339
352
  */
340
- get(n: string): any;
353
+ get(n: string): kebab.Json;
354
+ /** --- 按指定类型获取一个已加载的字段值,未加载时返回 undefined --- */
355
+ get<T>(n: string): T | undefined;
341
356
  /**
342
357
  * --- 收集待写字段,保留模型内的原始 JSON 值 ---
343
358
  * @returns 独立的 SQL 数据对象
@@ -373,13 +388,32 @@ export default class Mod {
373
388
  * @returns 是否成功,缺少定位字段、记录不存在或删除失败返回 false
374
389
  */
375
390
  remove(): Promise<boolean>;
376
- first(lock: boolean, array: true): Promise<false | null | Record<string, any>>;
377
- first(lock?: boolean, array?: false): Promise<false | null | (this & Record<string, any>)>;
391
+ /** --- 获取第一条原生记录,查询失败返回 false,未找到返回 null --- */
392
+ first(lock: boolean, array: true): Promise<false | null | TModRow>;
393
+ /** --- 获取第一个模型实例,查询失败返回 false,未找到返回 null --- */
394
+ first(lock?: boolean, array?: false): Promise<false | null | (this & TModRow)>;
395
+ /**
396
+ * --- 获取指定类型的第一条原生记录 ---
397
+ * @param lock 是否加锁
398
+ * @param array 传入 true 返回原生记录
399
+ * @returns 原生记录,查询失败返回 false,未找到返回 null
400
+ */
401
+ first<TRow extends object>(lock: boolean, array: true): Promise<false | null | TRow>;
402
+ /**
403
+ * --- 获取第一个模型实例,并为查询附加的字段指定类型 ---
404
+ * @param lock 是否加锁
405
+ * @param array 省略或传入 false 返回模型实例
406
+ * @returns 模型实例,查询失败返回 false,未找到返回 null
407
+ */
408
+ first<TExtra extends object>(lock?: boolean, array?: false): Promise<false | null | (this & TExtra)>;
378
409
  /**
379
410
  * --- 获取数据库第一个原生对象 ---
380
411
  * @param lock 是否加锁
412
+ * @returns 原生对象,查询失败返回 false,未找到返回 null
381
413
  */
382
- firstArray(lock?: boolean): Promise<Record<string, any> | false | null>;
414
+ firstArray(lock?: boolean): Promise<false | null | TModRow>;
415
+ /** --- 获取指定类型的第一条原生记录,查询失败返回 false,未找到返回 null --- */
416
+ firstArray<TRow extends object>(lock?: boolean): Promise<false | null | TRow>;
383
417
  /**
384
418
  * --- 联合查询表数据 ---
385
419
  * @param f 要联合查询的表列表、单个表、sql 对象
@@ -391,10 +425,34 @@ export default class Mod {
391
425
  * @param f 要联合查询的表列表、单个表、sql 对象
392
426
  */
393
427
  unionAll(f: lSql.Sql | string | IModUnionItem | string[] | IModUnionItem[]): this;
394
- all(): Promise<false | Rows<this>>;
395
- all(key: string): Promise<false | Record<string, this>>;
396
- allArray(): Promise<false | Array<Record<string, any>>>;
397
- allArray(key: string): Promise<false | Record<string, Record<string, any>>>;
428
+ /** --- 查询模型列表,查询失败返回 false --- */
429
+ all(): Promise<false | Rows<this & TModRow>>;
430
+ /**
431
+ * --- 查询模型字典,查询失败返回 false ---
432
+ * @param key 用作字典键的结果字段
433
+ */
434
+ all(key: string): Promise<false | Record<string, this & TModRow>>;
435
+ /** --- 查询模型列表,并为查询附加的字段指定类型,查询失败返回 false --- */
436
+ all<TExtra extends object>(): Promise<false | Rows<this & TExtra>>;
437
+ /**
438
+ * --- 查询模型字典,并为查询附加的字段指定类型,查询失败返回 false ---
439
+ * @param key 用作字典键的结果字段
440
+ */
441
+ all<TExtra extends object>(key: string): Promise<false | Record<string, this & TExtra>>;
442
+ /** --- 查询原生行列表,查询失败返回 false --- */
443
+ allArray(): Promise<false | TModRow[]>;
444
+ /**
445
+ * --- 查询原生行字典,查询失败返回 false ---
446
+ * @param key 用作字典键的结果字段
447
+ */
448
+ allArray(key: string): Promise<false | Record<string, TModRow>>;
449
+ /** --- 查询指定行类型的原生行列表,查询失败返回 false --- */
450
+ allArray<TRow extends object>(): Promise<false | TRow[]>;
451
+ /**
452
+ * --- 查询指定行类型的原生行字典,查询失败返回 false ---
453
+ * @param key 用作字典键的结果字段
454
+ */
455
+ allArray<TRow extends object>(key: string): Promise<false | Record<string, TRow>>;
398
456
  explain(all?: false): Promise<false | string>;
399
457
  explain(all: true): Promise<false | Record<string, any>>;
400
458
  /** --- 获取 contain 补查时使用的 where key(联表且无前缀时自动补主表前缀) --- */
@@ -422,7 +480,7 @@ export default class Mod {
422
480
  * @param opt.before 是否读取边界前一批,须提供 cursor
423
481
  * @returns 列表、首末行游标和扫描方向上的 hasMore,数据库错误返回 false
424
482
  */
425
- allCursor<T extends Record<string, unknown> = Record<string, unknown>>(count: number, opt: {
483
+ allCursor<T extends object = Record<string, unknown>>(count: number, opt: {
426
484
  'by': string | string[];
427
485
  'keys'?: string[];
428
486
  'order'?: 'DESC' | 'ASC';
@@ -576,16 +634,18 @@ export default class Mod {
576
634
  * @param data 数据
577
635
  */
578
636
  format(sql?: string, data?: any[]): string;
579
- /**
580
- * --- 获取值对象,获取的是新创建的数组 ---
581
- */
582
- toArray<TC extends abstract new (...args: any) => any>(): TOnlyProperties<InstanceType<TC>> & Record<string, any>;
637
+ /** --- 将已加载和已设置的字段复制为一个普通对象 --- */
638
+ toArray(): TModRow;
639
+ /** --- 将字段复制为普通对象,按指定构造器的实例属性提供类型 --- */
640
+ toArray<TC extends abstract new (...args: never[]) => object>(): TOnlyProperties<InstanceType<TC>> & TModRow;
641
+ /** --- 将字段复制为指定类型的普通对象 --- */
642
+ toArray<TRow extends object>(): TRow;
583
643
  /**
584
644
  * --- 获取当前设置要提交的数据 ---
585
645
  */
586
646
  updates(): Record<string, any>;
587
647
  /**
588
- * --- 当前是否设置了未保存 --=
648
+ * --- 当前是否设置了未保存 ---
589
649
  */
590
650
  unsaved(): boolean;
591
651
  /**
@@ -599,8 +659,9 @@ export default class Mod {
599
659
  */
600
660
  protected _keyGenerator(): string;
601
661
  }
662
+ /** --- 模型记录集合接口 --- */
602
663
  export interface IRows<T> extends Iterable<T> {
603
- readonly length: number;
664
+ readonly 'length': number;
604
665
  item(index: number): T;
605
666
  toArray(): Array<Record<string, any>>;
606
667
  }