dsh-gufa-code 1.3.117 → 1.3.133

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.
@@ -7,8 +7,8 @@
7
7
  <key>CFBundleDisplayName</key><string>古法编程悬浮层</string>
8
8
  <key>CFBundleExecutable</key><string>gufa-float</string>
9
9
  <key>CFBundlePackageType</key><string>APPL</string>
10
- <key>CFBundleShortVersionString</key><string>1.3.117</string>
11
- <key>CFBundleVersion</key><string>1.3.117</string>
10
+ <key>CFBundleShortVersionString</key><string>1.3.133</string>
11
+ <key>CFBundleVersion</key><string>1.3.133</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
@@ -84,6 +84,62 @@
84
84
  - 同时关闭 Monaco worker 诊断(`noSemanticValidation/noSyntaxValidation=true`),避免 dsh-app 自定义协议下 worker importScripts 失败产生重复/后台报错;补全仍由 worker 提供。
85
85
  - 模块解析失败码(2307/2792 等)忽略,并注入 Node 全局 shim(process/require/module/Buffer 等),否则 JS 文件会被 `Cannot find name process` 淹没。
86
86
 
87
+ ## 0.15 诊断误报:只保留语法 + 未定义变量(1.3.118)
88
+
89
+ - 全量 `getSemanticDiagnostics` 在动态 JS/JSON 配置项目里误报极多:`lodash` 的 UMD 包报 2306 "File is not a module"、从 `config.json` 推断出的类型报 2339 "Property 'username' does not exist"、`node-uuid` 类型声明报 `v4` 不存在等等。用户看到的 3/19/45 行“语法错误”都是这类噪音。
90
+ - 策略:语法诊断(`getSyntacticDiagnostics`)全保留;语义诊断白名单 `2304/2552/2448/2454`(Cannot find name / Block-scoped variable before declaration 等),其余(2339、2306、模块解析类)不展示。
91
+ - 实测 `baiducomp/taskks.js` 从 4 条误报 → 0 条;回归测试覆盖“属性不存在不报”。
92
+
93
+ ## 0.16 分割条拖拽不能每帧 setState(1.3.119)
94
+
95
+ - 现象:拖动左栏/聊天栏/终端高度拖沓。原因:`useSplitter` 的 mousemove 每帧 `setSize`,导致 `GufaApp` 整棵树(含 Monaco 容器、DSH ChatDock)反复 re-render,且聊天栏里的 DSH 原生浮层还要等下一次轮询才重定位。
96
+ - 方案:拖拽中只写根节点 CSS 变量(`--gufa-w-explorer / --gufa-w-chat / --gufa-h-terminal`),用 rAF 合帧、不触发 React;松手时才 `setSize` 一次并写 localStorage。终端/Monaco 靠自己的 ResizeObserver 自适应;ChatDock 监听 `layout:resize` 事件逐帧重定位原生浮层。
97
+ - 组件尺寸统一走 `var(--gufa-*, 数值px)`,`useLayoutEffect` 在首帧前同步变量,避免恢复持久化宽度时闪一下。
98
+
99
+ ## 0.17 Cmd+点击跳转定义改回 Monaco 原生链路(1.3.120)
100
+
101
+ - 旧实现:自定义 DOM mousedown → 先 setPosition 再 `instance.getAction('editor.action.revealDefinition').run()`,但**没有先把光标移到点击位置**,native action 在旧光标处解析;失败后再走 Host 搜索兜底,导致“有时跳错、有时没反应、hover 还要等项目级搜索”。
102
+ - 新实现:
103
+ - 用 `monaco.languages.registerDefinitionProvider` 给 JS/TS/Python 注册 provider;JS/TS 后端改用 **TypeScript LanguageService 的 `getDefinitionAtPosition`**(`host/ts-definition.js` / `code.tsDefinition`),不再用正则项目搜索(正则会出现同名函数跳到别的文件);Python 用 pyright `lsp.definition`;
104
+ - 用 `monaco.editor.registerEditorOpener` 把 Monaco 打开的 `file://` 位置转成 App 的 `editor:open-at`;
105
+ - Cmd+点击只做「focus + setPosition(点击位置) + 触发原生 revealDefinition」,F12 同样走原生;多结果由 Monaco 原生 peek 处理;
106
+ - 同时用 `setModeConfiguration({...mode, definitions:false})` 关掉 Monaco TS worker 自带的 definition provider,避免它和 Host 结果合并/跳错;
107
+ - Cmd 悬停不再跑 Host 搜索,按住 Cmd 立即给当前单词下划线/手型,真正解析只在点击时发生。
108
+ - 注意:`gufaRegisterDefinitionInfrastructure` 全局只注册一次(`G.__gufaDefinitionInfra`),provider 内动态读 `G.projectRoot`,HMR/多窗口都复用。
109
+
110
+ ## 0.18 ⌘+点击内置 API 跳到 TS lib(1.3.126)
111
+
112
+ - `parseInt` 这类系统 API 的定义在 `node_modules/typescript/lib/*.d.ts`,不在项目根内。旧 `code.tsDefinition` 把 root 外的定义全过滤掉,客户端拿不到结果;而旧兜底 `code.definition` 是正则项目搜索,会把 `parseInt` 当成普通单词,跳到项目里别的使用处(用户看到的“乱跳”)。
113
+ - 现在:`tsDefinition` 允许返回 TypeScript lib 内的定义(`external: true, absolutePath`);Cmd+点击不再经过 Monaco 原生动作/正则兜底,直接调 `code.tsDefinition`:
114
+ - 项目内定义 → `editor:open-at`;
115
+ - 系统 lib → `editor:open-external`,App 调 `code.readTsLib` 以只读标签打开(`~typescript/lib.es5.d.ts`),编辑器 `readOnly=true`,保存/自动保存跳过。
116
+ - `code.readTsLib` 只允许读 `typescript/lib` 下的 `.d.ts/.ts/.js`,不是任意路径读取。
117
+
118
+ ## 0.19 Monaco 原生功能审计(1.3.127)
119
+
120
+ 用户质问「本项目外定义全过滤」后,逐项核对我们对 Monaco 原生行为的覆盖:
121
+
122
+ | 能力 | 状态 |
123
+ | --- | --- |
124
+ | JS/TS **F12 Go to Definition** | 1.3.121 曾用 `setModeConfiguration({definitions:false})` 关掉原生 TS DefinitionProvider,属于误伤;**1.3.127 已恢复**,F12 重新走 Monaco 原生 TS worker;系统 lib(parseInt 等)由 `registerEditorOpener` 转成只读 `~typescript/lib*.d.ts` 标签 |
125
+ | JS/TS **Cmd+点击** | Monaco standalone **本来就没有** VS Code 层的定义链接(tsMode 只注册 DefinitionProvider/Hover,不注册 LinkProvider);所以必须自定义手势。现在 Cmd+点击直接走 Host TypeScript LanguageService(`code.tsDefinition`),不再经过原生动作/旧正则兜底,内置 API 也能跳 lib |
126
+ | JS/TS **diagnostics** | 1.3.117 起关闭 Monaco TS worker 诊断(`noSemanticValidation/noSyntaxValidation=true`),改用 Host tsc + 白名单语义错误(2304/2552/2448/2454)。这是**有意替换**:worker 诊断在 dsh-app 下不稳定,且动态 JS 项目全量语义诊断误报多(2339/2306)。若要恢复原生诊断,需同时接受这些误报 |
127
+ | AI Tab 补全 | 从来是自研(不是 Monaco 内置),用户要求移除,已删 |
128
+ | `automaticLayout` | 只在拖拽分割条期间临时关闭,松手恢复并 layout 一次(性能优化,不是功能删除) |
129
+ | 项目根白名单 | `ProjectRegistry` / `fs.read` 只允许项目内路径,这是文件读写安全限制;系统 TS lib 通过只读 `code.readTsLib` 单独放行 |
130
+ | minimap / overview ruler | 初始设计就关闭(视觉取舍),未改过 |
131
+
132
+ 结论:真正误伤原生功能的是「TS DefinitionProvider 被禁用」和「项目外定义被过滤」,1.3.126/1.3.127 已修正;diagnostics 是有意替换,若要原生诊断需要接受误报或用更细的过滤。
133
+
134
+ ## 0.20 Cmd+点击与 F12 统一(1.3.128)
135
+
136
+ - Monaco 的 F12 是内置 action:`editor.action.revealDefinition` → 查询所有 `registerDefinitionProvider` → 通过 `ICodeEditorService` + `registerEditorOpener` 打开。Cmd+点击不是 action,Monaco standalone 没有鼠标手势;`tsMode.js` 只注册 DefinitionProvider/Hover,不注册 LinkProvider(VS Code 的 Cmd+点击是 workbench 层另做的),所以鼠标事件必须自定义。
137
+ - 之前为了绕开不稳定的 TS worker,Cmd+点击走了 Host LanguageService 另一套解析,导致 F12 和 Cmd+点击行为不一致;1.3.123 恢复原生 TS DefinitionProvider 后,1.3.128 把 Cmd+点击改成:
138
+ 1. `focus()` + `setPosition(点击位置)`;
139
+ 2. 直接 `instance.getAction('editor.action.revealDefinition').run()`;
140
+ 3. 同一个 `registerEditorOpener` 打开项目文件或只读 `~typescript/lib*.d.ts`。
141
+ - 也就是说 Cmd+点击现在和 F12 **完全同一条代码路径**,不再有自己的解析/兜底。唯一的自定义只是「把鼠标事件翻译成这个 action」这一层。
142
+
87
143
  ## 1. 弹窗/菜单层级:只有一个正确做法(反复踩过多次,最终定案)
