dsh-chrome-bridge 1.19.0 → 1.20.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.
package/devtools.js CHANGED
@@ -6,6 +6,8 @@
6
6
  * 所以看 console 前先 attach 一下就能拿到「打开页面以来」的输出。网络请求没有补发,要 reload。
7
7
  */
8
8
 
9
+ import { tt } from './i18n/index.js'
10
+
9
11
  const time = (ms) => new Date(ms).toTimeString().slice(0, 8)
10
12
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
11
13
  const LEVELS = {
@@ -31,13 +33,15 @@ export async function consoleLog(call, tabId, { level = 'all', filter, limit = 4
31
33
  }
32
34
  const total = items.length
33
35
  items = items.slice(-limit)
34
- if (!items.length) return level === 'all' && !filter ? '(控制台没有输出)' : '(没有匹配的条目)'
36
+ if (!items.length) return level === 'all' && !filter ? tt('res.devtools.consoleEmpty') : tt('res.devtools.consoleNoMatch')
35
37
  const lines = items.map((c) => {
36
- const tag = c.kind === 'exception' ? '[未捕获] ' : c.kind && c.kind !== 'console' ? `[${c.kind}] ` : ''
38
+ const tag = c.kind === 'exception' ? tt('res.devtools.uncaught') : c.kind && c.kind !== 'console' ? `[${c.kind}] ` : ''
37
39
  const where = c.where ? ` (${shortWhere(c.where)})` : ''
38
40
  return `${time(c.at)} ${String(c.level).padEnd(7)} ${tag}${c.text}${where}`
39
41
  })
40
- const head = total > items.length ? `最近 ${items.length} 条(共 ${total} 条)` : `${items.length} 条`
42
+ const head = total > items.length
43
+ ? tt('res.devtools.consoleHead', { shown: items.length, total })
44
+ : tt('res.devtools.consoleCount', { n: items.length })
41
45
  return `${head}\n${lines.join('\n')}`
42
46
  }
43
47
 
@@ -51,7 +55,7 @@ export async function networkLog(call, tabId, { filter, reload = false, limit =
51
55
  const total = items.length
52
56
  items = items.slice(-limit)
53
57
  if (!items.length) {
54
- return filter ? '(没有匹配的请求)' : '(还没记到请求——只记调试器接上之后的;传 reload=true 刷新一次就能抓到页面加载的全部请求)'
58
+ return filter ? tt('res.devtools.netEmptyFiltered') : tt('res.devtools.netEmpty')
55
59
  }
56
60
  const hasId = items.some((n) => n.id)
57
61
  const lines = items.map((n) => {
@@ -60,35 +64,42 @@ export async function networkLog(call, tabId, { filter, reload = false, limit =
60
64
  const url = n.url.length > 150 ? n.url.slice(0, 149) + '…' : n.url
61
65
  return `${hasId ? `#${n.id} ` : ''}${n.method} ${status} ${String(n.type || '').toLowerCase()} ${ms} ${url}`
62
66
  })
63
- const head = (total > items.length ? `最近 ${items.length} 个请求(共 ${total} 个)` : `${items.length} 个请求`) +
64
- (hasId ? ';看返回内容:action=response,request 传 # 后面的编号' : ';扩展版本旧,看不了返回内容——重载一下扩展')
67
+ const head =
68
+ (total > items.length
69
+ ? tt('res.devtools.netHead', { shown: items.length, total })
70
+ : tt('res.devtools.netCount', { n: items.length })) +
71
+ (hasId ? tt('res.devtools.netHintResponse') : tt('res.devtools.netHintOldExt'))
65
72
  return `${head}\n${lines.join('\n')}`
66
73
  }
67
74
 
68
75
  export async function responseBody(call, tabId, requestId, limit = 6000) {
69
- if (!requestId) throw new Error('action=response 需要 request(action=network 列出的 # 编号)')
76
+ if (!requestId) throw new Error(tt('err.devtools.requestNeeded'))
70
77
  const id = String(requestId).replace(/^#/, '')
71
78
  let r
72
79
  try {
73
80
  r = await call('cdp', { tabId, method: 'Network.getResponseBody', params: { requestId: id } })
74
81
  } catch (e) {
75
82
  if (/No resource|No data found|identifier/i.test(e.message)) {
76
- throw new Error('拿不到这个请求的返回内容(太早了被清掉、请求还没完成,或调试器断开过)——action=network reload=true 重抓一次')
83
+ throw new Error(tt('err.devtools.noBody'))
77
84
  }
78
85
  throw e
79
86
  }
80
87
  const { body = '', base64Encoded } = r.result || {}
81
- if (base64Encoded) return `(二进制内容,约 ${Math.round((body.length * 3) / 4 / 1024)}KB——不是文字)`
88
+ if (base64Encoded) {
89
+ return tt('res.devtools.binary', { size: `${Math.round((body.length * 3) / 4 / 1024)}KB` })
90
+ }
82
91
  let text = body
83
92
  const t = body.trim()
84
93
  if (t.startsWith('{') || t.startsWith('[')) {
85
94
  try { text = JSON.stringify(JSON.parse(t), null, 2) } catch {}
86
95
  }
87
- return text.length > limit ? text.slice(0, limit) + `\n…(截断,全文 ${text.length} 字)` : text || '(空)'
96
+ return text.length > limit
97
+ ? text.slice(0, limit) + tt('res.devtools.truncated', { n: text.length })
98
+ : text || tt('res.devtools.empty')
88
99
  }
89
100
 
90
101
  export async function clearLogs(call, tabId) {
91
102
  await call('console', { tabId, clear: true })
92
103
  await call('network', { tabId, clear: true })
93
- return '已清空控制台和网络记录'
104
+ return tt('res.devtools.cleared')
94
105
  }
package/download.js CHANGED
@@ -14,6 +14,7 @@ import os from 'node:os'
14
14
  import path from 'node:path'
15
15
  import crypto from 'node:crypto'
16
16
  import { refElementJs } from './refs.js'
17
+ import { tt } from './i18n/index.js'
17
18
 
18
19
  const CHUNK = 2 * 1024 * 1024 // 页面里每次读回 2MB(base64 后约 2.7MB)
19
20
  const PAGE_MAX = 300 * 1024 * 1024 // 页面里最多暂存这么大,再大走插件直接下
@@ -70,7 +71,7 @@ export function uniquePath(dir, name) {
70
71
  const p = path.join(dir, i ? `${base} (${i})${ext}` : name)
71
72
  if (!fs.existsSync(p)) return p
72
73
  }
73
- throw new Error(`${dir} 里同名文件太多了:${name}`)
74
+ throw new Error(tt('err.dlTooManyNames', { dir, name }))
74
75
  }
75
76
 
76
77
  export function humanSize(n) {
@@ -128,14 +129,14 @@ const DROP_JS = (id) => `(() => { if (window.__dshDl) delete window.__dshDl[${JS
128
129
  async function viaPage(call, tabId, url, file) {
129
130
  const id = crypto.randomUUID()
130
131
  const r = (await call('eval', { tabId, expression: FETCH_JS(id, url), awaitPromise: true, userGesture: false }, TIMEOUT_MS)).value || {}
131
- if (r.status) throw new Error(`下载失败:服务器回 HTTP ${r.status}`)
132
+ if (r.status) throw new Error(tt('err.dlHttp', { status: r.status }))
132
133
  if (r.failed || r.tooBig) return null
133
134
  try {
134
135
  const fd = fs.openSync(file, 'w')
135
136
  try {
136
137
  for (let off = 0; off < r.size; off += CHUNK) {
137
138
  const b64 = (await call('eval', { tabId, expression: CHUNK_JS(id, off), userGesture: false })).value
138
- if (typeof b64 !== 'string') throw new Error('页面跳走了,下载中断')
139
+ if (typeof b64 !== 'string') throw new Error(tt('err.dlPageGone'))
139
140
  fs.writeSync(fd, Buffer.from(b64, 'base64'))
140
141
  }
141
142
  } finally {
@@ -176,7 +177,7 @@ async function viaNode(call, tabId, target, file, fetchImpl = globalThis.fetch)
176
177
  url = new URL(res.headers.get('location'), url).href
177
178
  continue
178
179
  }
179
- if (!res.ok || !res.body) throw new Error(`下载失败:服务器回 HTTP ${res.status}`)
180
+ if (!res.ok || !res.body) throw new Error(tt('err.dlHttp', { status: res.status }))
180
181
  const out = fs.createWriteStream(file)
181
182
  let size = 0
182
183
  try {
@@ -189,7 +190,7 @@ async function viaNode(call, tabId, target, file, fetchImpl = globalThis.fetch)
189
190
  }
190
191
  return { size, type: res.headers.get('content-type') || '', disposition: res.headers.get('content-disposition') || '', finalUrl: url }
191
192
  }
192
- throw new Error('下载失败:重定向太多次')
193
+ throw new Error(tt('err.dlRedirects'))
193
194
  } finally {
194
195
  clearTimeout(timer)
195
196
  }
@@ -200,14 +201,20 @@ async function viaNode(call, tabId, target, file, fetchImpl = globalThis.fetch)
200
201
  * @param opts.dir 存到哪个文件夹(调用方已经定好)
201
202
  */
202
203
  export async function download(call, tabId, { url, ref, selector, filename, dir }, deps = {}) {
203
- if ((ref === undefined || ref === null) && !selector && !url) throw new Error('要给出 url、ref 或 selector 之一')
204
+ if ((ref === undefined || ref === null) && !selector && !url) throw new Error(tt('err.dlNeedsTarget'))
204
205
  const target = (await call('eval', { tabId, expression: TARGET_JS({ ref, selector, url }), userGesture: false })).value
205
- if (!target) throw new Error('页面没回应(可能刚跳转,重试一次)')
206
- if (target.error === 'gone') throw new Error(ref !== undefined && ref !== null ? `编号 ${ref} 已失效——重新 browser_read what=snapshot` : `没找到元素: ${selector}`)
207
- if (target.error === 'nohref') throw new Error(`这个 ${target.tag} 元素没有链接地址(href / src)。是按钮的话,先 browser_click 它,看会不会打开下载链接`)
208
- if (target.error === 'badurl') throw new Error(`网址不对:${target.raw}`)
206
+ if (!target) throw new Error(tt('err.dlNoAnswer'))
207
+ if (target.error === 'gone') {
208
+ throw new Error(
209
+ ref !== undefined && ref !== null
210
+ ? tt('err.dlRefGone', { ref })
211
+ : tt('err.noElement', { sel: selector }),
212
+ )
213
+ }
214
+ if (target.error === 'nohref') throw new Error(tt('err.dlNoHref', { tag: target.tag }))
215
+ if (target.error === 'badurl') throw new Error(tt('err.dlBadUrl', { raw: target.raw }))
209
216
  const proto = new URL(target.url).protocol
210
- if (!['http:', 'https:', 'blob:', 'data:'].includes(proto)) throw new Error(`不支持这种网址:${proto}`)
217
+ if (!['http:', 'https:', 'blob:', 'data:'].includes(proto)) throw new Error(tt('err.dlBadProto', { proto }))
211
218
 
212
219
  fs.mkdirSync(dir, { recursive: true })
213
220
  const part = path.join(dir, `.dsh-download-${crypto.randomUUID()}.part`)
@@ -215,7 +222,7 @@ export async function download(call, tabId, { url, ref, selector, filename, dir
215
222
  let via = 'page'
216
223
  let meta = await viaPage(call, tabId, target.url, part)
217
224
  if (!meta) {
218
- if (proto === 'blob:' || proto === 'data:') throw new Error('页面里读不出这个文件(blob 链接可能已经失效:重新点一次生成它的按钮再试)')
225
+ if (proto === 'blob:' || proto === 'data:') throw new Error(tt('err.dlBlobDead'))
219
226
  via = 'direct'
220
227
  meta = await viaNode(call, tabId, target, part, deps.fetch)
221
228
  }
package/drag.js CHANGED
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import { refElementJs } from './refs.js'
15
+ import { tt } from './i18n/index.js'
15
16
 
16
17
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
17
18
 
@@ -47,7 +48,9 @@ const elementJs = (end) =>
47
48
 
48
49
  const isElementEnd = (end) => hasRef(end) || !!end.selector || !!end.text
49
50
  const describe = (end) =>
50
- hasRef(end) ? `[${end.ref}]` : end.selector || (end.text ? `「${end.text}」` : `(${end.x}, ${end.y})`)
51
+ hasRef(end)
52
+ ? `[${end.ref}]`
53
+ : end.selector || (end.text ? tt('res.drag.quotedText', { text: end.text }) : `(${end.x}, ${end.y})`)
51
54
 
52
55
  /** 一次 eval 算出两端的视口坐标,顺带判断是不是原生拖放。 */
53
56
  const PLAN_JS = (from, to) => `(async () => {
@@ -96,30 +99,40 @@ const NATIVE_JS = (from, to, a, b) => `(() => {
96
99
  */
97
100
  export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
98
101
  const plan = (await call('eval', { tabId, expression: PLAN_JS(from, to), userGesture: false })).value
99
- if (!plan) throw new Error('页面没回话(可能刚跳转,重试一次)')
102
+ if (!plan) throw new Error(tt('err.dragNoAnswer'))
100
103
  if (plan.missing) {
101
104
  const end = plan.missing === 'from' ? from : to
102
- throw new Error(`没找到${plan.missing === 'from' ? '起点' : '终点'} ${describe(end)}` +
103
- (hasRef(end) ? '(编号可能已失效,重新 snapshot)' : ''))
105
+ throw new Error(
106
+ tt('err.dragNotFound', {
107
+ end: plan.missing === 'from' ? tt('which.start') : tt('which.end'),
108
+ desc: describe(end),
109
+ }) + (hasRef(end) ? tt('err.dragRefStale') : ''),
110
+ )
111
+ }
112
+ if (plan.same) {
113
+ throw new Error(tt('err.dragSame', { from: describe(from), to: describe(to) }))
104
114
  }
105
- if (plan.same) throw new Error(`起点 ${describe(from)} 和终点 ${describe(to)} 找到的是同一个元素——换个更具体的写法(ref 或 selector)`)
106
115
  const { a, b } = plan
107
- if (!plan.bIn) throw new Error(`终点 ${describe(to)} 不在当前屏幕里——先滚动让起点和终点都露出来`)
116
+ if (!plan.bIn) throw new Error(tt('err.dragOffscreen', { to: describe(to) }))
108
117
 
109
118
  const cur = async (fn) => {
110
119
  if (!cursor) return 0
111
120
  try { return Number(await fn(cursor)) || 0 } catch { return 0 }
112
121
  }
113
122
  // 光标先滑到起点亮名牌,到位了再按下
114
- if (cursor) await sleep(Math.min(700, await cur((c) => c.move(a.x, a.y, { label: `拖拽 ${describe(from)} → ${describe(to)}` }))) + 60)
123
+ if (cursor) await sleep(Math.min(700, await cur((c) => c.move(a.x, a.y, { label: tt('res.drag.label', { from: describe(from), to: describe(to) }) }))) + 60)
115
124
 
116
125
  if (plan.native) {
117
126
  await cur((c) => c.down())
118
127
  await sleep(await cur((c) => c.move(b.x, b.y, { duration: 420, straight: true })))
119
128
  const r = (await call('eval', { tabId, expression: NATIVE_JS(from, to, a, b) })).value
120
129
  await cur((c) => c.up())
121
- if (r && r.error) throw new Error('终点那里没有元素')
122
- return `已拖拽 ${describe(from)} → ${describe(to)}(HTML5 拖放${r && r.accepted ? ',目标接受了' : ',但目标没表示接受——看看结果对不对'})`
130
+ if (r && r.error) throw new Error(tt('err.dragNoTarget'))
131
+ return tt('res.drag.doneHtml5', {
132
+ from: describe(from),
133
+ to: describe(to),
134
+ verdict: r && r.accepted ? tt('res.drag.accepted') : tt('res.drag.notAccepted'),
135
+ })
123
136
  }
124
137
 
125
138
  const mouse = (type, p, extra) => call('cdp', {
@@ -139,5 +152,12 @@ export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
139
152
  }
140
153
  await mouse('mouseReleased', b, { button: 'left', buttons: 0, clickCount: 1 })
141
154
  await cur((c) => c.up())
142
- return `已拖拽 ${describe(from)} → ${describe(to)}:(${Math.round(a.x)}, ${Math.round(a.y)}) → (${Math.round(b.x)}, ${Math.round(b.y)})`
155
+ return tt('res.drag.doneCoords', {
156
+ from: describe(from),
157
+ to: describe(to),
158
+ x1: Math.round(a.x),
159
+ y1: Math.round(a.y),
160
+ x2: Math.round(b.x),
161
+ y2: Math.round(b.y),
162
+ })
143
163
  }
package/i18n/en.js CHANGED
@@ -152,8 +152,8 @@ export default {
152
152
  'err.waitNeedsOne': 'Give exactly one of selector / text / url',
153
153
  'err.dragNeedsEnd': '%which needs one of %ref, %sel, %txt or %xy',
154
154
  'err.noWorkdir': 'Cannot determine the session working directory; drop to=workdir to save into the "Downloads" folder',
155
- 'which.start': 'The start',
156
- 'which.end': 'The end',
155
+ 'which.start': 'start point',
156
+ 'which.end': 'end point',
157
157
 
158
158
  // ── setup hints appended to errors ─────────────────────────────────────
159
159
  'hint.extOpened': 'I opened chrome://extensions for you (background tab)%store',
@@ -163,4 +163,148 @@ export default {
163
163
  'hint.copiedWin': 'paste it into the file picker\'s address bar and press Enter',
164
164
  'hint.notes': '\n(%notes)',
165
165
  'hint.notesSep': '; ',
166
+ 'err.navFirstPage': 'This is already the first page; cannot go back',
167
+ 'err.navLastPage': 'This is already the last page; cannot go forward',
168
+ 'res.wait.whatText': 'text "%text"',
169
+ 'res.wait.whatUrl': 'a URL containing "%url"',
170
+ 'res.wait.found': 'Found',
171
+ 'res.wait.goneState': 'No longer present:',
172
+ 'res.wait.ok': '%state %what after %ms',
173
+ 'res.wait.still': 'is still there',
174
+ 'res.wait.notYet': 'has not appeared yet',
175
+ 'err.waitTimeout': 'Waited %ms: %what %state',
176
+ 'err.panelTooLarge': 'Request is too large',
177
+ 'err.panelNotJson': 'Not JSON',
178
+ 'res.devtools.consoleEmpty': '(the console has no output)',
179
+ 'res.devtools.consoleNoMatch': '(no matching entries)',
180
+ 'res.devtools.uncaught': '[uncaught] ',
181
+ 'res.devtools.consoleHead': 'last %shown of %total entries',
182
+ 'res.devtools.consoleCount': '%n entries',
183
+ 'res.devtools.netEmptyFiltered': '(no matching requests)',
184
+ 'res.devtools.netEmpty': '(no requests recorded yet — only those made after the debugger attached; pass reload=true to refresh once and capture everything the page loads)',
185
+ 'res.devtools.netHead': 'last %shown of %total requests',
186
+ 'res.devtools.netCount': '%n requests',
187
+ 'res.devtools.netHintResponse': '; to see a response body: action=response with the # number from the list as request',
188
+ 'res.devtools.netHintOldExt': '; the extension is outdated and response bodies are unavailable — reload the extension',
189
+ 'err.devtools.requestNeeded': 'action=response needs request (the # number listed by action=network)',
190
+ 'err.devtools.noBody': 'cannot fetch this request\'s response body (evicted too early, the request is not finished, or the debugger was detached) — rerun action=network reload=true',
191
+ 'res.devtools.binary': '(binary content, about %size — not text)',
192
+ 'res.devtools.truncated': '\n…(truncated, %n characters in total)',
193
+ 'res.devtools.empty': '(empty)',
194
+ 'res.devtools.cleared': 'Console and network records cleared',
195
+ 'err.dlTooManyNames': 'too many files with the same name in %dir: %name',
196
+ 'err.dlHttp': 'download failed: the server returned HTTP %status',
197
+ 'err.dlPageGone': 'the page navigated away; the download was aborted',
198
+ 'err.dlRedirects': 'download failed: too many redirects',
199
+ 'err.dlNeedsTarget': 'give one of url, ref or selector',
200
+ 'err.dlNoAnswer': 'the page did not answer (it may have just navigated; try again)',
201
+ 'err.dlRefGone': 'ref %ref is no longer valid — run browser_read what=snapshot again',
202
+ 'err.noElement': 'element not found: %sel',
203
+ 'err.dlNoHref': 'this %tag element has no link (href / src). If it is a button, browser_click it first and see whether that opens a download link',
204
+ 'err.dlBadUrl': 'bad URL: %raw',
205
+ 'err.dlBadProto': 'unsupported URL scheme: %proto',
206
+ 'err.dlBlobDead': 'cannot read this file from the page (the blob link may have expired: click the button that generates it again and retry)',
207
+ 'res.drag.label': 'dragging %from → %to',
208
+ 'res.drag.quotedText': '"%text"',
209
+ 'err.dragNoAnswer': 'the page did not answer (it may have just navigated; try again)',
210
+ 'err.dragNotFound': 'could not find the %end: %desc',
211
+ 'err.dragRefStale': ' (the ref may be stale; take a fresh snapshot)',
212
+ 'err.dragSame': 'start %from and end %to resolve to the same element — be more specific (ref or selector)',
213
+ 'err.dragOffscreen': 'end %to is off screen — scroll so that both start and end are visible',
214
+ 'err.dragNoTarget': 'there is no element at the end point',
215
+ 'res.drag.doneHtml5': 'dragged %from → %to (HTML5 drag and drop%verdict)',
216
+ 'res.drag.accepted': '; the target accepted it',
217
+ 'res.drag.notAccepted': ', but the target did not report acceptance — check whether the result is right',
218
+ 'res.drag.doneCoords': 'dragged %from → %to: (%x1, %y1) → (%x2, %y2)',
219
+ 'err.refGone': 'ref %ref is no longer valid (the page changed or navigated) — run browser_read what=snapshot to get new refs',
220
+ 'err.snapshotFailed': 'the page did not return a snapshot (it may have just navigated; try again)',
221
+ 'res.snap.head': '%count interactive elements ([N] is the ref: pass ref=N to browser_click / browser_input)',
222
+ 'res.snap.nothing': '(no interactive elements found)',
223
+ 'res.snap.more': '\n…%more more elements are not listed — pass selector to look at part of the page',
224
+ 'res.snap.truncated': '\n…(truncated, %n characters in total — pass selector to narrow it down, or raise limit)',
225
+ 'err.refNotInt': 'the ref must be a positive integer; got %ref',
226
+ 'err.refFocus': 'could not focus ref %n (the element may not be focusable)',
227
+ 'err.selectNotSelect': 'not a <select> element',
228
+ 'err.selectNoOption': 'no such option',
229
+ 'err.selectFailed': 'selection failed: %why%options',
230
+ 'err.selectOptions': ' (allowed values: %options)',
231
+ 'res.hint.quoted': '"%text"',
232
+ 'res.hint.typing': 'typing %n chars',
233
+ 'res.hint.key': 'key %key',
234
+ 'res.hint.element': 'element %el',
235
+ 'res.hint.waitGone': 'wait for gone ',
236
+ 'res.hint.url': 'URL %url',
237
+ 'res.tabs.agentWindow': ' (DSH work window)',
238
+ 'res.tabs.empty': '(no tabs)',
239
+ 'res.tabs.footnote': '(* = the page the user is looking at)',
240
+ 'res.tabs.noMatch': '(no matching tabs)',
241
+ 'res.tabs.agentHint': ' (in a separate DSH work window, opened in the background without disturbing the page the user is looking at)',
242
+ 'res.tabs.background': ' (background tab)',
243
+ 'res.tabs.opened': 'opened tab %id%where: %url',
244
+ 'res.tabs.closed': 'closed tab %id',
245
+ 'res.tabs.activated': 'switched to tab %id',
246
+ 'res.read.iframeCross': '\n\n[iframe] %src (cross-site frame; its text cannot be read — use browser_screenshot)',
247
+ 'res.read.noText': '(the page has no visible text)',
248
+ 'res.read.noAttr': '(no such attribute)',
249
+ 'res.read.viewport': ' | viewport %w×%h, scrolled %scrollYpx',
250
+ 'res.read.dialog': '\n⚠️ a %type dialog is in the way: "%message" — call browser_dialog first to let it through',
251
+ 'res.click.atRef': 'clicked [%ref] %tag "%text" @ (%x, %y)',
252
+ 'res.click.atRefCount': 'clicked [%ref] %tag "%text" @ (%x, %y) ×%count',
253
+ 'res.click.byTag': 'clicked %tag "%text" @ (%x, %y)',
254
+ 'res.click.atCoords': 'clicked (%x, %y)',
255
+ 'res.input.typedAfterClick': 'typed %n characters (clicked %target first)',
256
+ 'res.input.typed': 'typed %n characters',
257
+ 'res.input.typedAfterFocus': ' (focused %target first)',
258
+ 'res.input.pressedKey': 'pressed key %key',
259
+ 'res.input.selected': 'selected "%label" (%value)',
260
+ 'res.input.uploaded': 'put %n files into %target',
261
+ 'res.input.uploadedChooser': 'handed %n files to the file picker the page just opened',
262
+ 'res.input.focused': 'focused %target',
263
+ 'res.input.hovered': 'hovered @ (%x, %y)',
264
+ 'res.input.hoveredEl': ' %tag "%text"',
265
+ 'res.input.scrolled': 'scrolled %dy, scrollY=%scrollY / page height %pageHeight',
266
+ 'res.nav.late': ' (the page has not finished loading; use browser_wait to wait if needed)',
267
+ 'res.nav.subtitle': ' — %title',
268
+ 'res.nav.go': 'reached %url%title%late',
269
+ 'res.nav.history': '%verb %url%title%late',
270
+ 'res.nav.back': 'went back to',
271
+ 'res.nav.forward': 'went forward to',
272
+ 'res.nav.reload': 'reloaded',
273
+ 'res.shot.note': 'screenshot (%mode, %size) — %where',
274
+ 'res.shot.saved': '\n(attachments are unavailable; saved to %file — use read_image to view it)',
275
+ 'res.wait.selector': 'waited for %sel @ (%x, %y) "%text", took %ms',
276
+ 'res.dialog.accepted': 'dialog accepted',
277
+ 'res.dialog.dismissed': 'dialog dismissed',
278
+ 'res.dl.warnHtml': '\n⚠️ what was downloaded is a web page (text/html) — most likely a login page or a "download is about to start" interstitial, not the file itself: open it, or use a direct file link',
279
+ 'res.dl.done': 'downloaded: %file (%size%type)%warn',
280
+ 'res.dl.typePart': ', %type',
281
+ 'setup.noVendor': 'the plugin package has no bundled host: reinstall the plugin from the release tarball (README, Install section).',
282
+ 'setup.unsupportedPlatform': 'the browser bridge does not support %platform yet (only macOS, Windows and Linux).',
283
+ 'setup.regHead': 'the host or the native messaging registration was not written (usually a permissions problem):',
284
+ 'setup.regHostDir': 'host directory %dir%mark',
285
+ 'setup.regNm': 'registration%kind %file%mark',
286
+ 'setup.nmKindWin': ' (registry + file)',
287
+ 'setup.nmKindFile': ' file',
288
+ 'setup.regTail': 'restart DSH once and it will retry; if that does not help, open an issue on GitHub.',
289
+ 'setup.launchFailed': 'Chrome failed to launch the host: %err\nAfter restarting DSH, quit Chrome completely and open it again.',
290
+ 'setup.storeHead': 'the extension is installed from the Chrome Web Store (DSH Bridge %version), but the host is not connected:',
291
+ 'setup.storeStep1': '1. make sure Chrome is running',
292
+ 'setup.storeStep2': '2. DSH Bridge is enabled on chrome://extensions',
293
+ 'setup.storeStep3': '3. if that does not help, quit Chrome completely and open it again',
294
+ 'setup.storeTail': 'no need to "Load unpacked" — the host and the native registration are already installed automatically.',
295
+ 'setup.manualHead': 'one last step for the browser bridge (once), pick one of two ways:',
296
+ 'setup.manualStore': '· simplest: install DSH Bridge from the Chrome Web Store (no developer mode):',
297
+ 'setup.storeUrl': ' %url',
298
+ 'setup.manualUnpacked': '· or load the unpacked extension:',
299
+ 'setup.manualStep1': ' 1. open chrome://extensions in Chrome',
300
+ 'setup.manualStep2': ' 2. turn on "Developer mode" in the top right corner',
301
+ 'setup.manualStep3': ' 3. click "Load unpacked", %paste, and pick this folder:',
302
+ 'setup.manualDir': ' %dir',
303
+ 'setup.manualTail': 'when it is installed, come back and retry; the host and the native registration are already installed automatically, no script to run.',
304
+ 'setup.pasteDarwin': 'press ⌘⇧G in the file picker, paste and hit Enter',
305
+ 'setup.pasteWin': 'paste the path into the address bar at the top of the file picker and hit Enter',
306
+ 'setup.pasteLinux': 'press Ctrl+L in the file picker, paste and hit Enter',
307
+ 'res.read.truncated': '\n…(truncated, %n characters in total)',
308
+ 'err.setupProcList': 'the process listing did not finish',
309
+ 'err.chromeNotFound': 'Chrome not found',
166
310
  }
package/i18n/index.js CHANGED
@@ -62,3 +62,20 @@ export function createT(locale, dicts = DICTS) {
62
62
  return text
63
63
  }
64
64
  }
65
+
66
+ /**
67
+ * 当前在用的 t():插件启动时由 apply() 按 config.locale 设一次;
68
+ * 其他模块(refs / nav / download / drag / devtools / panel / setup)用 tt() 取文案。
69
+ */
70
+ let active = createT(DEFAULT_LOCALE)
71
+
72
+ /** 切到指定语言,并把新的 t() 返回出去(apply() 自己还要用)。 */
73
+ export function setLocale(locale) {
74
+ active = createT(locale)
75
+ return active
76
+ }
77
+
78
+ /** 按当前语言取一条文案(模块内部用)。 */
79
+ export function tt(key, vars) {
80
+ return active(key, vars)
81
+ }
package/i18n/ru.js CHANGED
@@ -153,8 +153,8 @@ export default {
153
153
  'err.waitNeedsOne': 'Укажите ровно одно из: selector / text / url',
154
154
  'err.dragNeedsEnd': '%which: нужно одно из %ref, %sel, %txt или %xy',
155
155
  'err.noWorkdir': 'Не удалось определить рабочую папку сеанса; уберите to=workdir, чтобы сохранить в папку «Загрузки»',
156
- 'which.start': 'Начало',
157
- 'which.end': 'Конец',
156
+ 'which.start': 'начало',
157
+ 'which.end': 'конец',
158
158
 
159
159
  // ── подсказки, которые добавляются к ошибкам ───────────────────────────
160
160
  'hint.extOpened': 'Я открыл для вас chrome://extensions (в фоновой вкладке)%store',
@@ -164,4 +164,148 @@ export default {
164
164
  'hint.copiedWin': 'вставьте его в адресную строку окна выбора файлов и нажмите Enter',
165
165
  'hint.notes': '\n(%notes)',
166
166
  'hint.notesSep': '; ',
167
+ 'err.navFirstPage': 'Это уже первая страница, назад некуда',
168
+ 'err.navLastPage': 'Это уже последняя страница, вперёд некуда',
169
+ 'res.wait.whatText': 'текст «%text»',
170
+ 'res.wait.whatUrl': 'адрес, содержащий «%url»',
171
+ 'res.wait.found': 'Готово:',
172
+ 'res.wait.goneState': 'Больше нет:',
173
+ 'res.wait.ok': '%state %what — за %ms',
174
+ 'res.wait.still': 'ещё на месте',
175
+ 'res.wait.notYet': 'ещё не появился',
176
+ 'err.waitTimeout': 'Ждали %ms: %what %state',
177
+ 'err.panelTooLarge': 'Слишком большой запрос',
178
+ 'err.panelNotJson': 'Это не JSON',
179
+ 'res.devtools.consoleEmpty': '(в консоли ничего нет)',
180
+ 'res.devtools.consoleNoMatch': '(ничего не найдено)',
181
+ 'res.devtools.uncaught': '[не перехвачено] ',
182
+ 'res.devtools.consoleHead': 'последние %shown из %total записей',
183
+ 'res.devtools.consoleCount': '%n записей',
184
+ 'res.devtools.netEmptyFiltered': '(подходящих запросов нет)',
185
+ 'res.devtools.netEmpty': '(запросов пока нет — записываются только те, что пошли после подключения отладчика; передайте reload=true, чтобы один раз перезагрузить страницу и поймать все её запросы)',
186
+ 'res.devtools.netHead': 'последние %shown из %total запросов',
187
+ 'res.devtools.netCount': '%n запросов',
188
+ 'res.devtools.netHintResponse': '; чтобы увидеть тело ответа: action=response, в request передайте номер после #',
189
+ 'res.devtools.netHintOldExt': '; расширение устарело, тела ответов недоступны — перезагрузите расширение',
190
+ 'err.devtools.requestNeeded': 'action=response требует request (номер после # из списка action=network)',
191
+ 'err.devtools.noBody': 'не удалось получить тело ответа (слишком рано вытеснено, запрос ещё не завершён или отладчик отключался) — повторите action=network reload=true',
192
+ 'res.devtools.binary': '(двоичные данные, около %size — не текст)',
193
+ 'res.devtools.truncated': '\n…(обрезано, всего символов: %n)',
194
+ 'res.devtools.empty': '(пусто)',
195
+ 'res.devtools.cleared': 'Записи консоли и сети очищены',
196
+ 'err.dlTooManyNames': 'в %dir слишком много файлов с таким именем: %name',
197
+ 'err.dlHttp': 'не удалось скачать: сервер ответил HTTP %status',
198
+ 'err.dlPageGone': 'страница перешла, загрузка прервана',
199
+ 'err.dlRedirects': 'не удалось скачать: слишком много перенаправлений',
200
+ 'err.dlNeedsTarget': 'укажите одно из: url, ref, selector',
201
+ 'err.dlNoAnswer': 'страница не ответила (возможно, только что перешла — повторите)',
202
+ 'err.dlRefGone': 'номер %ref больше не действует — заново вызовите browser_read what=snapshot',
203
+ 'err.noElement': 'элемент не найден: %sel',
204
+ 'err.dlNoHref': 'у элемента %tag нет ссылки (href / src). Если это кнопка, сначала нажмите её через browser_click — возможно, она откроет ссылку на скачивание',
205
+ 'err.dlBadUrl': 'некорректный адрес: %raw',
206
+ 'err.dlBadProto': 'такая схема адреса не поддерживается: %proto',
207
+ 'err.dlBlobDead': 'не удалось прочитать файл со страницы (возможно, ссылка blob устарела: нажмите кнопку, которая её создаёт, и повторите)',
208
+ 'res.drag.label': 'перетаскивание %from → %to',
209
+ 'res.drag.quotedText': '«%text»',
210
+ 'err.dragNoAnswer': 'страница не ответила (возможно, только что перешла — повторите)',
211
+ 'err.dragNotFound': 'не найдено: %end %desc',
212
+ 'err.dragRefStale': ' (возможно, номер устарел — снимите снимок заново)',
213
+ 'err.dragSame': 'начало %from и конец %to — это один и тот же элемент; уточните (ref или selector)',
214
+ 'err.dragOffscreen': 'конец %to вне экрана — прокрутите так, чтобы были видны и начало, и конец',
215
+ 'err.dragNoTarget': 'в точке назначения нет элемента',
216
+ 'res.drag.doneHtml5': 'перетащили %from → %to (HTML5 drag and drop%verdict)',
217
+ 'res.drag.accepted': '; цель приняла его',
218
+ 'res.drag.notAccepted': ', но цель не сообщила о приёме — проверьте, получилось ли',
219
+ 'res.drag.doneCoords': 'перетащили %from → %to: (%x1, %y1) → (%x2, %y2)',
220
+ 'err.refGone': 'номер %ref больше не действует (страница изменилась или перешла) — заново вызовите browser_read what=snapshot, чтобы получить новые номера',
221
+ 'err.snapshotFailed': 'страница не вернула снимок (возможно, только что перешла — повторите)',
222
+ 'res.snap.head': 'интерактивных элементов: %count ([N] — это номер: передавайте ref=N в browser_click / browser_input)',
223
+ 'res.snap.nothing': '(интерактивных элементов не найдено)',
224
+ 'res.snap.more': '\n…ещё %more элементов не показано — передайте selector, чтобы посмотреть часть страницы',
225
+ 'res.snap.truncated': '\n…(обрезано, всего символов: %n — передайте selector, чтобы сузить область, или увеличьте limit)',
226
+ 'err.refNotInt': 'номер должен быть положительным целым; получено %ref',
227
+ 'err.refFocus': 'не удалось сфокусировать номер %n (возможно, элемент не может получать фокус)',
228
+ 'err.selectNotSelect': 'это не элемент <select>',
229
+ 'err.selectNoOption': 'такого варианта нет',
230
+ 'err.selectFailed': 'не удалось выбрать: %why%options',
231
+ 'err.selectOptions': ' (возможные значения: %options)',
232
+ 'res.hint.quoted': '«%text»',
233
+ 'res.hint.typing': 'ввод %n символов',
234
+ 'res.hint.key': 'клавиша %key',
235
+ 'res.hint.element': 'элемент %el',
236
+ 'res.hint.waitGone': 'ждём исчезновения ',
237
+ 'res.hint.url': 'адрес %url',
238
+ 'res.tabs.agentWindow': ' (рабочее окно DSH)',
239
+ 'res.tabs.empty': '(вкладок нет)',
240
+ 'res.tabs.footnote': '(* = вкладка, которую пользователь смотрит сейчас)',
241
+ 'res.tabs.noMatch': '(подходящих вкладок нет)',
242
+ 'res.tabs.agentHint': ' (в отдельном рабочем окне DSH, открыта в фоне и не мешает вкладке, которую смотрит пользователь)',
243
+ 'res.tabs.background': ' (фоновая вкладка)',
244
+ 'res.tabs.opened': 'открыта вкладка %id%where: %url',
245
+ 'res.tabs.closed': 'вкладка %id закрыта',
246
+ 'res.tabs.activated': 'переключились на вкладку %id',
247
+ 'res.read.iframeCross': '\n\n[iframe] %src (кросс-доменный фрейм: его текст не читается — смотрите через browser_screenshot)',
248
+ 'res.read.noText': '(на странице нет видимого текста)',
249
+ 'res.read.noAttr': '(такого атрибута нет)',
250
+ 'res.read.viewport': ' | окно %w×%h, прокручено %scrollYpx',
251
+ 'res.read.dialog': '\n⚠️ мешает диалог %type: «%message» — сначала вызовите browser_dialog, чтобы его закрыть',
252
+ 'res.click.atRef': 'нажали [%ref] %tag «%text» @ (%x, %y)',
253
+ 'res.click.atRefCount': 'нажали [%ref] %tag «%text» @ (%x, %y) ×%count',
254
+ 'res.click.byTag': 'нажали %tag «%text» @ (%x, %y)',
255
+ 'res.click.atCoords': 'нажали в точку (%x, %y)',
256
+ 'res.input.typedAfterClick': 'введено символов: %n (сначала нажали %target)',
257
+ 'res.input.typed': 'введено символов: %n',
258
+ 'res.input.typedAfterFocus': ' (сначала сфокусировали %target)',
259
+ 'res.input.pressedKey': 'нажата клавиша %key',
260
+ 'res.input.selected': 'выбрано «%label» (%value)',
261
+ 'res.input.uploaded': 'в %target передано файлов: %n',
262
+ 'res.input.uploadedChooser': 'передано файлов в окно выбора, которое только что открыла страница: %n',
263
+ 'res.input.focused': 'сфокусировано: %target',
264
+ 'res.input.hovered': 'наведено @ (%x, %y)',
265
+ 'res.input.hoveredEl': ' %tag «%text»',
266
+ 'res.input.scrolled': 'прокручено на %dy, scrollY=%scrollY / высота страницы %pageHeight',
267
+ 'res.nav.late': ' (страница ещё не догрузилась — при необходимости подождите через browser_wait)',
268
+ 'res.nav.subtitle': ' — %title',
269
+ 'res.nav.go': 'открыто %url%title%late',
270
+ 'res.nav.history': '%verb %url%title%late',
271
+ 'res.nav.back': 'назад к',
272
+ 'res.nav.forward': 'вперёд к',
273
+ 'res.nav.reload': 'перезагружено',
274
+ 'res.shot.note': 'снимок (%mode, %size) — %where',
275
+ 'res.shot.saved': '\n(хранилище вложений недоступно, файл сохранён в %file — посмотрите через read_image)',
276
+ 'res.wait.selector': 'дождались %sel @ (%x, %y) «%text», за %ms',
277
+ 'res.dialog.accepted': 'диалог подтверждён',
278
+ 'res.dialog.dismissed': 'диалог отменён',
279
+ 'res.dl.warnHtml': '\n⚠️ скачалась веб-страница (text/html) — скорее всего, это страница входа или промежуточная страница «загрузка вот-вот начнётся», а не сам файл: откройте её или возьмите прямую ссылку на файл',
280
+ 'res.dl.done': 'скачано: %file (%size%type)%warn',
281
+ 'res.dl.typePart': ', %type',
282
+ 'setup.noVendor': 'в пакете плагина нет встроенного хоста: переустановите плагин из release tarball (раздел Install в README).',
283
+ 'setup.unsupportedPlatform': 'мост браузера пока не поддерживает %platform (только macOS, Windows и Linux).',
284
+ 'setup.regHead': 'хост или регистрация native messaging не записались (скорее всего, проблема с правами):',
285
+ 'setup.regHostDir': 'каталог хоста %dir%mark',
286
+ 'setup.regNm': 'регистрация%kind %file%mark',
287
+ 'setup.nmKindWin': ' (реестр + файл)',
288
+ 'setup.nmKindFile': ' (файл)',
289
+ 'setup.regTail': 'перезапустите DSH — он попробует ещё раз; если не поможет, создайте issue на GitHub.',
290
+ 'setup.launchFailed': 'Chrome не смог запустить хост: %err\nПосле перезапуска DSH полностью закройте Chrome и откройте его заново.',
291
+ 'setup.storeHead': 'расширение установлено из Chrome Web Store (DSH Bridge %version), но хост не подключился:',
292
+ 'setup.storeStep1': '1. убедитесь, что Chrome запущен',
293
+ 'setup.storeStep2': '2. DSH Bridge включён на chrome://extensions',
294
+ 'setup.storeStep3': '3. если не помогло, полностью закройте Chrome и откройте заново',
295
+ 'setup.storeTail': '«Загружать распакованное» больше не нужно — хост и регистрация native уже установлены автоматически.',
296
+ 'setup.manualHead': 'мосту браузера остался последний шаг (однократно) — выберите один из двух способов:',
297
+ 'setup.manualStore': '· проще всего: установить DSH Bridge из Chrome Web Store (без режима разработчика):',
298
+ 'setup.storeUrl': ' %url',
299
+ 'setup.manualUnpacked': '· или загрузить распакованное расширение:',
300
+ 'setup.manualStep1': ' 1. откройте в Chrome chrome://extensions',
301
+ 'setup.manualStep2': ' 2. включите «Режим разработчика» в правом верхнем углу',
302
+ 'setup.manualStep3': ' 3. нажмите «Загрузить распакованное расширение», %paste, и выберите этот каталог:',
303
+ 'setup.manualDir': ' %dir',
304
+ 'setup.manualTail': 'после установки вернитесь сюда и повторите; хост и регистрация native уже установлены автоматически, никакие скрипты запускать не нужно.',
305
+ 'setup.pasteDarwin': 'в окне выбора файла нажмите ⌘⇧G, вставьте путь и нажмите Enter',
306
+ 'setup.pasteWin': 'вставьте путь в адресную строку сверху окна выбора файла и нажмите Enter',
307
+ 'setup.pasteLinux': 'в окне выбора файла нажмите Ctrl+L, вставьте путь и нажмите Enter',
308
+ 'res.read.truncated': '\n…(обрезано, всего символов: %n)',
309
+ 'err.setupProcList': 'список процессов не завершился',
310
+ 'err.chromeNotFound': 'Chrome не найден',
167
311
  }