dsh-git-push 0.0.0-stage → 2.8.6

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 (279) hide show
  1. package/.auditignore +30 -0
  2. package/.gitignore +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1486 -2
  5. package/cli.mjs +360 -0
  6. package/cordis.patch.yml +14 -0
  7. package/lib/ARCHITECTURE.md +34 -0
  8. package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
  9. package/lib/app/apply.js +275 -0
  10. package/lib/app/audit-api.js +158 -0
  11. package/lib/app/command-registry.js +266 -0
  12. package/lib/app/constants.js +16 -0
  13. package/lib/app/handlers/account.js +166 -0
  14. package/lib/app/handlers/clone.js +168 -0
  15. package/lib/app/handlers/http-constants.js +9 -0
  16. package/lib/app/handlers/identity-rewrite.js +94 -0
  17. package/lib/app/handlers/meta.js +175 -0
  18. package/lib/app/handlers/npm.js +169 -0
  19. package/lib/app/handlers/repo-actions.js +143 -0
  20. package/lib/app/handlers/repos.js +231 -0
  21. package/lib/app/handlers/settings.js +62 -0
  22. package/lib/app/host-doc-checks.js +25 -0
  23. package/lib/app/http-handlers.js +131 -0
  24. package/lib/app/index.js +30 -0
  25. package/lib/app/inject-text.js +192 -0
  26. package/lib/app/scan-root.js +23 -0
  27. package/lib/app/schema.js +150 -0
  28. package/lib/app/settings-bridge.js +167 -0
  29. package/lib/app/slash-commands.js +395 -0
  30. package/lib/app/slot-stats.js +35 -0
  31. package/lib/app/tool-call.js +672 -0
  32. package/lib/app/tools.js +34 -0
  33. package/lib/ast/brace.js +105 -0
  34. package/lib/ast/callgraph.js +135 -0
  35. package/lib/ast/code-lines.js +114 -0
  36. package/lib/ast/consts.js +12 -0
  37. package/lib/ast/control-flow.js +461 -0
  38. package/lib/ast/credential.js +199 -0
  39. package/lib/ast/dataflow.js +274 -0
  40. package/lib/ast/dup-code.js +165 -0
  41. package/lib/ast/index.js +36 -0
  42. package/lib/ast/io-risk-const.js +95 -0
  43. package/lib/ast/io-risk-fn.js +208 -0
  44. package/lib/ast/io-risk-loop.js +308 -0
  45. package/lib/ast/io-risk.js +314 -0
  46. package/lib/ast/lang.js +156 -0
  47. package/lib/ast/line-count.js +52 -0
  48. package/lib/ast/magic-number.js +272 -0
  49. package/lib/ast/naming.js +284 -0
  50. package/lib/ast/perf.js +472 -0
  51. package/lib/ast/scope.js +241 -0
  52. package/lib/ast/shell.js +131 -0
  53. package/lib/ast/size.js +378 -0
  54. package/lib/ast/symbol-index.js +399 -0
  55. package/lib/ast/tokenizer.js +341 -0
  56. package/lib/audit/analysis-coverage.js +98 -0
  57. package/lib/audit/audit-file.js +182 -0
  58. package/lib/audit/checks.js +17 -0
  59. package/lib/audit/client-entry.js +93 -0
  60. package/lib/audit/collector.js +477 -0
  61. package/lib/audit/ext-runner.js +80 -0
  62. package/lib/audit/file-context.js +138 -0
  63. package/lib/audit/finding.js +50 -0
  64. package/lib/audit/gitignore-match.js +113 -0
  65. package/lib/audit/glob.js +63 -0
  66. package/lib/audit/history-report.js +100 -0
  67. package/lib/audit/history.js +126 -0
  68. package/lib/audit/ignore-blind.js +101 -0
  69. package/lib/audit/index.js +33 -0
  70. package/lib/audit/orchestrate.js +476 -0
  71. package/lib/audit/public.js +24 -0
  72. package/lib/audit/repo-level.js +30 -0
  73. package/lib/audit/report-yaml.js +86 -0
  74. package/lib/audit/slot.js +65 -0
  75. package/lib/audit-defaults.js +18 -0
  76. package/lib/audit-rules/audit-rules-comment.yml +247 -0
  77. package/lib/audit-rules/audit-rules-cpp.yml +22 -0
  78. package/lib/audit-rules/audit-rules-docs.yml +32 -0
  79. package/lib/audit-rules/audit-rules-dsh.yml +162 -0
  80. package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
  81. package/lib/audit-rules/audit-rules-folder.yml +99 -0
  82. package/lib/audit-rules/audit-rules-frontend.yml +335 -0
  83. package/lib/audit-rules/audit-rules-go.yml +22 -0
  84. package/lib/audit-rules/audit-rules-i18n.yml +45 -0
  85. package/lib/audit-rules/audit-rules-java.yml +105 -0
  86. package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
  87. package/lib/audit-rules/audit-rules-npm.yml +187 -0
  88. package/lib/audit-rules/audit-rules-paths.yml +92 -0
  89. package/lib/audit-rules/audit-rules-performance.yml +215 -0
  90. package/lib/audit-rules/audit-rules-php.yml +22 -0
  91. package/lib/audit-rules/audit-rules-private.yml +24 -0
  92. package/lib/audit-rules/audit-rules-python.yml +106 -0
  93. package/lib/audit-rules/audit-rules-robustness.yml +27 -0
  94. package/lib/audit-rules/audit-rules-rust.yml +22 -0
  95. package/lib/audit-rules/audit-rules-structure.yml +159 -0
  96. package/lib/audit-rules/audit-rules-swift.yml +22 -0
  97. package/lib/audit-rules/audit-rules-template.yml +108 -0
  98. package/lib/checks/button-bind.js +276 -0
  99. package/lib/checks/common.js +170 -0
  100. package/lib/checks/credential-file.js +43 -0
  101. package/lib/checks/dataflow.js +40 -0
  102. package/lib/checks/dispatch.js +112 -0
  103. package/lib/checks/dup-code.js +69 -0
  104. package/lib/checks/dup-const.js +232 -0
  105. package/lib/checks/file-health.js +150 -0
  106. package/lib/checks/filter.js +137 -0
  107. package/lib/checks/folder.js +173 -0
  108. package/lib/checks/hardcoded-path.js +98 -0
  109. package/lib/checks/index.js +46 -0
  110. package/lib/checks/io.js +66 -0
  111. package/lib/checks/magic-number.js +42 -0
  112. package/lib/checks/npm-json.js +273 -0
  113. package/lib/checks/private.js +63 -0
  114. package/lib/checks/regex.js +256 -0
  115. package/lib/checks/semantic.js +134 -0
  116. package/lib/checks/structural.js +274 -0
  117. package/lib/cli/commands-account.mjs +107 -0
  118. package/lib/cli/commands-audit.mjs +144 -0
  119. package/lib/cli/commands-doc.mjs +127 -0
  120. package/lib/cli/commands-vcs.mjs +175 -0
  121. package/lib/client/index.js +162 -0
  122. package/lib/client-parts/00-loader.js +33 -0
  123. package/lib/client-parts/01-const.js +207 -0
  124. package/lib/client-parts/02-utils.js +62 -0
  125. package/lib/client-parts/03-icons.js +12 -0
  126. package/lib/client-parts/10-account.js +83 -0
  127. package/lib/client-parts/11-browser.js +95 -0
  128. package/lib/client-parts/20-repo.js +374 -0
  129. package/lib/client-parts/21-audit.js +301 -0
  130. package/lib/client-parts/22-settings.js +146 -0
  131. package/lib/client-parts/23-npm.js +383 -0
  132. package/lib/client-parts/30-page.js +56 -0
  133. package/lib/client-parts/40-controller.js +1092 -0
  134. package/lib/client-parts/41-actions.js +279 -0
  135. package/lib/client-parts/99-apply.js +72 -0
  136. package/lib/client.js +3195 -0
  137. package/lib/commit-push.js +148 -0
  138. package/lib/context/index.js +363 -0
  139. package/lib/core/atomic-json.js +98 -0
  140. package/lib/core/config.js +40 -0
  141. package/lib/core/credentials.js +274 -0
  142. package/lib/core/endpoints.js +109 -0
  143. package/lib/core/exec.js +162 -0
  144. package/lib/exempt/index.js +292 -0
  145. package/lib/fs/edit-after-read.js +103 -0
  146. package/lib/fsx.js +87 -0
  147. package/lib/git/account-status.js +140 -0
  148. package/lib/git/account.js +233 -0
  149. package/lib/git/api.js +136 -0
  150. package/lib/git/atomic-json.js +6 -0
  151. package/lib/git/browse.js +38 -0
  152. package/lib/git/clone-download.js +397 -0
  153. package/lib/git/clone-history-mode.js +143 -0
  154. package/lib/git/clone-history.js +175 -0
  155. package/lib/git/clone-jobs.js +250 -0
  156. package/lib/git/clone-replay-io.js +172 -0
  157. package/lib/git/clone-replay.js +275 -0
  158. package/lib/git/clone.js +445 -0
  159. package/lib/git/cloud.js +46 -0
  160. package/lib/git/commit-message.js +141 -0
  161. package/lib/git/config.js +6 -0
  162. package/lib/git/cred-env.js +88 -0
  163. package/lib/git/credentials.js +6 -0
  164. package/lib/git/endpoints.js +6 -0
  165. package/lib/git/exec.js +6 -0
  166. package/lib/git/identity-rewrite.js +297 -0
  167. package/lib/git/identity.js +150 -0
  168. package/lib/git/ignore.js +69 -0
  169. package/lib/git/index.js +41 -0
  170. package/lib/git/module-splitter.js +47 -0
  171. package/lib/git/post-push.js +101 -0
  172. package/lib/git/push-diagnose.js +142 -0
  173. package/lib/git/push.js +476 -0
  174. package/lib/git/remote-resolve.js +146 -0
  175. package/lib/git/remote.js +128 -0
  176. package/lib/git/repo-index.js +512 -0
  177. package/lib/git/repos.js +235 -0
  178. package/lib/git/scan-runner.js +159 -0
  179. package/lib/git/sensitive.js +134 -0
  180. package/lib/git/transport.js +430 -0
  181. package/lib/git/visibility.js +35 -0
  182. package/lib/git/wrapped-git.js +68 -0
  183. package/lib/http/index.js +170 -0
  184. package/lib/index.js +24 -0
  185. package/lib/link-check/index.js +187 -0
  186. package/lib/npm/account.js +64 -0
  187. package/lib/npm/install.js +211 -0
  188. package/lib/npm/npmrc.js +56 -0
  189. package/lib/npm/publish.js +171 -0
  190. package/lib/npm/registry.js +168 -0
  191. package/lib/plugin/auto-detect.js +92 -0
  192. package/lib/plugin/auto-push.js +154 -0
  193. package/lib/plugin/index.js +250 -0
  194. package/lib/readme-templates/readme.yml +38 -0
  195. package/lib/rule/compilers/credential.js +62 -0
  196. package/lib/rule/compilers/dataflow.js +38 -0
  197. package/lib/rule/compilers/file-health.js +75 -0
  198. package/lib/rule/compilers/frontend.js +86 -0
  199. package/lib/rule/compilers/func.js +35 -0
  200. package/lib/rule/compilers/helpers.js +71 -0
  201. package/lib/rule/compilers/index.js +29 -0
  202. package/lib/rule/compilers/link-semantic.js +45 -0
  203. package/lib/rule/compilers/list-kinds.js +12 -0
  204. package/lib/rule/compilers/numeric-kinds.js +66 -0
  205. package/lib/rule/compilers/regex.js +78 -0
  206. package/lib/rule/compilers/structure.js +80 -0
  207. package/lib/rule/compilers.js +17 -0
  208. package/lib/rule/homoglyph.js +45 -0
  209. package/lib/rule/loader.js +270 -0
  210. package/lib/rule/registry.js +115 -0
  211. package/lib/rule/scope.js +67 -0
  212. package/lib/score/docs-score.js +166 -0
  213. package/lib/score/index.js +140 -0
  214. package/lib/self/index.js +196 -0
  215. package/lib/skip-dirs.js +64 -0
  216. package/lib/tool-probes.json +50 -0
  217. package/lib/user-requirements.json +14 -0
  218. package/lib/vendor/js-yaml/LICENSE +21 -0
  219. package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
  220. package/package.json +95 -4
  221. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  222. package/scripts/audit-ext/_example-readme-present.mjs +34 -0
  223. package/scripts/audit-ext/variable-min-length.mjs +102 -0
  224. package/scripts/audit-runner.mjs +35 -0
  225. package/scripts/audit-runtime-check.mjs +129 -0
  226. package/scripts/browser-page-probe.mjs +271 -0
  227. package/scripts/build-client.mjs +119 -0
  228. package/scripts/check.mjs +88 -0
  229. package/scripts/clean-date-comments.py +102 -0
  230. package/scripts/cpu-sample.mjs +188 -0
  231. package/scripts/doc-drift.mjs +200 -0
  232. package/scripts/doc-func.mjs +212 -0
  233. package/scripts/doc-tree.mjs +456 -0
  234. package/scripts/doc-version.mjs +220 -0
  235. package/scripts/frontend-preview-check.mjs +124 -0
  236. package/scripts/hot-path-probe-cjs.cjs +71 -0
  237. package/scripts/hot-path-probe-fs-shim.mjs +28 -0
  238. package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
  239. package/scripts/hot-path-probe.mjs +153 -0
  240. package/scripts/module-splitter.py +800 -0
  241. package/scripts/platform-scan.mjs +168 -0
  242. package/scripts/preview-gen.mjs +489 -0
  243. package/scripts/preview-local-runner.mjs +55 -0
  244. package/scripts/preview-server-direct.mjs +116 -0
  245. package/scripts/preview-server.mjs +305 -0
  246. package/scripts/preview-slot-data.mjs +123 -0
  247. package/scripts/probe-recheck.mjs +47 -0
  248. package/scripts/readme-gen.mjs +268 -0
  249. package/scripts/rename-locator.mjs +97 -0
  250. package/scripts/rule-switch.mjs +97 -0
  251. package/scripts/rules-solo-audit.mjs +173 -0
  252. package/scripts/scan-file-io.mjs +713 -0
  253. package/scripts/scan-hardcoded-paths.mjs +125 -0
  254. package/scripts/scan-repos.mjs +167 -0
  255. package/scripts/scan-version.mjs +122 -0
  256. package/scripts/scrub-user-wording.mjs +420 -0
  257. package/scripts/symbol-index.mjs +85 -0
  258. package/scripts/sync-plugin-install.mjs +223 -0
  259. package/scripts/sync-plugin.mjs +279 -0
  260. package/scripts/verify-prestep.mjs +100 -0
  261. package/skills/dev/audit-rule-authoring.md +58 -0
  262. package/skills/dev/dsh-git-push.md +323 -0
  263. package/skills/dev/git-push-live-fix.md +45 -0
  264. package/skills/dsh-repo-index.md +35 -0
  265. package/skills/guide/guide-audit.md +167 -0
  266. package/skills/guide/guide-cli-scripts.md +104 -0
  267. package/skills/guide/guide-clone-repos.md +173 -0
  268. package/skills/guide/guide-commit-push.md +156 -0
  269. package/skills/guide/guide-inject-ui.md +166 -0
  270. package/skills/guide/guide-slash-completion.md +118 -0
  271. package/skills/workflow/README.md +21 -0
  272. package/skills/workflow/git-commit-discipline.md +68 -0
  273. package/skills/workflow/git-project-startup.md +85 -0
  274. package/skills/workflow/git-rebuild-process.md +57 -0
  275. package/skills/workflow/github-operations.md +91 -0
  276. package/skills/workflow/readme-sync-git-md.md +28 -0
  277. package/skills/workflow/task-completion-report.md +73 -0
  278. package/skills/workflow/tool-json-add-ask.md +35 -0
  279. package/skills/workflow/versioning-rule.md +211 -0