88
144
 
89
145
  **现象**:弹窗被右侧「古法 AI」聊天栏压住、只显示一半、关闭按钮点不到;或者反过来把官方设置/会话弹窗盖住。
package/docs/RELEASE.md CHANGED
@@ -1,6 +1,13 @@
1
1
  # 发布流程(维护者)
2
2
 
3
- ## 一键发布:打 tag + 建 GitHub Release
3
+ ## ⚠️ 发布规则(用户明确要求)
4
+
5
+ - **只有用户明确说「发布 / 发版」时才发布 npm**。日常改 bug、跑测试、构建本地 client/helper 都不发布。
6
+ - 创建 GitHub Release **不再自动触发 npm 发布**(`publish.yml` 只保留 `workflow_dispatch`)。
7
+ - 用户未要求发布时:本地 commit / push main 可以(只会跑 test,不会发 npm),但**不要**打新 tag、不要 `gh release create`。
8
+ - 用户要求发布时:按下面流程 bump/tag/release,然后手动触发 `publish.yml`。
9
+
10
+ ## 发布流程:打 tag + 建 GitHub Release + 手动触发 npm
4
11
 
5
12
  1. 确认 `package.json` 版本号已更新(`npm version patch --no-git-tag-version` 或手改);
6
13
  2. 提交并推送 tag:
