dsh-gufa-code 1.3.215 → 1.3.234

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.
Binary file
Binary file
Binary file
package/host/code.js CHANGED
@@ -190,7 +190,67 @@ function importTargetPaths(currentPath, spec) {
190
190
  ]
191
191
  }
192
192
 
193
- async function listCandidates(root, textBudgets) {
193
+ /** 解析 PHP 的 use 语句:短类名 → 完全限定类名(支持 as 别名 / use function / use const)。 */
194
+ function parsePhpImports(text) {
195
+ const map = new Map()
196
+ const useRe = /^[ \t]*use[ \t]+(?:function[ \t]+|const[ \t]+)?([A-Za-z_][\w\\]*)(?:[ \t]+as[ \t]+([A-Za-z_]\w*))?[ \t]*;/gm
197
+ let match
198
+ while ((match = useRe.exec(String(text))) !== null) {
199
+ const fqcn = match[1]
200
+ const segments = fqcn.split('\\').filter((part) => part !== '')
201
+ if (segments.length === 0) continue
202
+ const alias = match[2] !== undefined ? match[2] : segments[segments.length - 1]
203
+ if (/^[A-Za-z_]\w*$/.test(alias)) map.set(alias, fqcn)
204
+ }
205
+ return map
206
+ }
207
+
208
+ /** 读 composer.json 的 PSR-4 映射,按 mtime 缓存。 */
209
+ const PSR4_CACHE = new Map()
210
+ async function psr4Map(root) {
211
+ let stamp = 'none'
212
+ try {
213
+ stamp = String((await stat(join(root, 'composer.json'))).mtimeMs)
214
+ } catch {
215
+ stamp = 'none'
216
+ }
217
+ const cached = PSR4_CACHE.get(root)
218
+ if (cached !== undefined && cached.stamp === stamp) return cached.map
219
+ let map = {}
220
+ try {
221
+ const parsed = JSON.parse(await readFile(join(root, 'composer.json'), 'utf8'))
222
+ const autoload = parsed !== null && typeof parsed === 'object' ? parsed.autoload : null
223
+ const psr4 = autoload !== null && typeof autoload === 'object' ? autoload['psr-4'] : null
224
+ if (psr4 !== null && typeof psr4 === 'object') {
225
+ for (const [prefix, target] of Object.entries(psr4)) {
226
+ const value = Array.isArray(target) ? target[0] : target
227
+ if (typeof value !== 'string') continue
228
+ map[String(prefix).replace(/\\+$/, '')] = value.replace(/\/+$/, '').replace(/^\.\//, '')
229
+ }
230
+ }
231
+ } catch {
232
+ map = {}
233
+ }
234
+ PSR4_CACHE.set(root, { stamp, map })
235
+ return map
236
+ }
237
+
238
+ /** 完全限定 PHP 类名 → 项目内相对路径候选(PSR-4)。 */
239
+ async function phpClassPaths(root, fqcn) {
240
+ const name = String(fqcn).replace(/^\\/, '')
241
+ const psr4 = await psr4Map(root)
242
+ const paths = []
243
+ for (const [prefix, dir] of Object.entries(psr4)) {
244
+ if (name !== prefix && !name.startsWith(`${prefix}\\`)) continue
245
+ const rest = name.slice(prefix.length).replace(/^\\/, '').replace(/\\/g, '/')
246
+ if (rest === '') continue
247
+ const base = dir === '' ? rest : `${dir}/${rest}`
248
+ paths.push(`${base}.php`, `${base}/index.php`)
249
+ }
250
+ return paths
251
+ }
252
+
253
+ /** 解析当前文件的 import/require,得到 标识符 → 模块 spec 的映射。 */async function listCandidates(root, textBudgets) {
194
254
  /* Git 项目用 git ls-files(尊重 .gitignore、含未跟踪文件),否则 BFS 遍历。 */
195
255
  let isGit = false
196
256
  try {
@@ -269,6 +329,13 @@ function findDefinitionsInText(text, relPath, word, patterns, results, current)
269
329
  for (const pattern of patterns) {
270
330
  const match = pattern.regex.exec(line)
271
331
  if (match === null) continue
332
+ /* method 模式的修饰符段会把调用语句当成定义(`throw new X(...)` 的 `throw new ` 也符合),
333
+ 导致跳到调用行自身;按前缀关键字排除。 */
334
+ if (pattern.kind === 'method') {
335
+ const wordIndex = match[0].indexOf(match[1])
336
+ const prefix = wordIndex >= 0 ? match[0].slice(0, wordIndex) : ''
337
+ if (/(?:^|\s)(?:new|throw|return|echo|print|yield|await|instanceof|elseif|else|while|for|foreach|switch|case|catch|if|require|include)\s*$/.test(prefix)) continue
338
+ }
272
339
  const column = (match.index ?? 0) + match[0].indexOf(match[1]) + 1
273
340
  results.push({
274
341
  path: relPath,
@@ -321,6 +388,22 @@ export async function definition(body, env) {
321
388
  const importMap = parseImportMap(text)
322
389
  const importedSpec = importMap.get(word)
323
390
  const importTargets = new Set(importedSpec === undefined ? [] : importTargetPaths(relPath, importedSpec))
391
+ /* PHP:use 导入 + composer.json PSR-4;静态调用 ItemLogic::getItemData 点到方法名时按限定符反查 */
392
+ try {
393
+ const phpImports = parsePhpImports(text)
394
+ if (phpImports.size > 0) {
395
+ const owners = []
396
+ if (phpImports.has(word)) owners.push(word)
397
+ const prefix = lineText.slice(0, Math.max(column, 1))
398
+ const qualified = /([A-Za-z_]\w*)::\s*[\A-Za-z_0-9]*$/.exec(prefix)
399
+ if (qualified !== null && phpImports.has(qualified[1]) && !owners.includes(qualified[1])) owners.push(qualified[1])
400
+ for (const owner of owners) {
401
+ for (const target of await phpClassPaths(root, phpImports.get(owner))) importTargets.add(target)
402
+ }
403
+ }
404
+ } catch {
405
+ /* PHP 解析失败不影响其它语言 */
406
+ }
324
407
  const results = []
325
408
  /* 1) 当前文件(用编辑器传来的内容,能命中未保存的改动) */
326
409
  findDefinitionsInText(text, relPath, word, patterns, results, current)
@@ -420,7 +503,5 @@ export async function resolvePath(body, env) {
420
503
  return { path: pool[0], matches: pool.slice(0, 10) }
421
504
  }
422
505
 
423
- export function register(router, env) {
424
- router.method('code.definition', (body) => definition(body, env))
425
- router.method('code.resolvePath', (body) => resolvePath(body, env))
426
- }
506
+ /** 故意不注册路由:code.definition/code.resolvePath 由 host/fs.js 统一注册(热重载入口)。 */
507
+ export function register() {}
package/host/fs.js CHANGED
@@ -6,12 +6,12 @@ import { createHash, randomUUID } from 'node:crypto'
6
6
  import { statSync } from 'node:fs'
7
7
  import { createReadStream } from 'node:fs'
8
8
  import { access, cp, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
9
- import { execFile } from 'node:child_process'
9
+ import { execFile, spawn } from 'node:child_process'
10
10
  import { promisify } from 'node:util'
11
11
  import { constants } from 'node:fs'
12
12
  import { tmpdir } from 'node:os'
13
13
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
14
- import { fileURLToPath } from 'node:url'
14
+ import { fileURLToPath, pathToFileURL } from 'node:url'
15
15
  import { ApiError, badRequest } from './context.js'
16
16
  import { registerLsp } from './lsp.js'
17
17
 
@@ -99,7 +99,31 @@ async function readClipboardFilePaths() {
99
99
  'JSON.stringify(out);',
100
100
  ].join('\n')
101
101
  const { stdout } = await runCommand('osascript', ['-l', 'JavaScript', '-e', script], { timeout: 5000, maxBuffer: 2 * 1024 * 1024 })
102
- return parseClipboardPaths(stdout)
102
+ const direct = parseClipboardPaths(stdout)
103
+ if (direct.length > 0) return direct
104
+ /* 古法编程自己拷的文件是 AppleScript alias 列表(不是 Finder 的 file-url 项),
105
+ 用 the clipboard as list 再取一次 POSIX 路径。 */
106
+ const listScript = [
107
+ 'on run',
108
+ 'try',
109
+ 'set theList to the clipboard as list',
110
+ 'on error',
111
+ 'return ""',
112
+ 'end try',
113
+ 'set out to ""',
114
+ 'repeat with f in theList',
115
+ 'try',
116
+ 'set out to out & POSIX path of f & linefeed',
117
+ 'end try',
118
+ 'end repeat',
119
+ 'return out',
120
+ 'end run',
121
+ ].join('\n')
122
+ const fallback = await runCommand('osascript', ['-e', listScript], { timeout: 5000, maxBuffer: 2 * 1024 * 1024 }).catch(() => ({ stdout: '' }))
123
+ return String(fallback.stdout ?? '')
124
+ .split(/\r?\n/)
125
+ .map((line) => line.trim())
126
+ .filter((line) => line !== '')
103
127
  }
104
128
  if (process.platform === 'win32') {
105
129
  const script = [
@@ -144,6 +168,57 @@ function parseClipboardPaths(stdout) {
144
168
  }
145
169
  }
146
170
 
171
+ /** 把项目内文件/文件夹路径写进系统剪贴板(file URL),供另一个古法编程实例/系统粘贴。 */
172
+ async function writeClipboardFilePaths(paths) {
173
+ const list = paths.filter((item) => typeof item === 'string' && item !== '')
174
+ if (list.length === 0) return false
175
+ try {
176
+ if (process.platform === 'darwin') {
177
+ /* 用 AppleScript 写 alias 列表:JXA 的 writeObjects 在 osascript 退出后剪贴板会丢,
178
+ AppleScript 的 set the clipboard to {POSIX file ...} 能跨进程保留。 */
179
+ const script = [
180
+ 'on run argv',
181
+ 'set out to {}',
182
+ 'repeat with p in argv',
183
+ 'set end of out to POSIX file p',
184
+ 'end repeat',
185
+ 'set the clipboard to out',
186
+ 'end run',
187
+ ].join('\n')
188
+ await runCommand('osascript', ['-e', script, ...list], { timeout: 8000, maxBuffer: 1024 * 1024 })
189
+ return true
190
+ }
191
+ if (process.platform === 'win32') {
192
+ const script = [
193
+ '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8;',
194
+ 'Add-Type -AssemblyName System.Windows.Forms;',
195
+ '$paths = ConvertFrom-Json $env:GUFA_CLIP_PATHS;',
196
+ '$col = New-Object System.Collections.Specialized.StringCollection;',
197
+ 'foreach ($item in @($paths)) { [void]$col.Add([string]$item) }',
198
+ '[System.Windows.Forms.Clipboard]::SetFileDropList($col);',
199
+ ].join('\n')
200
+ await runCommand('powershell', ['-NoProfile', '-NonInteractive', '-Sta', '-Command', script], {
201
+ timeout: 8000,
202
+ maxBuffer: 1024 * 1024,
203
+ env: { ...process.env, GUFA_CLIP_PATHS: JSON.stringify(list) },
204
+ })
205
+ return true
206
+ }
207
+ /* Linux:xclip 写 text/uri-list;没有 xclip 时返回 false 交给前端提示 */
208
+ const uriList = list.map((path) => pathToFileURL(path).href).join('\n') + '\n'
209
+ await new Promise((resolvePromise, reject) => {
210
+ const child = spawn('xclip', ['-selection', 'clipboard', '-t', 'text/uri-list', '-i'], { stdio: ['pipe', 'ignore', 'ignore'] })
211
+ child.once('error', reject)
212
+ child.once('exit', (code) => (code === 0 ? resolvePromise() : reject(new Error(`xclip exit ${code}`))))
213
+ child.stdin.end(uriList)
214
+ })
215
+ return true
216
+ } catch {
217
+ return false
218
+ }
219
+ }
220
+
221
+
147
222
  export async function resolveProjectPath(root, raw, { create = false } = {}) {
148
223
  if (typeof raw !== 'string') throw badRequest('path must be a string')
149
224
  if (isAbsolute(raw)) throw new ApiError('path-invalid', '不允许绝对路径', 400)
@@ -631,6 +706,26 @@ export function register(router, env) {
631
706
  return { copied, failed }
632
707
  })
633
708
 
709
+ /** 把资源管理器选中的文件/文件夹写入系统剪贴板(跨古法编程实例复制粘贴)。 */
710
+ router.method('fs.copyToSystemClipboard', async (body) => {
711
+ const root = await projectOf(env, body)
712
+ const list = Array.isArray(body.from) ? body.from.filter((item) => typeof item === 'string' && item !== '') : []
713
+ if (list.length === 0) throw badRequest('from is required')
714
+ const absolute = []
715
+ for (const raw of list) {
716
+ const source = await resolveProjectPath(root, raw)
717
+ if (source === root) throw new ApiError('refuse', '不能复制项目根目录', 400)
718
+ const info = await stat(source)
719
+ if (info === undefined) continue
720
+ absolute.push(source)
721
+ }
722
+ if (absolute.length === 0) throw new ApiError('not-found', '选中的文件不存在', 404)
723
+ if (!(await writeClipboardFilePaths(absolute))) {
724
+ throw new ApiError('clipboard-failed', '写入系统剪贴板失败(Linux 需要安装 xclip)', 500)
725
+ }
726
+ return { ok: true, count: absolute.length }
727
+ })
728
+
634
729
  /** 把系统剪贴板里的文件匹配回项目内已有文件(供聊天框「粘贴文件→@引用」使用)。 */
635
730
  /** 全项目文本搜索(左侧「搜索」面板用)。返回按文件分组、带上行列号的匹配。 */
636
731
  router.method('fs.search', async (body) => {
@@ -0,0 +1,322 @@
1
+ /**
2
+ * 系统文件关联("古法编程 Open")。
3
+ *
4
+ * 目标:安装插件后,用户在 Finder/资源管理器里右键文件 →「打开方式」能看到「古法编程」;
5
+ * 选中后唤起 DSH,插件读到 pending 请求 → 自动进入 IDE(工作区 = 文件所在目录)并打开文件。
6
+ *
7
+ * macOS 实现:在 ~/Applications 生成一个极薄的 .app 包装(AppleScript applet),
8
+ * 注册 LaunchServices 文档类型;不修改 DSH 本体、不需要管理员权限。
9
+ * Windows/Linux 的实现留待后续补充(当前 route 返回 supported:false)。
10
+ */
11
+ import { execFile } from 'node:child_process'
12
+ import { access, cp, mkdir, readFile, realpath, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
13
+ import { constants, readFileSync, watch } from 'node:fs'
14
+ import { homedir, tmpdir } from 'node:os'
15
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
16
+ import { fileURLToPath } from 'node:url'
17
+ import { promisify } from 'node:util'
18
+ import { ApiError, badRequest } from './context.js'
19
+ import { debugLog } from './dev.js'
20
+
21
+ const run = promisify(execFile)
22
+ const PLUGIN_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
23
+ const PLUGIN_VERSION = (() => {
24
+ try {
25
+ return String(JSON.parse(readFileSync(join(PLUGIN_ROOT, 'package.json'), 'utf8')).version ?? '0')
26
+ } catch {
27
+ return '0'
28
+ }
29
+ })()
30
+ const PENDING_DIR = join(homedir(), '.dsh')
31
+ const PENDING_FILE = join(PENDING_DIR, 'gufa-open-pending.txt')
32
+ const OPENER_ID = 'com.gufa-code.opener'
33
+ const OPENER_NAME = '古法编程'
34
+ const OPENER_APP = join(homedir(), 'Applications', 'GufaCodeOpen.app')
35
+
36
+ /** 注册到「打开方式」的文件扩展名:常见的编程/文本/HTML/Markdown。 */
37
+ export const OPEN_WITH_EXTENSIONS = [
38
+ 'md', 'markdown', 'mdx', 'txt', 'text', 'log', 'rst', 'adoc',
39
+ 'json', 'jsonc', 'json5', 'yml', 'yaml', 'toml', 'ini', 'conf', 'env',
40
+ 'js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx', 'mts', 'cts', 'vue', 'svelte', 'astro',
41
+ 'html', 'htm', 'xhtml', 'css', 'scss', 'sass', 'less',
42
+ 'py', 'pyw', 'rb', 'php', 'phtml', 'go', 'rs', 'java', 'kt', 'kts', 'scala', 'swift', 'm', 'mm',
43
+ 'c', 'h', 'cc', 'cpp', 'cxx', 'hpp', 'hxx', 'cs', 'fs', 'vb',
44
+ 'sh', 'bash', 'zsh', 'fish', 'ps1', 'bat', 'cmd',
45
+ 'sql', 'graphql', 'gql', 'proto', 'tf', 'hcl', 'lua', 'pl', 'pm', 'r', 'dart', 'ex', 'exs',
46
+ 'xml', 'svg', 'csv', 'tsv', 'gitignore', 'editorconfig',
47
+ ]
48
+
49
+ let installPromise = null
50
+
51
+ async function exists(path) {
52
+ try {
53
+ await access(path, constants.F_OK)
54
+ return true
55
+ } catch {
56
+ return false
57
+ }
58
+ }
59
+
60
+ async function plistJson(path) {
61
+ const { stdout } = await run('plutil', ['-convert', 'json', '-o', '-', path], { timeout: 10000, maxBuffer: 8 * 1024 * 1024 })
62
+ return JSON.parse(stdout)
63
+ }
64
+
65
+ async function writePlist(path, value) {
66
+ const jsonPath = `${path}.json`
67
+ await writeFile(jsonPath, JSON.stringify(value), 'utf8')
68
+ await run('plutil', ['-convert', 'xml1', jsonPath], { timeout: 10000 })
69
+ await rename(jsonPath, path)
70
+ }
71
+
72
+ /** 生成 AppleScript applet:接收 Finder 的打开事件,把路径写入 pending 并唤起 DSH。 */
73
+ function openerScript() {
74
+ return [
75
+ 'on open theFiles',
76
+ ' set homePath to POSIX path of (path to home folder)',
77
+ ' set dirPath to homePath & ".dsh"',
78
+ ' set outPath to dirPath & "/gufa-open-pending.txt"',
79
+ ' try',
80
+ ' do shell script "mkdir -p " & quoted form of dirPath',
81
+ ' set fh to open for access (POSIX file outPath) with write permission',
82
+ ' set eof fh to 0',
83
+ ' repeat with f in theFiles',
84
+ ' write ((POSIX path of f) & linefeed) to fh as «class utf8»',
85
+ ' end repeat',
86
+ ' close access fh',
87
+ ' end try',
88
+ ' try',
89
+ ' do shell script "open -b com.deepseek.dsh \'dsh://open\'"',
90
+ ' on error',
91
+ ' try',
92
+ ' do shell script "open -a \'DeepSeek Harness\' \'dsh://open\'"',
93
+ ' end try',
94
+ ' end try',
95
+ 'end open',
96
+ ].join('\r')
97
+ }
98
+
99
+ async function buildOpenerApp() {
100
+ const tmpScript = join(tmpdir(), `gufa-code-open-${process.pid}-${Date.now()}.applescript`)
101
+ const tmpApp = join(tmpdir(), `GufaCodeOpen-${process.pid}-${Date.now()}.app`)
102
+ try {
103
+ await writeFile(tmpScript, openerScript(), 'utf8')
104
+ await rm(tmpApp, { recursive: true, force: true })
105
+ await run('osacompile', ['-o', tmpApp, tmpScript], { timeout: 30000, maxBuffer: 8 * 1024 * 1024 })
106
+ const infoPath = join(tmpApp, 'Contents', 'Info.plist')
107
+ const info = await plistJson(infoPath)
108
+ info.CFBundleIdentifier = OPENER_ID
109
+ info.CFBundleName = OPENER_NAME
110
+ info.CFBundleDisplayName = OPENER_NAME
111
+ info.CFBundleShortVersionString = PLUGIN_VERSION
112
+ info.CFBundleVersion = PLUGIN_VERSION
113
+ info.LSUIElement = true
114
+ info.NSHumanReadableCopyright = '古法编程 · AI 辅助(dsh-gufa-code)'
115
+ info.CFBundleDocumentTypes = [{
116
+ CFBundleTypeName: '古法编程文档',
117
+ CFBundleTypeRole: 'Editor',
118
+ LSHandlerRank: 'Alternate',
119
+ CFBundleTypeExtensions: OPEN_WITH_EXTENSIONS,
120
+ }]
121
+ await writePlist(infoPath, info)
122
+ try {
123
+ await run('codesign', ['--force', '--deep', '-s', '-', tmpApp], { timeout: 30000 })
124
+ } catch {
125
+ /* ad-hoc 签名失败不阻塞 */
126
+ }
127
+ await mkdir(dirname(OPENER_APP), { recursive: true })
128
+ await rm(OPENER_APP, { recursive: true, force: true })
129
+ await cp(tmpApp, OPENER_APP, { recursive: true })
130
+ } finally {
131
+ await rm(tmpScript, { force: true }).catch(() => {})
132
+ await rm(tmpApp, { recursive: true, force: true }).catch(() => {})
133
+ }
134
+ }
135
+
136
+ async function lsregister(path, unregister = false) {
137
+ const candidates = [
138
+ '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister',
139
+ '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister',
140
+ ]
141
+ let binary = ''
142
+ for (const candidate of candidates) {
143
+ if (await exists(candidate)) {
144
+ binary = candidate
145
+ break
146
+ }
147
+ }
148
+ if (binary === '') return false
149
+ await run(binary, unregister ? ['-u', path] : ['-f', path], { timeout: 20000, maxBuffer: 8 * 1024 * 1024 }).catch(() => undefined)
150
+ return true
151
+ }
152
+
153
+ /** 确保 macOS 打开器已安装/更新(幂等)。 */
154
+ async function ensureMacOpener() {
155
+ if (process.platform !== 'darwin') return { supported: false, installed: false, reason: '目前仅支持 macOS' }
156
+ if (installPromise !== null) return installPromise
157
+ installPromise = (async () => {
158
+ let installed = false
159
+ let currentVersion = ''
160
+ if (await exists(join(OPENER_APP, 'Contents', 'Info.plist'))) {
161
+ installed = true
162
+ try {
163
+ currentVersion = String((await plistJson(join(OPENER_APP, 'Contents', 'Info.plist'))).CFBundleVersion ?? '')
164
+ } catch {
165
+ currentVersion = ''
166
+ }
167
+ }
168
+ if (installed !== true || currentVersion !== PLUGIN_VERSION) {
169
+ await buildOpenerApp()
170
+ installed = true
171
+ }
172
+ await lsregister(OPENER_APP)
173
+ return { supported: true, installed: true, appPath: OPENER_APP, version: PLUGIN_VERSION, extensions: OPEN_WITH_EXTENSIONS.length }
174
+ })().finally(() => {
175
+ installPromise = null
176
+ })
177
+ return installPromise
178
+ }
179
+
180
+ /** 读取 pending 打开请求;不删除,等客户端处理成功后 open.ack 再删(避免启动竞态丢请求)。 */
181
+ async function readPending() {
182
+ if (!(await exists(PENDING_FILE))) return { token: '', entries: [] }
183
+ const info = await stat(PENDING_FILE).catch(() => null)
184
+ if (info === null) return { token: '', entries: [] }
185
+ /* 超过 2 分钟的旧请求直接过期,避免反复打开很久以前误触的文件 */
186
+ if (Date.now() - info.mtimeMs > 120000) {
187
+ await rm(PENDING_FILE, { force: true }).catch(() => {})
188
+ return { token: '', entries: [] }
189
+ }
190
+ const token = `${Math.round(info.mtimeMs)}:${info.size}`
191
+ let text = ''
192
+ try {
193
+ text = await readFile(PENDING_FILE, 'utf8')
194
+ } catch {
195
+ text = ''
196
+ }
197
+ const paths = text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== '' && isAbsolute(line))
198
+ const entries = []
199
+ for (const path of paths.slice(0, 20)) {
200
+ /* 打开器拿到的路径可能含 symlink/大小写差异;项目根是 realpath,
201
+ 这里统一 canonical 化,客户端才能算出正确的相对路径。 */
202
+ const canonical = await realpath(path).catch(() => path)
203
+ const detail = await stat(canonical).catch(() => null)
204
+ if (detail === null) continue
205
+ entries.push({ path: canonical, kind: detail.isDirectory() ? 'dir' : 'file' })
206
+ }
207
+ return { token, entries }
208
+ }
209
+
210
+ /** 客户端处理成功后确认该请求,Host 才删除 pending 文件。 */
211
+ async function ackPending(token) {
212
+ const info = await stat(PENDING_FILE).catch(() => null)
213
+ if (info === null) return { ok: false, reason: 'missing' }
214
+ const current = `${Math.round(info.mtimeMs)}:${info.size}`
215
+ if (typeof token === 'string' && token !== '' && token !== current) return { ok: false, reason: 'stale' }
216
+ await rm(PENDING_FILE, { force: true }).catch(() => {})
217
+ return { ok: true }
218
+ }
219
+
220
+ export function register(router) {
221
+ router.method('open.pending', async () => {
222
+ if (process.platform !== 'darwin') return { supported: false, token: '', entries: [] }
223
+ const pending = await readPending()
224
+ if (pending.entries.length > 0) {
225
+ try { debugLog(`open-pending entries=${pending.entries.length} token=${pending.token} paths=${pending.entries.map((entry) => entry.path).join('|')}`) } catch { /* ignore */ }
226
+ }
227
+ return { supported: true, ...pending }
228
+ })
229
+ router.method('open.ack', async (body) => {
230
+ if (process.platform !== 'darwin') return { ok: false }
231
+ const result = await ackPending(typeof body?.token === 'string' ? body.token : '')
232
+ try { debugLog(`open-ack token=${String(body?.token ?? '')} ok=${result.ok === true} reason=${result.reason ?? ''}`) } catch { /* ignore */ }
233
+ return result
234
+ })
235
+ /* 事件推送:客户端连上后先发当前 pending,再 fs.watch 监听;不再由客户端轮询文件。 */
236
+ router.stream('open.watch', async (body, context = {}) => {
237
+ const send = typeof context.send === 'function' ? context.send : () => {}
238
+ const signal = context.signal
239
+ if (process.platform !== 'darwin') {
240
+ try { send({ type: 'unsupported' }) } catch { /* ignore */ }
241
+ return
242
+ }
243
+ await mkdir(PENDING_DIR, { recursive: true }).catch(() => {})
244
+ let stopped = false
245
+ let watcher = null
246
+ let debounce = null
247
+ let finish = null
248
+ const emit = async () => {
249
+ if (stopped) return
250
+ const pending = await readPending().catch(() => ({ token: '', entries: [] }))
251
+ if (stopped || pending.entries.length === 0) return
252
+ try {
253
+ send({ type: 'pending', token: pending.token, entries: pending.entries })
254
+ debugLog(`open-watch emit entries=${pending.entries.length} token=${pending.token} paths=${pending.entries.map((entry) => entry.path).join('|')}`)
255
+ } catch {
256
+ /* 客户端已断开 */
257
+ }
258
+ }
259
+ const stop = () => {
260
+ stopped = true
261
+ if (debounce !== null) {
262
+ clearTimeout(debounce)
263
+ debounce = null
264
+ }
265
+ if (watcher !== null) {
266
+ try { watcher.close() } catch { /* ignore */ }
267
+ watcher = null
268
+ }
269
+ if (signal !== undefined && signal !== null && typeof signal.removeEventListener === 'function') {
270
+ try { signal.removeEventListener('abort', stop) } catch { /* ignore */ }
271
+ }
272
+ if (typeof finish === 'function') finish()
273
+ }
274
+ if (signal !== undefined && signal !== null) {
275
+ if (signal.aborted === true) return
276
+ signal.addEventListener('abort', stop, { once: true })
277
+ }
278
+ await emit()
279
+ try {
280
+ watcher = watch(PENDING_DIR, { persistent: true }, (eventType, filename) => {
281
+ if (filename !== null && filename !== undefined && basename(String(filename)) !== basename(PENDING_FILE)) return
282
+ if (debounce !== null) clearTimeout(debounce)
283
+ debounce = setTimeout(() => {
284
+ debounce = null
285
+ void emit()
286
+ }, 80)
287
+ })
288
+ watcher.on?.('error', () => stop())
289
+ } catch (error) {
290
+ debugLog(`open-watch error=${String(error instanceof Error ? error.message : error)}`)
291
+ }
292
+ await new Promise((resolve) => {
293
+ finish = resolve
294
+ if (stopped) {
295
+ finish()
296
+ return
297
+ }
298
+ if (signal !== undefined && signal !== null && signal.aborted === true) stop()
299
+ })
300
+ })
301
+
302
+ router.method('open.ensure', async () => {
303
+ if (process.platform !== 'darwin') return { supported: false, installed: false, reason: '目前仅支持 macOS' }
304
+ return ensureMacOpener()
305
+ })
306
+ router.method('open.status', async () => {
307
+ if (process.platform !== 'darwin') return { supported: false, installed: false }
308
+ return {
309
+ supported: true,
310
+ installed: await exists(OPENER_APP),
311
+ appPath: OPENER_APP,
312
+ pendingPath: PENDING_FILE,
313
+ extensions: OPEN_WITH_EXTENSIONS.length,
314
+ }
315
+ })
316
+ router.method('open.uninstall', async () => {
317
+ if (process.platform !== 'darwin') return { ok: false, reason: '目前仅支持 macOS' }
318
+ await lsregister(OPENER_APP, true)
319
+ await rm(OPENER_APP, { recursive: true, force: true })
320
+ return { ok: true }
321
+ })
322
+ }
package/index.js CHANGED
@@ -13,7 +13,7 @@ import { fileURLToPath } from 'node:url'
13
13
  import { createRouter, ProjectRegistry } from './host/context.js'
14
14
 
15
15
  const HOST_DIR = join(dirname(fileURLToPath(import.meta.url)), 'host')
16
- const MODULE_FILES = ['assets.js', 'dev.js', 'project.js', 'fs.js', 'git.js', 'ssh.js', 'terminal.js', 'chat.js']
16
+ const MODULE_FILES = ['assets.js', 'dev.js', 'project.js', 'fs.js', 'git.js', 'ssh.js', 'terminal.js', 'chat.js', 'open-with.js']
17
17
 
18
18
  function existingModuleFiles() {
19
19
  return MODULE_FILES.filter((name) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.215",
3
+ "version": "1.3.234",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
package/screenshots.json CHANGED
@@ -1,3 +1,5 @@
1
1
  [
2
- "docs/screenshot-ide.jpg"
2
+ "docs/screenshot-main.jpg",
3
+ "docs/screenshot-moyu.jpg",
4
+ "docs/screenshot-git.jpg"
3
5
  ]
@@ -436,6 +436,53 @@ try {
436
436
  check('definition ignores too-short word', emptyResult.word === 'x' && emptyResult.matches.length === 0)
437
437
  await call(router, 'fs.delete', { root, path: 'nav' }).catch(() => {})
438
438
 
439
+ console.log('code.definition PHP')
440
+ const phpComposer = JSON.stringify({ autoload: { 'psr-4': { 'App\\': 'app/' } } }, null, 2)
441
+ await call(router, 'fs.create', { root, path: 'composer.json', kind: 'file' })
442
+ await call(router, 'fs.write', { root, path: 'composer.json', content: phpComposer })
443
+ await call(router, 'fs.create', { root, path: 'app', kind: 'dir' })
444
+ await call(router, 'fs.create', { root, path: 'app/Exception', kind: 'dir' })
445
+ await call(router, 'fs.create', { root, path: 'app/Exception/AppException.php', kind: 'file' })
446
+ await call(router, 'fs.write', { root, path: 'app/Exception/AppException.php', content: '<?php\nnamespace App\\Exception;\n\nclass AppException extends \\RuntimeException\n{\n}\n' })
447
+ await call(router, 'fs.create', { root, path: 'app/Helper', kind: 'dir' })
448
+ await call(router, 'fs.create', { root, path: 'app/Helper/Functions.php', kind: 'file' })
449
+ await call(router, 'fs.write', { root, path: 'app/Helper/Functions.php', content: '<?php\n\nfunction get_return()\n{\n return 1;\n}\n' })
450
+ await call(router, 'fs.create', { root, path: 'app/Logic', kind: 'dir' })
451
+ await call(router, 'fs.create', { root, path: 'app/Logic/ItemLogic.php', kind: 'file' })
452
+ await call(router, 'fs.write', { root, path: 'app/Logic/ItemLogic.php', content: '<?php\nnamespace App\\Logic;\n\nclass ItemLogic\n{\n public function getItemData()\n {\n return [];\n }\n}\n' })
453
+ await call(router, 'fs.create', { root, path: 'app/Controller', kind: 'dir' })
454
+ const phpUse = [
455
+ '<?php',
456
+ 'namespace App\\Controller;',
457
+ '',
458
+ 'use App\\Logic\\ItemLogic;',
459
+ 'use App\\Exception\\AppException;',
460
+ '',
461
+ 'class Test',
462
+ '{',
463
+ ' public function run()',
464
+ ' {',
465
+ ' throw new AppException($msg, $code);',
466
+ ' $x = get_return();',
467
+ ' $y = ItemLogic::getItemData();',
468
+ ' }',
469
+ '}',
470
+ '',
471
+ ].join('\n')
472
+ await call(router, 'fs.create', { root, path: 'app/Controller/Test.php', kind: 'file' })
473
+ await call(router, 'fs.write', { root, path: 'app/Controller/Test.php', content: phpUse })
474
+ const phpClassDef = await call(router, 'code.definition', { root, path: 'app/Controller/Test.php', line: 11, column: 22, word: 'AppException', content: phpUse })
475
+ check('PHP finds use-imported class via PSR-4', phpClassDef.matches[0]?.path === 'app/Exception/AppException.php', JSON.stringify(phpClassDef.matches.slice(0, 3)))
476
+ check('PHP throw call is not treated as definition', !phpClassDef.matches.some((item) => item.path === 'app/Controller/Test.php'), JSON.stringify(phpClassDef.matches.slice(0, 3)))
477
+ const phpFnDef = await call(router, 'code.definition', { root, path: 'app/Controller/Test.php', line: 12, column: 14, word: 'get_return', content: phpUse })
478
+ check('PHP finds global function', phpFnDef.matches[0]?.path === 'app/Helper/Functions.php', JSON.stringify(phpFnDef.matches.slice(0, 3)))
479
+ const phpStaticClassDef = await call(router, 'code.definition', { root, path: 'app/Controller/Test.php', line: 13, column: 22, word: 'ItemLogic', content: phpUse })
480
+ check('PHP static call class resolves via use', phpStaticClassDef.matches[0]?.path === 'app/Logic/ItemLogic.php', JSON.stringify(phpStaticClassDef.matches.slice(0, 3)))
481
+ const phpStaticMethodDef = await call(router, 'code.definition', { root, path: 'app/Controller/Test.php', line: 13, column: 36, word: 'getItemData', content: phpUse })
482
+ check('PHP static method resolves via qualified use', phpStaticMethodDef.matches[0]?.path === 'app/Logic/ItemLogic.php', JSON.stringify(phpStaticMethodDef.matches.slice(0, 3)))
483
+ await call(router, 'fs.delete', { root, path: 'app' }).catch(() => {})
484
+ await call(router, 'fs.delete', { root, path: 'composer.json' }).catch(() => {})
485
+
439
486
  console.log('workspaces')
440
487
  const fakeSessions = new Map([
441
488
  ['s1', { id: 's1', updatedAt: 20 }],