@@ -0,0 +1,274 @@
1
+ /**
2
+ * AST 实现层 · 数据流检查(三层审计 L2)
3
+ *
4
+ * 职责:同函数内的「清空后访问」数据流判定——变量/对象先被清空
5
+ * (clear()/reset()/splice(0)/length=0/=[]/=null/delete),之后在同一
6
+ * 函数体内又被读取/访问(.get()/.at()/[下标] 等),构成「读已清空对象」
7
+ * 风险(拿到 undefined / 空值)。
8
+ *
9
+ * 为什么是 L2(AST+YAML)而不是 L1(正则):
10
+ * L1 正则只能筛「文件里同时出现过清空词和访问词」,无法区分两者是否
11
+ * 在同一函数内、是否先后有序。L2 用 token 级函数区间(collectInnerFnRanges)
12
+ * 精确到「同一函数体、清空行 < 访问行」才算命中。
13
+ *
14
+ * 为什么够不到 L3(运行时):
15
+ * 闭包捕获、跨模块引用、异步回调里的真实时序(清空在 setTimeout 后执行、
16
+ * 访问在 Promise resolve 时)静态无法确定——那是 scripts/audit-runtime-check.mjs
17
+ * 的职责,本模块只在静态可判定时给结论。
18
+ *
19
+ * 判定保守(宁漏不误报):
20
+ * ① 只统计同一函数体区间内的动作(顶层/function/方法/箭头函数体);
21
+ * ② 清空与访问必须命中**同一个对象名**(ident 相同);
22
+ * ③ 访问行必须在清空行**之后**(行号单调);
23
+ * ④ **写回撤销**:清空后被重新填充(push/set/add/重新赋值)→ 撤销清空标记,
24
+ * 其后访问不算命中(对象已被重新填充,不是「读已清空对象」)。
25
+ */
26
+
27
+ import { tokenize } from './tokenizer.js';
28
+ import { matchBrace } from './brace.js';
29
+
30
+ /** 清空动作:方法调用(对象.clear() / .reset() / .flush() / .purge())。 */
31
+ const CLEAR_METHODS = new Set(['clear', 'reset', 'empty', 'flush', 'purge']);
32
+ /** 访问动作:方法读——清空后调用会拿 undefined(.get() / .at(0) / .first() / .peek())。
33
+ * shift/pop 是「消费式访问」,常见于 `while (len) { shift() }` 保护模式,不报(宁漏不误报)。 */
34
+ const ACCESS_METHODS = new Set(['get', 'at', 'first', 'last', 'peek', 'head']);
35
+ /** 写回动作:清空后重新填充(push/add/set/append/unshift/assign)→ 撤销清空标记。 */
36
+ const WRITE_METHODS = new Set(['push', 'add', 'set', 'append', 'unshift', 'assign', 'insert']);
37
+
38
+ /**
39
+ * 收集文本里所有「函数体 token 区间」——function 声明 + 方法 + 箭头函数,
40
+ * 以及**排除函数体后**的顶层作用域孤岛区间。
41
+ *
42
+ * 互斥性(修复跨函数误连):
43
+ * 旧实现把顶层作用域 = 整个文件区间,导致「模块级清空(顶层 `resultsByIndex =
44
+ * new Map()` 重置)→ 另一函数里的访问」被误判为同函数。正确做法是:
45
+ * 顶层只保留**不属于任何函数体**的 token 段(变量声明/模块级语句),
46
+ * 与各函数体区间互斥,各自独立扫描——清空动作和访问动作必须落在同一区间。
47
+ *
48
+ * @param {Array} tokens token 流
49
+ * @returns {Array<[number, number]>} [startIdx, endIdx](含大括号,闭区间;互斥不重叠)
50
+ */
51
+ /** 段①:函数声明/表达式体(function f() {...} / const f = function() {...})。 */
52
+ function collectDeclaredFnBodies(tokens) {
53
+ const fnRanges = [];
54
+ for (let i = 0; i < tokens.length; i++) {
55
+ const t = tokens[i];
56
+ if (!(t.type === 'ident' && t.value === 'function')) continue;
57
+ let openIdx = -1;
58
+ for (let j = i + 1; j < Math.min(tokens.length, i + 24); j++) {
59
+ if (tokens[j].type === 'punct' && tokens[j].value === '{') { openIdx = j; break; }
60
+ }
61
+ if (openIdx === -1) continue;
62
+ const r = matchBrace(tokens, openIdx);
63
+ if (r) fnRanges.push(r);
64
+ }
65
+ return fnRanges;
66
+ }
67
+
68
+ /** 段②:箭头函数体(() => {...})与方法简写(method() {...})。 */
69
+ function collectArrowMethodBodies(tokens) {
70
+ const fnRanges = [];
71
+ for (let i = 0; i < tokens.length - 1; i++) {
72
+ const t = tokens[i];
73
+ if (t.type === 'punct' && t.value === '=>' && tokens[i + 1]?.type === 'punct' && tokens[i + 1]?.value === '{') {
74
+ const r = matchBrace(tokens, i + 1);
75
+ if (r) fnRanges.push(r);
76
+ }
77
+ if (t.type === 'punct' && t.value === ')' && tokens[i + 1]?.type === 'punct' && tokens[i + 1]?.value === '{') {
78
+ let prev = null;
79
+ for (let j = i - 1; j >= 0; j--) {
80
+ if (tokens[j].type === 'ws' || tokens[j].type === 'comment') continue;
81
+ prev = tokens[j];
82
+ break;
83
+ }
84
+ if (prev && prev.type === 'ident') {
85
+ const r = matchBrace(tokens, i + 1);
86
+ if (r) fnRanges.push(r);
87
+ }
88
+ }
89
+ }
90
+ return fnRanges;
91
+ }
92
+
93
+ /** 段③:排序去重叠(嵌套只留最外层)+ 补顶层作用域孤岛(函数外 token 段)。 */
94
+ function mergeFnRanges(fnRanges, tokens) {
95
+ fnRanges.sort((a, b) => a[0] - b[0]);
96
+ const merged = [];
97
+ for (const r of fnRanges) {
98
+ const last = merged[merged.length - 1];
99
+ if (last && r[0] <= last[1]) { last[1] = Math.max(last[1], r[1]); continue; } // 重叠/嵌套 → 合并
100
+ merged.push([r[0], r[1]]);
101
+ }
102
+ const bodies = [...merged];
103
+ // 顶层孤岛 = [0, lastCode] 减去所有函数体区间
104
+ let lastCode = tokens.length - 1;
105
+ while (lastCode >= 0 && (tokens[lastCode].type === 'comment' || tokens[lastCode].type === 'ws')) lastCode--;
106
+ if (lastCode >= 0) {
107
+ let cursor = 0;
108
+ for (const [fs, fe] of merged) {
109
+ if (fs > cursor) bodies.push([cursor, fs - 1]); // 函数前的顶层段
110
+ cursor = Math.max(cursor, fe + 1);
111
+ }
112
+ if (cursor <= lastCode) bodies.push([cursor, lastCode]); // 函数后的顶层段
113
+ }
114
+ return bodies;
115
+ }
116
+
117
+ /** 收集全部函数体区间(声明/表达式/箭头/方法 + 顶层孤岛)。 */
118
+ function collectFnBodies(tokens) {
119
+ const fnRanges = [...collectDeclaredFnBodies(tokens), ...collectArrowMethodBodies(tokens)];
120
+ return mergeFnRanges(fnRanges, tokens);
121
+ }
122
+
123
+ /** 从 i 向前跳过空白/注释,取最近一个有效 token。 */
124
+ function prevNonWs(tokens, i) {
125
+ for (let j = i - 1; j >= 0; j--) {
126
+ if (tokens[j].type === 'ws' || tokens[j].type === 'comment') continue;
127
+ return tokens[j];
128
+ }
129
+ return null;
130
+ }
131
+
132
+ /** 从 i 向后(含 i)跳过空白/注释,取最近一个有效 token。 */
133
+ function nextNonWs(tokens, i, to) {
134
+ for (let j = i; j <= to; j++) {
135
+ const tj = tokens[j];
136
+ if (tj?.type === 'ws' || tj?.type === 'comment') continue;
137
+ return tj;
138
+ }
139
+ return null;
140
+ }
141
+
142
+ /** obj 位于实参位(前 token 是 '(' 或 ',',后 token 是 ',' 或 ')')→ 可能被引用填充,撤销清空。 */
143
+ function applyArgWriteback(tokens, i, nxt, obj, clearMap) {
144
+ if (!(nxt?.type === 'punct' && (nxt.value === ',' || nxt.value === ')'))) return false;
145
+ const prev = prevNonWs(tokens, i);
146
+ if (prev && prev.type === 'punct' && (prev.value === '(' || prev.value === ',')) {
147
+ clearMap.delete(obj);
148
+ }
149
+ return true;
150
+ }
151
+
152
+ /**
153
+ * obj = rhs:rhs 是 null/undefined/[] 记清空;声明初始化不算清空;其它赋值记写回。
154
+ * @returns {boolean} 本 token 已按赋值处理
155
+ */
156
+ function applyAssignClearOrWriteback(tokens, i, to, t, nxt, obj, clearMap) {
157
+ if (!(nxt?.type === 'punct' && nxt.value === '=')) return false;
158
+ const rhs = nextNonWs(tokens, i + 2, to);
159
+ if (!rhs) return true;
160
+ const isEmptyAssign = (rhs.type === 'ident' && (rhs.value === 'null' || rhs.value === 'undefined'))
161
+ || (rhs.type === 'punct' && rhs.value === '[' && tokens[i + 3]?.type === 'punct' && tokens[i + 3].value === ']');
162
+ if (!isEmptyAssign) {
163
+ clearMap.delete(obj);
164
+ return true;
165
+ }
166
+ // 声明初始化(var/let/const 变量 = [] / = null)不算清空
167
+ const prev = prevNonWs(tokens, i);
168
+ const decl = prev && prev.type === 'ident' && (prev.value === 'var' || prev.value === 'let' || prev.value === 'const');
169
+ if (!decl) {
170
+ clearMap.set(obj, { line: t.line, op: `= ${rhs.value === '[' ? '[]' : rhs.value}` });
171
+ }
172
+ return true;
173
+ }
174
+
175
+ /**
176
+ * 方法清空:.clear()/.reset()/.flush()、.splice(0)、.length = 0。
177
+ * @returns {number} 新的循环下标 i;未命中返回原 i
178
+ */
179
+ function applyClearMethods(t, member, memberIdx, callOpen, tokens, obj, clearMap, i) {
180
+ if (callOpen && CLEAR_METHODS.has(member)) {
181
+ clearMap.set(obj, { line: t.line, op: `.${member}()` });
182
+ return memberIdx + 1;
183
+ }
184
+ if (callOpen && member === 'splice') {
185
+ const arg1 = tokens[memberIdx + 2];
186
+ if (!arg1 || (arg1.type === 'num' && Number(arg1.value) === 0)) {
187
+ clearMap.set(obj, { line: t.line, op: '.splice(0)' });
188
+ }
189
+ return memberIdx + 1;
190
+ }
191
+ if (member === 'length' && tokens[memberIdx + 1]?.type === 'punct' && tokens[memberIdx + 1].value === '='
192
+ && tokens[memberIdx + 2]?.type === 'num' && Number(tokens[memberIdx + 2].value) === 0) {
193
+ clearMap.set(obj, { line: t.line, op: '.length = 0' });
194
+ return memberIdx + 2;
195
+ }
196
+ return i;
197
+ }
198
+
199
+ /**
200
+ * 清空后访问:.get()/.at() 或 [下标]。命中则记一条并撤销该对象标记(同对象只报一次)。
201
+ * @returns {number} 新的循环下标 i
202
+ */
203
+ function applyAccessAfterClear(t, nxt, member, memberIdx, callOpen, tokens, i, obj, clearMap, out) {
204
+ if (!clearMap.has(obj)) return i;
205
+ const cleared = clearMap.get(obj);
206
+ if (callOpen && ACCESS_METHODS.has(member)) {
207
+ out.push({ line: t.line, obj, clearLine: cleared.line, clearOp: cleared.op, accessOp: `.${member}()` });
208
+ clearMap.delete(obj);
209
+ return memberIdx + 1;
210
+ }
211
+ if (nxt?.type === 'punct' && nxt.value === '[') {
212
+ const idx = tokens[i + 2];
213
+ if (idx && (idx.type === 'num' || idx.type === 'ident')) {
214
+ out.push({ line: t.line, obj, clearLine: cleared.line, clearOp: cleared.op, accessOp: `[${idx.value}]` });
215
+ clearMap.delete(obj);
216
+ }
217
+ }
218
+ return i;
219
+ }
220
+
221
+ /**
222
+ * 在单个函数体区间内判定「清空后访问」。
223
+ *
224
+ * @param {Array} tokens token 流
225
+ * @param {number} from 区间起点(含)
226
+ * @param {number} to 区间终点(含)
227
+ * @returns {Array<{line:number, obj:string, clearLine:number, clearOp:string, accessOp:string}>}
228
+ */
229
+ function scanClearThenAccess(tokens, from, to) {
230
+ const out = [];
231
+ const clearMap = new Map(); // obj -> { line, op }
232
+ for (let i = from; i <= to; i++) {
233
+ const t = tokens[i];
234
+ if (t.type !== 'ident') continue;
235
+ const identName = t.value;
236
+ const nxt = tokens[i + 1];
237
+ const memberIdx = (nxt?.type === 'punct' && nxt.value === '.') ? i + 2 : -1;
238
+ const member = memberIdx >= 0 && tokens[memberIdx]?.type === 'ident' ? tokens[memberIdx].value : null;
239
+ const callOpen = memberIdx >= 0 && tokens[memberIdx + 1]?.type === 'punct' && tokens[memberIdx + 1].value === '(';
240
+
241
+ if (callOpen && WRITE_METHODS.has(member)) {
242
+ clearMap.delete(identName);
243
+ continue;
244
+ }
245
+ if (applyArgWriteback(tokens, i, nxt, identName, clearMap)) continue;
246
+ if (applyAssignClearOrWriteback(tokens, i, to, t, nxt, identName, clearMap)) continue;
247
+ const afterClear = applyClearMethods(t, member, memberIdx, callOpen, tokens, identName, clearMap, i);
248
+ if (afterClear !== i) { i = afterClear; continue; }
249
+ i = applyAccessAfterClear(t, nxt, member, memberIdx, callOpen, tokens, i, identName, clearMap, out);
250
+ }
251
+ return out;
252
+ }
253
+
254
+ /**
255
+ * 三层审计 L2 入口:同函数「清空后访问」数据流检测。
256
+ *
257
+ * @param {string} text 文件全文
258
+ * @returns {Array<{line:number, obj:string, clearLine:number, clearOp:string, accessOp:string}>}
259
+ */
260
+ export function checkClearAccessAst(text = '') {
261
+ const tokens = tokenize(text);
262
+ const bodies = collectFnBodies(tokens);
263
+ const seen = new Set(); // 去重(同一行同对象只报一次)
264
+ const out = [];
265
+ for (const [from, to] of bodies) {
266
+ for (const hit of scanClearThenAccess(tokens, from, to)) {
267
+ const key = `${hit.line}:${hit.obj}`;
268
+ if (seen.has(key)) continue;
269
+ seen.add(key);
270
+ out.push(hit);
271
+ }
272
+ }
273
+ return out;
274
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * AST 实现层 · 重复代码检测(抽公共函数候选)
3
+ *
4
+ * 判定标准(量化判定标准,量化版):
5
+ * 「三处重复、五行以上、未来会改」——满足就抽。本检测自动化前两条:
6
+ * · 重复次数 ≥ 3 处(2 次观察,3 次必须抽)
7
+ * · 函数体 ≥ 5 行(少于 5 行的重复,抽出来反而增加跳转成本)
8
+ * 第三条「未来会改」无法静态判定,留给人工。
9
+ *
10
+ * 不该抽的形态(自动排除):
11
+ * · 纯语法糖/单行表达式(如 arr.filter(x => x))
12
+ * · 依赖 this/闭包状态、参数是上下文对象(无法安全抽取)
13
+ * · 布尔 flag 参数控制分支的「伪公共」函数
14
+ * · 参数 > 5 个(职责不清)
15
+ * · test/ 夹具内的重复(测试各自独立,抽公共测试工具另说)
16
+ *
17
+ * 归一化策略(找"结构相同"而非"文本相同"的重复):
18
+ * 变量名符号化(ident → V)、数字符号化(num → N)、字符串保留原文
19
+ * (字符串内容不同通常语义不同)、注释与空白剔除。这样
20
+ * `const a = x + 1` 与 `const total = count + 1` 视为同一结构。
21
+ */
22
+
23
+ import { tokenize } from './tokenizer.js';
24
+ import { collectNamedFnRanges } from './callgraph.js';
25
+
26
+ /** 重复判定阈值:同一结构函数体出现 ≥ 此数即候选(量化标准:≥3 处必须抽)。 */
27
+ const DUP_COUNT_MIN = 3;
28
+ /** 函数体最少行数:少于 5 行的重复不值得抽(跳转成本 > 收益)。 */
29
+ const DUP_LINES_MIN = 5;
30
+ /** 参数上限:超过 5 个参数的函数不报(职责不清,抽了也难维护)。 */
31
+ const PARAMS_MAX = 5;
32
+ /** 布尔 flag 参数名清单(有这些参数的函数视为"伪公共",不报)。 */
33
+ const BOOL_FLAG_NAMES = new Set(['flag', 'force', 'enabled', 'disabled', 'dryRun', 'dryrun', 'isAdmin', 'isMobile', 'isDark', 'verbose', 'quiet', 'useCache', 'skipCache', 'silent']);
34
+
35
+ /**
36
+ * 提取单个文件的具名函数体,归一化后返回候选列表。
37
+ * @param {string} text 文件全文
38
+ * @param {string} file 文件路径(供 finding 定位)
39
+ * @returns {Array<{file:string, name:string, line:number, hash:string, lines:number, params:number, hasBoolFlag:boolean}>}
40
+ */
41
+ export function collectDupCodeCandidates(text, file = '') {
42
+ const tokens = tokenize(text);
43
+ const ranges = collectNamedFnRanges(tokens);
44
+ const out = [];
45
+ for (const [name, [openIdx, closeIdx]] of ranges) {
46
+ if (!name || name === '(匿名)') continue;
47
+ // 提取函数体 token(openIdx+1 .. closeIdx-1,跳过 {} 本身)
48
+ const bodyTokens = tokens.slice(openIdx + 1, closeIdx);
49
+ // 行数:函数体 token 跨度(openIdx 的 { 到 closeIdx 的 },含两端)——视觉行数,
50
+ // 与量化标准「重复行数 ≥5」的口径一致(5 行 = 从 function 签名行到闭括号行)
51
+ if (closeIdx <= openIdx) continue;
52
+ const bodyLines = tokens[closeIdx].line - tokens[openIdx].line + 1;
53
+ if (bodyLines < DUP_LINES_MIN) continue;
54
+
55
+ // 归一化哈希:变量名/数字符号化,剔 ws/comment,字符串保留
56
+ const parts = [];
57
+ for (const t of bodyTokens) {
58
+ if (t.type === 'ws' || t.type === 'comment') continue;
59
+ if (t.type === 'ident') parts.push('V');
60
+ else if (t.type === 'num') parts.push('N');
61
+ else if (t.type === 'str' || t.type === 'tmpl') parts.push(`S(${t.value.length})`); // 字符串按长度,避免「内容不同但结构同」误合并
62
+ else parts.push(t.value);
63
+ }
64
+ if (parts.length < 8) continue; // 函数体太短(<8 token)视为语法糖,不值得抽
65
+ const hash = parts.join('\u0001'); // 用不可打印分隔符,避免与 || 等运算符字符冲突
66
+
67
+ // 参数个数与布尔 flag 判定(从函数签名 token 区间取——openIdx 之前的 '(' ... ')')
68
+ const params = countParams(tokens, openIdx);
69
+ const hasBoolFlag = hasBoolFlagParam(tokens, openIdx);
70
+
71
+ // 纯语法糖排除:函数体归一化后 ≤ 2 种 token 类型 且 无 ident → 如 (x) => x
72
+ const typeSet = new Set(parts);
73
+ if (typeSet.size <= 1) continue; // 全是同一符号(如 V|V|V)→ 语法糖
74
+
75
+ out.push({ file, name, line: tokens[openIdx].line, hash, lines: bodyLines, params, hasBoolFlag });
76
+ }
77
+ return out;
78
+ }
79
+
80
+ /**
81
+ * 跨文件聚合重复候选:同一归一化结构出现 ≥3 处的函数体。
82
+ * @param {Array<Array<{file,name,line,hash,lines,params,hasBoolFlag}>>} perFileCandidates
83
+ * @param {object} [opts] { minLines=5, minOccurrences=3 } 阈值(可被规则 yml 覆盖)
84
+ * @returns {Array<{hash:string, lines:number, instances:Array<{file,name,line}>}>}
85
+ */
86
+ export function findDuplicateBodies(perFileCandidates, opts = {}) {
87
+ const minLines = Number(opts.minLines) || DUP_LINES_MIN;
88
+ const minOcc = Number(opts.minOccurrences) || DUP_COUNT_MIN;
89
+ const byHash = new Map();
90
+ for (const list of perFileCandidates) {
91
+ for (const c of list) {
92
+ if (c.hasBoolFlag) continue; // 伪公共不报
93
+ if (c.params > PARAMS_MAX) continue; // 参数太多不报
94
+ if (c.lines < minLines) continue; // 行数不足不报
95
+ if (!byHash.has(c.hash)) byHash.set(c.hash, []);
96
+ byHash.get(c.hash).push(c);
97
+ }
98
+ }
99
+ const out = [];
100
+ for (const [hash, instances] of byHash) {
101
+ // 同一结构出现 ≥ 阈值即报(量化标准:2 次观察、3 次必须抽)——
102
+ // 不区分同文件/跨文件:同文件 3 个相同函数体同样是「该抽」信号
103
+ if (instances.length >= minOcc) {
104
+ out.push({ hash, lines: instances[0].lines, instances });
105
+ }
106
+ }
107
+ // 行数多的优先(更值得抽)
108
+ out.sort((a, b) => b.lines - a.lines);
109
+ return out;
110
+ }
111
+
112
+ /** 从函数体 openIdx 回找签名括号,数参数个数(顶层逗号 + 1;无参数 0)。 */
113
+ function countParams(tokens, openIdx) {
114
+ let closeIdx = -1;
115
+ let parenDepth = 0;
116
+ // 回找与 openIdx 前最近的 ')' 配对的 '(':从 openIdx-1 向左扫
117
+ for (let j = openIdx - 1; j >= 0; j--) {
118
+ const t = tokens[j];
119
+ if (t.type !== 'punct') continue;
120
+ if (t.value === ')') { parenDepth++; closeIdx = j; break; }
121
+ if (t.value === ';' || t.value === '{') break;
122
+ }
123
+ if (closeIdx === -1) return 0;
124
+ // 在 closeIdx 内找配对 '('
125
+ let depth = 0, openParen = -1;
126
+ for (let j = closeIdx; j >= 0; j--) {
127
+ const t = tokens[j];
128
+ if (t.type !== 'punct') continue;
129
+ if (t.value === ')') depth++;
130
+ else if (t.value === '(') { depth--; if (depth === 0) { openParen = j; break; } }
131
+ }
132
+ if (openParen === -1) return 0;
133
+ let commas = 0;
134
+ let inner = 0;
135
+ for (let j = openParen + 1; j < closeIdx; j++) {
136
+ const t = tokens[j];
137
+ if (t.type !== 'punct') continue;
138
+ if (t.value === '(' || t.value === '[' || t.value === '{') inner++;
139
+ else if (t.value === ')' || t.value === ']' || t.value === '}') inner--;
140
+ else if (t.value === ',' && inner === 0) commas++;
141
+ }
142
+ return commas + (closeIdx - openParen > 1 ? 1 : 0);
143
+ }
144
+
145
+ /** 签名括号内是否含布尔 flag 参数名。 */
146
+ function hasBoolFlagParam(tokens, openIdx) {
147
+ let closeIdx = -1;
148
+ for (let j = openIdx - 1; j >= 0; j--) {
149
+ const t = tokens[j];
150
+ if (t.type !== 'punct') continue;
151
+ if (t.value === ')') { closeIdx = j; break; }
152
+ if (t.value === ';' || t.value === '{') break;
153
+ }
154
+ if (closeIdx === -1) return false;
155
+ // 从 closeIdx 向左扫到签名 '(':ident 是参数名,命中布尔 flag 词表即伪公共
156
+ for (let j = closeIdx; j >= 0; j--) {
157
+ const t = tokens[j];
158
+ if (t.type === 'punct') {
159
+ if (t.value === '(') break; // 到签名起点
160
+ continue;
161
+ }
162
+ if (t.type === 'ident' && BOOL_FLAG_NAMES.has(t.value)) return true;
163
+ }
164
+ return false;
165
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * AST 实现层 · 统一出口
3
+ *
4
+ * 分层位置(三层审计架构第二层):
5
+ * ① 规则声明 → lib/audit-rules/*.yml(阈值、豁免清单、上下文关键字)
6
+ * ② 具体实现 → lib/ast/*(本目录,token 级解析:字符串/模板串/注释感知)
7
+ * ③ 调用包装 → lib/checks/*(把 AST 判定转成 finding,不重复造逻辑)
8
+ * ④ 编排调度 → lib/audit/*(收集文件、跑检查、汇总)
9
+ *
10
+ * 命名说明:本目录叫 ast/ 但实现是 **token 级**而非真正的语法树——
11
+ * Node 无内置 JS AST,零依赖约束下 token 级已足够覆盖「注释/字符串里的内容不算代码」
12
+ * 这类判定。命名取「比正则更精确的语法级判定」之意,与逐行正则形成对照。
13
+ *
14
+ * 本文件只做再导出、不含实现:
15
+ * 调用方既可 `import { tokenize } from '../ast/index.js'`(出口稳定),
16
+ * 也可直接引具体模块(如 '../ast/tokenizer.js')以获得更窄的依赖面。
17
+ */
18
+
19
+ export { tokenize, clearTokenCache } from './tokenizer.js';
20
+ export { matchBrace, isBlockParen, matchingOpen, collectInnerFnRanges } from './brace.js';
21
+ export { checkSyncFs, checkEmptyCatchAst, checkComplexityAst, checkNestingDepthAst } from './control-flow.js';
22
+ export { checkFuncLinesAst, checkFuncDensityAst, funcRangesAst, maxFunctionLength, checkFileLines, countCommentLines, checkRepeatedStringsAst, checkCommentDensityAst } from './size.js';
23
+ export { checkNameLengthAst, checkShortFunctionNameAst, checkSmallFileReadAst, checkConsoleLogJsonAst } from './naming.js';
24
+ export { javaKtFuncRanges, detectLang } from './lang.js';
25
+ export { makeCodeLineFilter, codeStringLiterals } from './code-lines.js';
26
+ export { shellCdDynamicLines, writeIntoGitignoredLines } from './shell.js';
27
+ export { checkMagicNumberSmartAst } from './magic-number.js';
28
+ export {
29
+ isMeaningfulCredentialValue,
30
+ checkPlaceholderCredentialAst,
31
+ checkCredentialRefAst,
32
+ } from './credential.js';
33
+ // 三层审计 L2——数据流检查(同函数清空后访问)
34
+ export { checkClearAccessAst } from './dataflow.js';
35
+ // I/O 风险分级(四级;scanIoRiskAst 供 checks 层精筛与 scan-file-io 复用)
36
+ export { scanIoRiskAst, summarizeIoRisk, rankIoFixList, RISK_BADGE, RISK_LABEL } from './io-risk.js';
@@ -0,0 +1,95 @@
1
+ /**
2
+ * dsh-git-push — I/O 风险分级:常量与档位工具
3
+ *
4
+ * 职责:定义「哪些调用算 I/O」「算什么操作类别」「风险如何升档」三类纯数据,
5
+ * 以及依赖它们的档位工具函数(raise)。不含任何 token 分析逻辑。
6
+ *
7
+ * 分层:lib/ast/io-risk.js 的从属模块(由该文件再导出),调用方不应直接 import。
8
+ */
9
+ /** 同步 fs 调用名(带 Sync 后缀)→ 统一视为阻塞调用。 */
10
+ export const SYNC_FS_FNS = new Set([
11
+ 'readFileSync', 'writeFileSync', 'appendFileSync', 'existsSync', 'statSync', 'lstatSync',
12
+ 'readdirSync', 'mkdirSync', 'rmdirSync', 'rmSync', 'unlinkSync', 'renameSync',
13
+ 'copyFileSync', 'chmodSync', 'chownSync', 'openSync', 'closeSync', 'readSync',
14
+ 'writeSync', 'truncateSync', 'realpathSync', 'symlinkSync', 'linkSync', 'accessSync',
15
+ ]);
16
+
17
+ /** 异步 fs 调用名(无 Sync 后缀的常见形态)。 */
18
+ export const ASYNC_FS_FNS = new Set([
19
+ 'readFile', 'writeFile', 'appendFile', 'stat', 'lstat', 'readdir', 'mkdir', 'rmdir',
20
+ 'rm', 'unlink', 'rename', 'copyFile', 'chmod', 'chown', 'open', 'close', 'read',
21
+ 'write', 'truncate', 'realpath', 'symlink', 'link', 'access', 'createReadStream',
22
+ 'createWriteStream', 'watch', 'opendir',
23
+ ]);
24
+
25
+ /** 操作类别:写 / 删 / 改名 涉及数据安全,风险加权。 */
26
+ export const KIND_BY_FN = {
27
+ writeFileSync: 'write', writeFile: 'write', appendFileSync: 'write', appendFile: 'write',
28
+ createWriteStream: 'write', writeSync: 'write', write: 'write', truncateSync: 'write',
29
+ truncate: 'write',
30
+ unlinkSync: 'delete', unlink: 'delete', rmSync: 'delete', rm: 'delete',
31
+ rmdirSync: 'delete', rmdir: 'delete',
32
+ renameSync: 'rename', rename: 'rename', copyFileSync: 'rename', copyFile: 'rename',
33
+ };
34
+
35
+ /**
36
+ * 元数据/查询/幂等目录操作(io-risk 优化——对照诊断「97% 误报」):
37
+ * 单文件 stat/exists/readdir/access 微秒级、mkdir(recursive)/rmdir 幂等——不搬运数据内容,
38
+ * 请求路径上不构成阻塞风险 → 降为 low(不再按「请求路径 I/O」一律 medium)。
39
+ * 循环内的仍走循环分级(循环内逐次 stat 累积由循环规则判定,不受本档豁免)。
40
+ */
41
+ export const META_FS_FNS = new Set([
42
+ 'existsSync', 'statSync', 'lstatSync', 'readdirSync', 'accessSync', 'realpathSync',
43
+ 'exists', 'stat', 'lstat', 'readdir', 'access', 'realpath',
44
+ 'mkdirSync', 'rmdirSync', 'mkdir', 'rmdir',
45
+ ]);
46
+
47
+ /** 循环体识别:for/while/do 关键字与数组迭代方法。 */
48
+ export const LOOP_KEYWORDS = new Set(['for', 'while', 'do']);
49
+ export const LOOP_METHODS = new Set([
50
+ 'forEach', 'map', 'filter', 'reduce', 'reduceRight', 'flatMap', 'some', 'every',
51
+ 'find', 'findIndex', 'findLast', 'findLastIndex',
52
+ ]);
53
+
54
+ /** 请求处理路径特征(在函数体内出现任一即认定)。 */
55
+ export const REQUEST_PATTERNS = [
56
+ /\b(?:req|request)\.(?:headers|method|url|body|on)\b/,
57
+ /\bres\.(?:writeHead|write|end|setHeader|statusCode)\b/,
58
+ /\b(?:handle|route|onRequest)[A-Za-z_$]*\s*\(/,
59
+ /\bcreateServer\s*\(\s*(?:async\s*)?\(?\s*(?:req|request)\s*,/,
60
+ /\(\s*(?:req|request)\s*,\s*(?:res|response)\s*\)/,
61
+ ];
62
+
63
+ /** 风险档位(数值越大越高)。 */
64
+ export const LEVELS = ['safe', 'low', 'medium', 'high'];
65
+
66
+ /** 徽标。 */
67
+ export const RISK_BADGE = { high: '🔴', medium: '🟠', low: '🟡', safe: '🟢' };
68
+
69
+ /** 风险中文名。 */
70
+ export const RISK_LABEL = { high: '高', medium: '中', low: '低', safe: '安全' };
71
+
72
+ /**
73
+ * 是否循环头:for/while/do 关键字,或 `.forEach(` / `.map(` 等方法调用。
74
+ *
75
+ * 方法形态**必须**校验前导 `.`:`LOOP_METHODS` 里的名字(map/find/filter/some/…)
76
+ * 同样是极其常见的普通变量名/参数名。早先只做 `LOOP_METHODS.has(value)`
77
+ * 而不看前一个 token,导致 `JSON.stringify(map, null, 2)` 里的参数 `map`、
78
+ * `const map = new Map()` 里的 `map` 都被当成循环头 —— 实测全仓 1109 个「循环头」
79
+ * 里有 44 个是这种裸标识符(4.0%),既凭空造出循环范围(把无关行的 I/O
80
+ * 误标成「循环内」),也让真正的循环范围互相干扰。
81
+ *
82
+ * @param {object} t 当前 token
83
+ * @param {object} [prev] 前一个 token;方法调用形态须满足 `prev.value === '.'`
84
+ * @returns {boolean}
85
+ */
86
+ export function isLoopHead(t, prev) {
87
+ if (LOOP_KEYWORDS.has(t.value)) return true;
88
+ return LOOP_METHODS.has(t.value) && prev?.value === '.';
89
+ }
90
+
91
+ /** 档位提升 n 级(用于写/删加权)。 */
92
+ export function raise(level, n = 1) {
93
+ const i = LEVELS.indexOf(level);
94
+ return LEVELS[Math.min(LEVELS.length - 1, i + n)];
95
+ }