@@ -11,10 +18,12 @@
11
18
  ```bash
12
19
  gh release create v1.3.x --title "..." --notes "..."
13
20
  ```
14
- 4. 触发两个 workflow:
15
- - `.github/workflows/publish.yml`:**npm trusted publishing(OIDC provenance)自动发布**,不需要本地 npm token / 2FA;
16
- - `.github/workflows/build-float.yml`:三平台编译 helper + 严格冒烟,并把二进制作为 release assets 附上。
17
- 5. 验证:`npm view dsh-gufa-code version`、Release 页面 assets。
21
+ 4. Release 会触发 `.github/workflows/build-float.yml`(三平台编译 helper + 严格冒烟,二进制作为 release assets);
22
+ 5. **用户明确要求发布时**,手动触发 npm(trusted publishing / OIDC provenance,不需要本地 token):
23
+ ```bash
24
+ gh workflow run publish.yml --repo liujiannanchenjbguo/dsh-gufa-code
25
+ ```
26
+ 6. 验证:`npm view dsh-gufa-code version`、Release 页面 assets。
18
27
 
19
28
  ## 本地发布(不推荐,需要 npm 2FA)
20
29
 
package/host/fs.js CHANGED
@@ -285,6 +285,30 @@ export function register(router, env) {
285
285
  /* Python 语言服务(LSP/pyright):/lsp/definition API;Cmd+点击与悬停由客户端调用 */
286
286
  registerLsp(router, env)
287
287
 
288
+ /* JS/TS 定义解析(Monaco DefinitionProvider 用):LanguageService 比正则项目搜索准确 */
289
+ router.method('code.tsDefinition', async (body) => {
290
+ let stamp = '0'
291
+ try {
292
+ stamp = String(statSync(new URL('./ts-definition.js', import.meta.url)).mtimeMs)
293
+ } catch {
294
+ stamp = '0'
295
+ }
296
+ const module = await import(new URL(`./ts-definition.js?gufa-tsdef=${stamp}`, import.meta.url).href)
297
+ return module.tsDefinition(body, env)
298
+ })
299
+
300
+ /* 只读读取 TypeScript 内置 lib(parseInt/Promise 等系统 API 定义) */
301
+ router.method('code.readTsLib', async (body) => {
302
+ let stamp = '0'
303
+ try {
304
+ stamp = String(statSync(new URL('./ts-definition.js', import.meta.url)).mtimeMs)
305
+ } catch {
306
+ stamp = '0'
307
+ }
308
+ const module = await import(new URL(`./ts-definition.js?gufa-tsdef=${stamp}`, import.meta.url).href)
309
+ return module.readTsLib(body)
310
+ })
311
+
288
312
  /* JS/TS 诊断:TypeScript 编译器在 Host 侧跑,返回 Monaco marker 需要的位置 */
289
313
  router.method('lint.javascript', async (body) => {
290
314
  let stamp = '0'
package/host/lint.js CHANGED
@@ -22,6 +22,10 @@ const IGNORED_CODES = new Set([
22
22
  2580, // Cannot find name 'require' 等(由 globals shim 兜底,仍兜不住时静默)
23
23
  ])
24
24
 
25
+ /** 只保留用户真正需要的语义诊断:未定义变量(2304/2552)等;
26
+ * 属性类型不匹配(2339 等)在动态 JS/JSON 配置项目里误报太多,直接不展示。 */
27
+ const SEMANTIC_CODES = new Set([2304, 2552, 2448, 2454])
28
+
25
29
  const GLOBALS_FILE = '/__gufa_code_globals__.d.ts'
26
30
  const GLOBALS_TEXT = [
27
31
  'declare var process: any;',
@@ -161,7 +165,10 @@ export async function diagnose(body, env) {
161
165
  const program = ts.createProgram(rootNames, options, host)
162
166
  const sourceFile = program.getSourceFile(canonical(absolute))
163
167
  if (sourceFile === undefined || sourceFile === null) return { diagnostics: [] }
164
- const collected = [...program.getSyntacticDiagnostics(sourceFile), ...program.getSemanticDiagnostics(sourceFile)]
168
+ /* 语法错误全保留;语义只保留「未定义变量」这类,避免动态 JS 项目的类型误报 */
169
+ const syntactic = program.getSyntacticDiagnostics(sourceFile)
170
+ const semantic = program.getSemanticDiagnostics(sourceFile).filter((diagnostic) => SEMANTIC_CODES.has(Number(diagnostic.code)))
171
+ const collected = [...syntactic, ...semantic]
165
172
  const diagnostics = []
166
173
  const seenDiagnostics = new Set()
167
174
  for (const diagnostic of collected) {
@@ -0,0 +1,212 @@
1
+ /**
2
+ * JS/TS 定义解析(供 Monaco 原生 DefinitionProvider / F12 / Cmd+点击使用)。
3
+ *
4
+ * 和 host/lint.js 一样把当前编辑内容 + 本地 import 组成一个 TypeScript Program,
5
+ * 但这里用 LanguageService 的 getDefinitionAtPosition:比原来的正则项目搜索准确,
6
+ * 不会再因为同名函数/变量跳到别的文件。
7
+ */
8
+ import { readFile } from 'node:fs/promises'
9
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
10
+
11
+ import ts from 'typescript'
12
+
13
+ import { ApiError, badRequest } from './context.js'
14
+
15
+ const GLOBALS_FILE = '/__gufa_code_tsdef_globals__.d.ts'
16
+ const GLOBALS_TEXT = 'declare var process: any;\ndeclare var require: any;\ndeclare var module: any;\ndeclare var exports: any;\n'
17
+
18
+ function inside(root, target) {
19
+ const rel = relative(root, target)
20
+ return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))
21
+ }
22
+
23
+ function compilerOptions(root) {
24
+ return {
25
+ allowJs: true,
26
+ checkJs: true,
27
+ noEmit: true,
28
+ target: ts.ScriptTarget.ES2022,
29
+ module: ts.ModuleKind.ESNext,
30
+ moduleResolution: ts.ModuleResolutionKind.NodeJs,
31
+ jsx: ts.JsxEmit.Preserve,
32
+ esModuleInterop: true,
33
+ allowSyntheticDefaultImports: true,
34
+ resolveJsonModule: true,
35
+ skipLibCheck: true,
36
+ skipDefaultLibCheck: true,
37
+ strict: false,
38
+ noImplicitAny: false,
39
+ types: [],
40
+ lib: ['lib.es2022.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
41
+ allowNonTsExtensions: true,
42
+ baseUrl: root,
43
+ }
44
+ }
45
+
46
+ function collectScriptFiles(root, currentAbsolute, currentContent) {
47
+ const virtual = new Map([[currentAbsolute, currentContent], [GLOBALS_FILE, GLOBALS_TEXT]])
48
+ const scriptFiles = [currentAbsolute, GLOBALS_FILE]
49
+ const seen = new Set(scriptFiles)
50
+ const queue = [currentAbsolute]
51
+ while (queue.length > 0 && seen.size <= 40) {
52
+ const file = queue.shift()
53
+ const text = virtual.get(file) ?? ts.sys.readFile(file)
54
+ if (typeof text !== 'string') continue
55
+ let pre = null
56
+ try {
57
+ pre = ts.preProcessFile(text, true, true)
58
+ } catch {
59
+ continue
60
+ }
61
+ const specs = [...(pre.importedFiles ?? []), ...(pre.referencedFiles ?? [])]
62
+ for (const spec of specs) {
63
+ try {
64
+ const resolution = ts.resolveModuleName(spec.fileName, file, compilerOptions(root), {
65
+ fileExists: ts.sys.fileExists,
66
+ readFile: ts.sys.readFile,
67
+ })
68
+ const resolved = resolution.resolvedModule?.resolvedFileName
69
+ if (typeof resolved !== 'string' || resolved === '' || !inside(root, resolved)) continue
70
+ const key = resolve(resolved)
71
+ if (seen.has(key)) continue
72
+ seen.add(key)
73
+ scriptFiles.push(key)
74
+ queue.push(key)
75
+ } catch {
76
+ /* ignore */
77
+ }
78
+ }
79
+ }
80
+ return { scriptFiles, virtual }
81
+ }
82
+
83
+ export async function tsDefinition(body, env) {
84
+ if (typeof body.root !== 'string' || body.root === '') throw badRequest('root is required')
85
+ const project = env.projects.ensure(body.root)
86
+ const root = project.root
87
+ const rawPath = typeof body.path === 'string' ? body.path : ''
88
+ if (rawPath === '') throw badRequest('path is required')
89
+ const absolute = resolve(root, rawPath)
90
+ if (!inside(root, absolute)) throw new ApiError('path-outside', '路径超出项目范围', 403)
91
+ const extension = rawPath.split('.').pop()?.toLowerCase() ?? ''
92
+ if (!['js', 'jsx', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts'].includes(extension)) return { matches: [] }
93
+ const line = Math.max(1, Math.trunc(Number(body.line) || 1))
94
+ const column = Math.max(1, Math.trunc(Number(body.column) || 1))
95
+ let content = typeof body.content === 'string' ? body.content : ''
96
+ if (content === '') {
97
+ try {
98
+ content = await readFile(absolute, 'utf8')
99
+ } catch {
100
+ throw new ApiError('not-found', `文件不存在:${rawPath}`, 404)
101
+ }
102
+ }
103
+
104
+ const { scriptFiles, virtual } = collectScriptFiles(root, absolute, content)
105
+ const options = compilerOptions(root)
106
+ const host = {
107
+ getScriptFileNames: () => scriptFiles,
108
+ getScriptVersion: (fileName) => (virtual.has(resolve(fileName)) ? '1' : '0'),
109
+ getScriptSnapshot: (fileName) => {
110
+ const key = resolve(fileName)
111
+ const text = virtual.get(key) ?? ts.sys.readFile(key)
112
+ if (text === undefined) return undefined
113
+ return ts.ScriptSnapshot.fromString(text)
114
+ },
115
+ getCurrentDirectory: () => root,
116
+ getCompilationSettings: () => options,
117
+ getDefaultLibFileName: (compileOptions) => ts.getDefaultLibFilePath(compileOptions),
118
+ fileExists: (fileName) => virtual.has(resolve(fileName)) || ts.sys.fileExists(fileName),
119
+ readFile: (fileName) => virtual.get(resolve(fileName)) ?? ts.sys.readFile(fileName),
120
+ readDirectory: ts.sys.readDirectory,
121
+ directoryExists: ts.sys.directoryExists,
122
+ getDirectories: ts.sys.getDirectories,
123
+ getCanonicalFileName: (fileName) => fileName,
124
+ useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
125
+ getNewLine: () => '\n',
126
+ }
127
+ let languageService = null
128
+ try {
129
+ languageService = ts.createLanguageService(host)
130
+ } catch {
131
+ languageService = null
132
+ }
133
+ if (languageService === null) return { matches: [] }
134
+ let definitions = []
135
+ try {
136
+ const program = languageService.getProgram()
137
+ const sourceFile = program?.getSourceFile(absolute)
138
+ if (sourceFile === undefined || sourceFile === null) return { matches: [] }
139
+ const offset = ts.getPositionOfLineAndCharacter(sourceFile, Math.min(sourceFile.getLineStarts().length - 1, line - 1), column - 1)
140
+ definitions = languageService.getDefinitionAtPosition(absolute, offset) ?? []
141
+ } catch {
142
+ definitions = []
143
+ }
144
+ const libDir = dirname(ts.getDefaultLibFilePath(options))
145
+ const matches = []
146
+ const seen = new Set()
147
+ for (const definition of definitions) {
148
+ if (definition === null || definition === undefined) continue
149
+ const fileName = resolve(definition.fileName)
150
+ const internal = inside(root, fileName)
151
+ /* 项目内定义正常返回;TS 内置 lib(parseInt/Promise 等)也返回,
152
+ 客户端会以只读标签打开 node_modules/typescript/lib/*.d.ts。 */
153
+ if (!internal && !inside(libDir, fileName)) continue
154
+ let defSource = null
155
+ try {
156
+ defSource = languageService.getProgram()?.getSourceFile(fileName)
157
+ } catch {
158
+ defSource = null
159
+ }
160
+ if (defSource === undefined || defSource === null) continue
161
+ const start = Math.max(0, Number(definition.textSpan?.start) || 0)
162
+ const position = ts.getLineAndCharacterOfPosition(defSource, start)
163
+ const path = internal ? relative(root, fileName).split(sep).join('/') : relative(libDir, fileName).split(sep).join('/')
164
+ const key = `${internal ? 'in' : 'lib'}:${fileName}:${position.line + 1}:${position.character + 1}`
165
+ if (seen.has(key)) continue
166
+ seen.add(key)
167
+ matches.push({
168
+ path,
169
+ absolutePath: internal ? undefined : fileName,
170
+ external: internal ? undefined : true,
171
+ line: position.line + 1,
172
+ column: position.character + 1,
173
+ kind: internal ? 'lsp' : 'lib',
174
+ preview: internal ? '' : `typescript/lib/${path}`,
175
+ score: internal ? 1000 : 900,
176
+ })
177
+ if (matches.length >= 8) break
178
+ }
179
+ return { matches }
180
+ }
181
+
182
+ const LIB_EXTENSIONS = new Set(['.d.ts', '.ts', '.js'])
183
+
184
+ /** 只读打开 TypeScript 内置 lib(parseInt/Promise/Array 等定义)用。 */
185
+ export async function readTsLib(body) {
186
+ const libDir = dirname(ts.getDefaultLibFilePath({}))
187
+ const libName = typeof body.libName === 'string' ? body.libName.trim() : ''
188
+ const rawPath = typeof body.absolutePath === 'string' ? body.absolutePath : ''
189
+ let absolute = ''
190
+ if (libName !== '') {
191
+ if (!/^lib\.[A-Za-z0-9._-]+\.d\.ts$/.test(libName)) throw new ApiError('forbidden', '非法的 TypeScript lib 名称', 403)
192
+ absolute = resolve(libDir, libName)
193
+ } else {
194
+ if (rawPath === '') throw new ApiError('bad-request', 'absolutePath is required', 400)
195
+ absolute = resolve(rawPath)
196
+ }
197
+ if (!inside(libDir, absolute)) throw new ApiError('forbidden', '只允许读取 TypeScript 内置 lib 文件', 403)
198
+ const extension = absolute.slice(absolute.lastIndexOf('.')).toLowerCase()
199
+ if (!LIB_EXTENSIONS.has(extension)) throw new ApiError('forbidden', '不允许的文件类型', 403)
200
+ const content = await readFile(absolute, 'utf8')
201
+ return {
202
+ content,
203
+ language: 'typescript',
204
+ absolutePath: absolute,
205
+ name: absolute.slice(absolute.lastIndexOf('/') + 1),
206
+ }
207
+ }
208
+
209
+ export function registerTsDefinition(router, env) {
210
+ router.method('code.tsDefinition', (body) => tsDefinition(body, env))
211
+ router.method('code.readTsLib', (body) => readTsLib(body))
212
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.117",
3
+ "version": "1.3.133",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -149,8 +149,52 @@ try {
149
149
  content: 'const = 1\n',
150
150
  })
151
151
  check('lint reports syntax error', lintSyntax.diagnostics.some((item) => item.severity === 1 && item.code === 1134), JSON.stringify(lintSyntax.diagnostics))
152
+ const lintNoisy = await call(router, 'lint.javascript', {
153
+ root,
154
+ path: 'src/lint-sample.js',
155
+ language: 'javascript',
156
+ content: 'const someObject = {}\nsomeObject.missingProperty\n',
157
+ })
158
+ check('lint suppresses dynamic property warnings', lintNoisy.diagnostics.length === 0, JSON.stringify(lintNoisy.diagnostics))
152
159
  await call(router, 'fs.delete', { root, path: 'src/lint-sample.js' }).catch(() => {})
153
160
 
161
+ console.log('code.tsDefinition')
162
+ await call(router, 'fs.create', { root, path: 'src/tsdef-sample.js', kind: 'file' })
163
+ await call(router, 'fs.write', {
164
+ root,
165
+ path: 'src/tsdef-sample.js',
166
+ content: 'function zzDefinitionTarget() {\n return 1\n}\nzzDefinitionTarget()\n',
167
+ })
168
+ const tsDefResult = await call(router, 'code.tsDefinition', {
169
+ root,
170
+ path: 'src/tsdef-sample.js',
171
+ line: 4,
172
+ column: 1,
173
+ content: 'function zzDefinitionTarget() {\n return 1\n}\nzzDefinitionTarget()\n',
174
+ })
175
+ check('tsDefinition resolves local function', tsDefResult.matches.length > 0 && tsDefResult.matches[0].path === 'src/tsdef-sample.js' && tsDefResult.matches[0].line === 1, JSON.stringify(tsDefResult.matches))
176
+ check('tsDefinition lands on function name column', tsDefResult.matches[0].column === 10, JSON.stringify(tsDefResult.matches))
177
+ const tsLibResult = await call(router, 'code.tsDefinition', {
178
+ root,
179
+ path: 'src/tsdef-sample.js',
180
+ line: 1,
181
+ column: 18,
182
+ content: 'const zzParsed = parseInt("42", 10)\n',
183
+ })
184
+ check('tsDefinition resolves builtin to TS lib', tsLibResult.matches.some((item) => item.external === true && String(item.absolutePath || '').includes('/typescript/lib/lib.')), JSON.stringify(tsLibResult.matches))
185
+ const tsLibApi = await call(router, 'code.readTsLib', { absolutePath: tsLibResult.matches.find((item) => item.external === true)?.absolutePath ?? '' })
186
+ check('readTsLib returns d.ts content', typeof tsLibApi.content === 'string' && tsLibApi.content.includes('parseInt') && tsLibApi.language === 'typescript')
187
+ const tsLibByName = await call(router, 'code.readTsLib', { libName: 'lib.es5.d.ts' })
188
+ check('readTsLib by libName', typeof tsLibByName.content === 'string' && tsLibByName.content.includes('parseInt'), String(tsLibByName.content?.length))
189
+ let badLibName = false
190
+ try {
191
+ await call(router, 'code.readTsLib', { libName: '../package.json' })
192
+ } catch (error) {
193
+ badLibName = error.code === 'forbidden'
194
+ }
195
+ check('readTsLib rejects traversal', badLibName)
196
+ await call(router, 'fs.delete', { root, path: 'src/tsdef-sample.js' }).catch(() => {})
197
+
154
198
  console.log('fs.search')
155
199
  await call(router, 'fs.create', { root, path: 'search.txt', kind: 'file' })
156
200
  await call(router, 'fs.write', { root, path: 'search.txt', content: 'Alpha beta\nBETA gamma\nbeta BETA\n' })
@@ -1684,6 +1684,8 @@ html[data-platform=darwin][data-fullscreen] .gufa-titlebar{height:44px;padding-l
1684
1684
  .gufa-breadcrumb b{font-weight:500;color:var(--gufa-text)}
1685
1685
  .gufa-editor-host{flex:1 1 auto;position:relative;min-height:0;min-width:0;overflow:hidden}
1686
1686
  .gufa-def-link{text-decoration:underline;text-decoration-color:var(--gufa-accent);text-decoration-thickness:1px;text-underline-offset:2px;cursor:pointer}
1687
+ /* Cmd 悬停:只变正经链接蓝,不下划线、不弹框 */
1688
+ .gufa-def-link-color{color:#4aa8ff!important;text-decoration:none!important;cursor:pointer}
1687
1689
  .monaco-editor.gufa-def-hover .view-lines{cursor:pointer}
1688
1690
  .gufa-editor-fallback{position:absolute;inset:0;overflow:auto;margin:0;padding:14px 18px;font:12.5px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre;tab-size:2}
1689
1691
  .gufa-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;height:100%;padding:28px;