dsh-chrome-bridge 1.16.4 → 1.17.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/README.md +3 -0
- package/drag.js +15 -4
- package/i18n/en.js +157 -0
- package/i18n/index.js +64 -0
- package/i18n/ru.js +158 -0
- package/i18n/zh.js +158 -0
- package/index.js +146 -162
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -23,4 +23,7 @@ On DSH 0.2.2 or later, open the plugin on the Plugins page and click "Update to
|
|
|
23
23
|
|
|
24
24
|
DSH 0.2.2 起,在「插件」页点开它,点「更新到 …」;更老的 DSH 先卸载,再添加一次。DSH 用 pnpm 安装插件,而 pnpm 默认不装刚发布的版本,所以新版大约发布一天后才装得到。
|
|
25
25
|
|
|
26
|
+
Tool descriptions can be English or Russian: set `config.locale: en` (or `ru`) on the bundle in the profile's `cordis.patch.yml` and restart DSH.
|
|
27
|
+
工具描述可以是英文或俄文:在 profile 的 `cordis.patch.yml` 里给这个 bundle 加 `config.locale: en`(或 `ru`),然后重启 DSH。
|
|
28
|
+
|
|
26
29
|
Full documentation / 完整说明:https://github.com/OrderG-X/dsh-chrome-bridge
|
package/drag.js
CHANGED
|
@@ -15,14 +15,23 @@ import { refElementJs } from './refs.js'
|
|
|
15
15
|
|
|
16
16
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
17
17
|
|
|
18
|
-
/**
|
|
18
|
+
/**
|
|
19
|
+
* 按可见文字找元素:看得见、包含这段文字的元素里,文字正好就是这段的优先
|
|
20
|
+
* (不然「顺序:Item A, Item B…」这种把几项连在一起的小段落会比列表项本身还小,抢走匹配),
|
|
21
|
+
* 同一档里取面积最小的那个(最贴近文字本身)。
|
|
22
|
+
*/
|
|
19
23
|
const textElementJs = (text) => `((t) => {
|
|
20
|
-
|
|
24
|
+
const norm = (s) => String(s || '').replace(/\\s+/g, ' ').trim();
|
|
25
|
+
const want = norm(t);
|
|
26
|
+
let best = null, area = Infinity, exact = false;
|
|
21
27
|
for (const el of document.body.querySelectorAll('*')) {
|
|
22
28
|
if (!(el.textContent || '').includes(t) || !(el.innerText || '').includes(t)) continue;
|
|
23
29
|
const r = el.getBoundingClientRect();
|
|
24
|
-
if (r.width < 1 || r.height < 1
|
|
25
|
-
|
|
30
|
+
if (r.width < 1 || r.height < 1) continue;
|
|
31
|
+
const ex = norm(el.innerText) === want;
|
|
32
|
+
if (exact && !ex) continue;
|
|
33
|
+
if (ex === exact && r.width * r.height >= area) continue;
|
|
34
|
+
best = el; area = r.width * r.height; exact = ex;
|
|
26
35
|
}
|
|
27
36
|
return best;
|
|
28
37
|
})(${JSON.stringify(String(text))})`
|
|
@@ -46,6 +55,7 @@ const PLAN_JS = (from, to) => `(async () => {
|
|
|
46
55
|
const dst = ${elementJs(to)};
|
|
47
56
|
if (${isElementEnd(from)} && !src) return { missing: 'from' };
|
|
48
57
|
if (${isElementEnd(to)} && !dst) return { missing: 'to' };
|
|
58
|
+
if (src && src === dst) return { same: true };
|
|
49
59
|
if (src) {
|
|
50
60
|
src.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'instant' });
|
|
51
61
|
// 后台标签页会暂停 rAF,定时器兜底
|
|
@@ -92,6 +102,7 @@ export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
|
|
|
92
102
|
throw new Error(`没找到${plan.missing === 'from' ? '起点' : '终点'} ${describe(end)}` +
|
|
93
103
|
(hasRef(end) ? '(编号可能已失效,重新 snapshot)' : ''))
|
|
94
104
|
}
|
|
105
|
+
if (plan.same) throw new Error(`起点 ${describe(from)} 和终点 ${describe(to)} 找到的是同一个元素——换个更具体的写法(ref 或 selector)`)
|
|
95
106
|
const { a, b } = plan
|
|
96
107
|
if (!plan.bIn) throw new Error(`终点 ${describe(to)} 不在当前屏幕里——先滚动让起点和终点都露出来`)
|
|
97
108
|
|
package/i18n/en.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side dictionary (English). Same keys as zh.js, which stays the reference
|
|
3
|
+
* dictionary: a key missing here falls back to Chinese, and so does a translation
|
|
4
|
+
* that drops a placeholder the Chinese text needs (see i18n/index.js).
|
|
5
|
+
*
|
|
6
|
+
* This layer is model-facing: tool descriptions, parameter docs and error messages.
|
|
7
|
+
* Keep the operational detail — the model reads these as instructions.
|
|
8
|
+
*/
|
|
9
|
+
export default {
|
|
10
|
+
// ── shared ──────────────────────────────────────────────────────────────
|
|
11
|
+
'param.tab': 'Tab id (number), or "active" for the tab the user is currently looking at. When omitted, the tab this session opened or last acted on is reused; with none, the call fails — it never falls back to the tab the user is on',
|
|
12
|
+
'param.ref': 'Element ref: the [N] numbers listed by browser_read(what=snapshot). Most reliable — when you have a ref, do not guess a selector',
|
|
13
|
+
|
|
14
|
+
// ── browser_tabs ───────────────────────────────────────────────────────
|
|
15
|
+
'tool.tabs.desc': 'List / find / open / close / switch Chrome tabs. Every other browser_* tool takes a tab argument, so call this first to get an id. It drives the user\'s real Chrome (logins intact) and never spins up a clean browser. Pages opened with open go by default into a separate "DSH work window" in the background without stealing focus, so the page the user is looking at is left alone.',
|
|
16
|
+
'tool.tabs.action': 'list all; find filters by title/URL; open opens a new tab (background work window by default); close closes it; activate brings it to the front (that pulls the window in front of the user — do not use it unless asked)',
|
|
17
|
+
'tool.tabs.query': 'Keyword for action=find (matches title or URL)',
|
|
18
|
+
'tool.tabs.url': 'URL to open when action=open',
|
|
19
|
+
'tool.tabs.tab': 'Tab id for action=close/activate',
|
|
20
|
+
|
|
21
|
+
// ── browser_read ───────────────────────────────────────────────────────
|
|
22
|
+
'tool.read.desc': 'Read page content. what=snapshot lists the elements you can click/fill, each with a [N] ref — call it first when you are about to act, then pass ref=N straight to browser_click / browser_input; that beats guessing selectors (elements inside same-origin iframes are listed too and can be used by ref); text returns the visible text (best for scraping content); html returns the outer HTML; attr returns one attribute; info returns title/URL/viewport and tells you whether an alert/confirm/prompt dialog is blocking the page (if so, call browser_dialog first).',
|
|
23
|
+
'tool.read.what': 'What to read',
|
|
24
|
+
'tool.read.selector': 'CSS selector; for snapshot/text/html it defaults to the whole page',
|
|
25
|
+
'tool.read.name': 'Attribute to read when what=attr, e.g. href',
|
|
26
|
+
'tool.read.limit': 'Maximum characters to return; default 6000 (8000 for snapshot)',
|
|
27
|
+
|
|
28
|
+
// ── browser_click ──────────────────────────────────────────────────────
|
|
29
|
+
'tool.click.desc': 'Click something on the page. Most reliable is ref (the number browser_read what=snapshot gave you); next selector or text (find by visible text); failing that, fall back to x/y coordinates. It sends real mouse events (can trigger new windows, dialogs, focus), not synthetic JS clicks. A small cursor appears on the user\'s screen while clicking.',
|
|
30
|
+
'tool.click.selector': 'CSS selector',
|
|
31
|
+
'tool.click.text': 'Find the element by its visible text and click it (survives redesigns better than a selector)',
|
|
32
|
+
'tool.click.x': 'Viewport X coordinate (with y)',
|
|
33
|
+
'tool.click.y': 'Viewport Y coordinate (with x)',
|
|
34
|
+
'tool.click.count': 'Number of clicks; default 1 (2 = double click)',
|
|
35
|
+
|
|
36
|
+
// ── browser_input ──────────────────────────────────────────────────────
|
|
37
|
+
'tool.input.desc': 'Type into the page: type enters text (focusing selector first if given), key presses keys (combos like meta+a work), select picks a dropdown option, upload attaches files, focus focuses, hover hovers, scroll scrolls.',
|
|
38
|
+
'tool.input.action': 'Input action to perform',
|
|
39
|
+
'tool.input.text': 'Text to enter when action=type',
|
|
40
|
+
'tool.input.ref': '%ref; can replace selector',
|
|
41
|
+
'tool.input.selector': 'CSS selector (for type it is clicked first to focus; select/upload/focus/hover need it or ref)',
|
|
42
|
+
'tool.input.key': 'Key for action=key, e.g. Enter / Escape / "meta+a" / "ctrl+shift+k"',
|
|
43
|
+
'tool.input.value': 'Value or option label to pick when action=select',
|
|
44
|
+
'tool.input.files': 'Absolute local file paths for action=upload (only regular, non-hidden files under the session working directory or the system temp directory)',
|
|
45
|
+
'tool.input.dy': 'Vertical scroll amount for action=scroll; default 600 (positive scrolls down)',
|
|
46
|
+
'tool.input.dx': 'Horizontal scroll amount for action=scroll; default 0',
|
|
47
|
+
'tool.input.x': 'Viewport X for action=hover when no selector is given',
|
|
48
|
+
'tool.input.y': 'Viewport Y for action=hover when no selector is given',
|
|
49
|
+
|
|
50
|
+
// ── browser_nav ────────────────────────────────────────────────────────
|
|
51
|
+
'tool.nav.desc': 'Go to a URL (action=go, the default), or go back, forward or reload. All of them wait for the page to finish loading.',
|
|
52
|
+
'tool.nav.action': 'go navigates to url (default); back / forward / reload need no url',
|
|
53
|
+
'tool.nav.url': 'Target URL when action=go',
|
|
54
|
+
|
|
55
|
+
// ── browser_screenshot ─────────────────────────────────────────────────
|
|
56
|
+
'tool.screenshot.desc': 'Screenshot the page; the image is handed straight to you. mode=viewport captures the visible viewport, full the whole page, element a single element (needs ref or selector). The in-page cursor is captured too, so you see the same picture the user does.',
|
|
57
|
+
'tool.screenshot.mode': 'How much to capture',
|
|
58
|
+
'tool.screenshot.ref': 'Element to capture when mode=element: %ref',
|
|
59
|
+
'tool.screenshot.selector': 'Element to capture when mode=element (CSS selector)',
|
|
60
|
+
'tool.screenshot.format': 'png (default) or jpeg',
|
|
61
|
+
|
|
62
|
+
// ── browser_eval ───────────────────────────────────────────────────────
|
|
63
|
+
'tool.eval.desc': 'Run a snippet of JS in the page and get the return value back. Good for state that selectors cannot reach, inspecting the DOM, and triggering the page\'s own functions. The return value is JSON-serialized. Note: it runs in page context — do not use it to click (use browser_click).',
|
|
64
|
+
'tool.eval.expression': 'JS expression to run; wrap multiple statements in an IIFE and return',
|
|
65
|
+
|
|
66
|
+
// ── browser_wait ───────────────────────────────────────────────────────
|
|
67
|
+
'tool.wait.desc': 'Wait until the page reaches a state, then continue — more reliable than sleep. Pick exactly one of: selector waits for the element to appear (and be visible), text waits for a piece of text to show up, url waits for the URL to contain a substring (handy after a redirect or login). gone=true waits for it to disappear instead (a spinner, say).',
|
|
68
|
+
'tool.wait.selector': 'CSS selector',
|
|
69
|
+
'tool.wait.text': 'Text that must appear in the page\'s visible text',
|
|
70
|
+
'tool.wait.url': 'Substring the URL must contain',
|
|
71
|
+
'tool.wait.gone': 'true = wait for it to disappear; default false',
|
|
72
|
+
'tool.wait.timeoutMs': 'Timeout in milliseconds; default 15000, max %max',
|
|
73
|
+
|
|
74
|
+
// ── browser_dialog ─────────────────────────────────────────────────────
|
|
75
|
+
'tool.dialog.desc': 'Handle alert / confirm / prompt dialogs. A blocking dialog freezes every later action on the page, so when browser_read(what=info) reports one, call this first.',
|
|
76
|
+
'tool.dialog.action': 'accept confirms, dismiss cancels',
|
|
77
|
+
'tool.dialog.text': 'Text to enter into a prompt dialog',
|
|
78
|
+
|
|
79
|
+
// ── browser_drag ───────────────────────────────────────────────────────
|
|
80
|
+
'tool.drag.desc': 'Drag something to another place: sortable lists, kanban cards, sliders, dropping files into a box, canvases and so on. Give the start and the end each as a ref (snapshot number), selector, text (visible text) or x/y coordinates; drop zones ("drop here" boxes) usually have no ref, so toText is the easiest way to find them. Both HTML5 draggable drag-and-drop and mouse-driven components are handled; screenshot or read the page afterwards to confirm the result.',
|
|
81
|
+
'tool.drag.fromRef': 'Start: %ref',
|
|
82
|
+
'tool.drag.fromSelector': 'Start: CSS selector',
|
|
83
|
+
'tool.drag.fromText': 'Start: find the element by visible text',
|
|
84
|
+
'tool.drag.fromX': 'Start: viewport X (with fromY)',
|
|
85
|
+
'tool.drag.fromY': 'Start: viewport Y',
|
|
86
|
+
'tool.drag.toRef': 'End: element ref',
|
|
87
|
+
'tool.drag.toSelector': 'End: CSS selector',
|
|
88
|
+
'tool.drag.toText': 'End: find the element by visible text (best for drop zones)',
|
|
89
|
+
'tool.drag.toX': 'End: viewport X (with toY)',
|
|
90
|
+
'tool.drag.toY': 'End: viewport Y',
|
|
91
|
+
'tool.drag.steps': 'How many mouse steps the drag takes; default 12 (raise it for finer slider control)',
|
|
92
|
+
|
|
93
|
+
// ── browser_download ───────────────────────────────────────────────────
|
|
94
|
+
'tool.download.desc': 'Download the file a link points to (invoice, report, PDF, image …) onto this machine, with the user\'s Chrome logins. Give one of ref (a link\'s snapshot number), selector or url; relative addresses resolve against the page, and blob: / data: links work too. Saved into the "Downloads" folder by default, or into the session working directory with to=workdir; existing files are not overwritten — (1) is appended. If the download control is not a link (the file only exists after a click): click it with browser_click, then find the file URL with browser_devtools action=network and pass that here.',
|
|
95
|
+
'tool.download.selector': 'CSS selector (pointing at an element with an address: a / img / video / source …)',
|
|
96
|
+
'tool.download.url': 'URL to download; a relative address is fine',
|
|
97
|
+
'tool.download.filename': 'File name to save as; defaults to the server-provided name or the name in the URL',
|
|
98
|
+
'tool.download.to': 'downloads (default) saves into the "Downloads" folder; workdir saves into the session working directory',
|
|
99
|
+
|
|
100
|
+
// ── browser_devtools ───────────────────────────────────────────────────
|
|
101
|
+
'tool.devtools.desc': 'Inspect a page the way devtools does: console shows console output and JS errors; network shows network requests (status, timing); response shows the body a particular request returned (JSON from an API, say); clear wipes this tab\'s records. When a page "does nothing when clicked", "shows no data" or "is blank", look here first.',
|
|
102
|
+
'tool.devtools.action': 'What to inspect',
|
|
103
|
+
'tool.devtools.level': 'action=console: error shows errors only, warning shows errors+warnings, default all',
|
|
104
|
+
'tool.devtools.filter': 'console/network: keep only entries containing this text (URL, method or content counts)',
|
|
105
|
+
'tool.devtools.reload': 'action=network: reload the page first to capture every request of the load (only requests after the debugger attached are recorded)',
|
|
106
|
+
'tool.devtools.request': 'action=response: the number after # in the network list',
|
|
107
|
+
'tool.devtools.limit': 'console/network: how many entries (default 40); response: how many characters (default 6000)',
|
|
108
|
+
|
|
109
|
+
// ── errors ─────────────────────────────────────────────────────────────
|
|
110
|
+
'err.dirNotOwned': '%dir is not a directory that belongs only to the current user; refusing to use it',
|
|
111
|
+
'err.bridgeDown': 'The browser bridge is not running (cannot find %sock): Chrome is not open, or the extension is not loaded.\n%hint',
|
|
112
|
+
'err.badJson': 'The host returned bad JSON',
|
|
113
|
+
'err.unknownHostError': 'Unknown error',
|
|
114
|
+
'err.connect': 'Cannot reach the browser bridge: %message\n%hint',
|
|
115
|
+
'err.closed': 'The browser bridge connection was closed',
|
|
116
|
+
'err.timeout': 'Timed out waiting for the browser bridge (%ms)',
|
|
117
|
+
'err.noActiveTab': 'No active tab',
|
|
118
|
+
'err.badTab': 'tab must be a tab id (number) or "active"; got "%tab"',
|
|
119
|
+
'err.noTab': 'No tab given (tab). Use browser_tabs to open (open) or find (list / find) the page you want first, then pass its id as tab; to act on the page the user is looking at, pass tab="active" explicitly. Without tab only the tab you opened or named yourself is reused — the page the user is on is never touched',
|
|
120
|
+
'err.uploadAbs': 'upload needs absolute paths; got: %path',
|
|
121
|
+
'err.uploadMissing': 'File not found: %path',
|
|
122
|
+
'err.uploadHidden': 'Cannot upload a hidden directory / hidden file: %path',
|
|
123
|
+
'err.uploadOutsideCwd': 'Only files under the session working directory (%cwd) or the system temp directory can be uploaded: %path',
|
|
124
|
+
'err.uploadOutside': 'Only files under the session working directory or the system temp directory can be uploaded: %path',
|
|
125
|
+
'err.uploadNotFile': 'Not a regular file: %path',
|
|
126
|
+
'err.openNeedsUrl': 'action=open needs a url',
|
|
127
|
+
'err.unknownAction': 'Unknown action: %action',
|
|
128
|
+
'err.attrNeeds': 'what=attr needs selector and name',
|
|
129
|
+
'err.unknownWhat': 'Unknown what: %what',
|
|
130
|
+
'err.clickNeeds': 'Give one of ref, selector, text or x+y',
|
|
131
|
+
'err.shadowUnsupported': 'Ref %ref is inside the shadow DOM or an iframe, where %action does not support refs yet — use browser_eval instead',
|
|
132
|
+
'err.typeNeedsText': 'action=type needs text',
|
|
133
|
+
'err.keyNeedsKey': 'action=key needs key',
|
|
134
|
+
'err.selectNeedsTarget': 'action=select needs ref or selector',
|
|
135
|
+
'err.selectNeedsValue': 'action=select needs value',
|
|
136
|
+
'err.uploadNeedsTarget': 'action=upload needs ref or selector',
|
|
137
|
+
'err.uploadNeedsFiles': 'action=upload needs files',
|
|
138
|
+
'err.focusNeedsTarget': 'action=focus needs ref or selector',
|
|
139
|
+
'err.hoverNeedsTarget': 'action=hover needs ref or selector, or x/y coordinates',
|
|
140
|
+
'err.navNeedsUrl': 'action=go needs a url',
|
|
141
|
+
'err.shotNeedsTarget': 'mode=element needs ref or selector',
|
|
142
|
+
'err.shotZeroSize': 'That element has no size (it may be hidden), so it cannot be captured',
|
|
143
|
+
'err.waitNeedsOne': 'Give exactly one of selector / text / url',
|
|
144
|
+
'err.dragNeedsEnd': '%which needs one of %ref, %sel, %txt or %xy',
|
|
145
|
+
'err.noWorkdir': 'Cannot determine the session working directory; drop to=workdir to save into the "Downloads" folder',
|
|
146
|
+
'which.start': 'The start',
|
|
147
|
+
'which.end': 'The end',
|
|
148
|
+
|
|
149
|
+
// ── setup hints appended to errors ─────────────────────────────────────
|
|
150
|
+
'hint.extOpened': 'I opened chrome://extensions for you (background tab)%store',
|
|
151
|
+
'hint.extOpenedStore': '; check that DSH Bridge is enabled there',
|
|
152
|
+
'hint.copied': 'The extension folder path is already on the clipboard (%how)',
|
|
153
|
+
'hint.copiedMac': 'in the file picker press ⌘⇧G, then ⌘V and Enter',
|
|
154
|
+
'hint.copiedWin': 'paste it into the file picker\'s address bar and press Enter',
|
|
155
|
+
'hint.notes': '\n(%notes)',
|
|
156
|
+
'hint.notesSep': '; ',
|
|
157
|
+
}
|
package/i18n/index.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 服务端 i18n:工具描述 / 参数说明 / 报错文案的多语言。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不复用 DSH 的 locale 服务:那个(client-locale)只给浏览器端的界面文字用,
|
|
5
|
+
* 工具是注册进模型上下文里的,注册那一刻就得是最终语言。所以这里自己拿字典,
|
|
6
|
+
* 由 config.locale 选一份(见 index.js 的 apply)。
|
|
7
|
+
*
|
|
8
|
+
* 约定和 client.js 一致:字典是普通对象、zh 是基准、缺 key 回落 zh。
|
|
9
|
+
* 占位符用 %name(不是 DSH 的 {name},那个会跟宿主自己的插值撞),支持多字母。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import zh from './zh.js'
|
|
13
|
+
import en from './en.js'
|
|
14
|
+
import ru from './ru.js'
|
|
15
|
+
|
|
16
|
+
/** 基准语言:别的字典缺 key 时回落到这里,也是 config.locale 没给/给错时的默认。 */
|
|
17
|
+
export const DEFAULT_LOCALE = 'zh'
|
|
18
|
+
|
|
19
|
+
export const DICTS = { zh, en, ru }
|
|
20
|
+
export const LOCALES = Object.keys(DICTS)
|
|
21
|
+
|
|
22
|
+
/** "en-US" / "EN" → "en";认不出的(含空值)→ 基准语言,不报错。 */
|
|
23
|
+
export function normalizeLocale(value) {
|
|
24
|
+
if (typeof value !== 'string') return DEFAULT_LOCALE
|
|
25
|
+
const tag = value.trim().toLowerCase().split(/[-_]/)[0]
|
|
26
|
+
return LOCALES.includes(tag) ? tag : DEFAULT_LOCALE
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 模板里用到的占位符名字集合;t() 用它判断译文有没有漏掉参数,test-i18n.mjs 用它做对齐检查。 */
|
|
30
|
+
export function placeholders(template) {
|
|
31
|
+
const found = String(template).match(/%[A-Za-z_]\w*/g) || []
|
|
32
|
+
return new Set(found.map((s) => s.slice(1)))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** %name 替换。没给值的占位符原样留着——漏参数要看得见,不能悄悄吞掉。 */
|
|
36
|
+
export function fmt(template, vars) {
|
|
37
|
+
return String(template).replace(/%([A-Za-z_]\w*)/g, (m, key) => (vars && key in vars ? String(vars[key]) : m))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 按语言造一个 t()。
|
|
42
|
+
* 缺 key → 回落 zh
|
|
43
|
+
* 译文漏了 zh 用到的参数 → 同样回落 zh(不然报错里会少一段细节)
|
|
44
|
+
* key 在 zh 里也没有 → 原样返回 key(方便一眼看出是漏配)
|
|
45
|
+
*
|
|
46
|
+
* dicts 只在测试里传(造一份缺 key / 缺占位符的字典验证兜底),正常调用不用管。
|
|
47
|
+
*/
|
|
48
|
+
export function createT(locale, dicts = DICTS) {
|
|
49
|
+
const base = dicts[DEFAULT_LOCALE] || DICTS[DEFAULT_LOCALE]
|
|
50
|
+
const dict = dicts[normalizeLocale(locale)] || base
|
|
51
|
+
return function t(key, vars) {
|
|
52
|
+
let text = Object.hasOwn(dict, key) ? dict[key] : base[key]
|
|
53
|
+
if (text === undefined) return key
|
|
54
|
+
if (vars) {
|
|
55
|
+
const needed = placeholders(base[key])
|
|
56
|
+
if (needed.size) {
|
|
57
|
+
const have = placeholders(text)
|
|
58
|
+
if ([...needed].some((name) => !have.has(name))) text = base[key]
|
|
59
|
+
}
|
|
60
|
+
return fmt(text, vars)
|
|
61
|
+
}
|
|
62
|
+
return text
|
|
63
|
+
}
|
|
64
|
+
}
|
package/i18n/ru.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Серверный словарь (русский). Ключи те же, что в zh.js — он остаётся эталонным:
|
|
3
|
+
* отсутствующий здесь ключ откатывается на китайский, как и перевод, потерявший
|
|
4
|
+
* подстановку, которая нужна китайскому тексту (см. i18n/index.js).
|
|
5
|
+
*
|
|
6
|
+
* Слой обращён к модели: описания инструментов, справка по параметрам, тексты ошибок.
|
|
7
|
+
* Технические имена (ref, selector, tab, action, what, shadow DOM, iframe) не переводятся —
|
|
8
|
+
* это имена параметров, которые модель передаёт в вызовах.
|
|
9
|
+
*/
|
|
10
|
+
export default {
|
|
11
|
+
// ── общее ───────────────────────────────────────────────────────────────
|
|
12
|
+
'param.tab': 'id вкладки (число) или "active" — вкладка, которую пользователь смотрит прямо сейчас. Если не указан, берётся вкладка, открытая или последней использованная этим сеансом; если такой нет — вызов завершается ошибкой, к вкладке пользователя он не переключается',
|
|
13
|
+
'param.ref': 'Номер элемента — [N] из вывода browser_read(what=snapshot). Самый надёжный способ: если есть ref, не угадывайте селектор',
|
|
14
|
+
|
|
15
|
+
// ── browser_tabs ───────────────────────────────────────────────────────
|
|
16
|
+
'tool.tabs.desc': 'Показать / найти / открыть / закрыть / переключить вкладки Chrome. Остальным инструментам browser_* нужен параметр tab, поэтому сначала вызовите этот, чтобы получить id. Работает с настоящим Chrome пользователя (все логины на месте) и не открывает чистый браузер. Страницы, открытые через open, по умолчанию попадают в отдельное «рабочее окно DSH» в фоне и не забирают фокус, поэтому страница, которую смотрит пользователь, не затрагивается.',
|
|
17
|
+
'tool.tabs.action': 'list — все; find — фильтр по заголовку/URL; open — новая вкладка (по умолчанию в отдельном рабочем окне); close — закрыть; activate — вывести на передний план (окно окажется перед пользователем, поэтому только если об этом просили)',
|
|
18
|
+
'tool.tabs.query': 'Ключевое слово для action=find (по заголовку или URL)',
|
|
19
|
+
'tool.tabs.url': 'URL, который открыть при action=open',
|
|
20
|
+
'tool.tabs.tab': 'id вкладки для action=close/activate',
|
|
21
|
+
|
|
22
|
+
// ── browser_read ───────────────────────────────────────────────────────
|
|
23
|
+
'tool.read.desc': 'Прочитать содержимое страницы. what=snapshot перечисляет элементы, по которым можно кликать и в которые можно вводить текст, каждый с номером [N] — вызовите его первым, если собираетесь действовать, а затем передавайте ref=N прямо в browser_click / browser_input; это надёжнее, чем угадывать селекторы (элементы внутри same-origin iframe тоже попадают в список и доступны по номеру); text возвращает видимый текст (лучший вариант для сбора содержимого); html — внешний HTML; attr — один атрибут; info — заголовок/URL/вьюпорт и сообщает, не блокирует ли страницу диалог (если да, сначала вызовите browser_dialog).',
|
|
24
|
+
'tool.read.what': 'Что читать',
|
|
25
|
+
'tool.read.selector': 'CSS-селектор; для snapshot/text/html по умолчанию вся страница',
|
|
26
|
+
'tool.read.name': 'Атрибут для чтения при what=attr, например href',
|
|
27
|
+
'tool.read.limit': 'Сколько символов вернуть максимум; по умолчанию 6000 (для snapshot — 8000)',
|
|
28
|
+
|
|
29
|
+
// ── browser_click ──────────────────────────────────────────────────────
|
|
30
|
+
'tool.click.desc': 'Кликнуть по странице. Надёжнее всего ref (номер, который выдал browser_read what=snapshot); затем selector или text (поиск по видимому тексту); если ничего не подходит — координаты x/y. Отправляются настоящие события мыши (могут открыть новое окно, диалог, дать фокус), а не поддельный клик из JS. Во время клика на экране пользователя появляется маленький курсор.',
|
|
31
|
+
'tool.click.selector': 'CSS-селектор',
|
|
32
|
+
'tool.click.text': 'Найти элемент по видимому тексту и кликнуть по нему (устойчивее к редизайну, чем селектор)',
|
|
33
|
+
'tool.click.x': 'Координата X во вьюпорте (вместе с y)',
|
|
34
|
+
'tool.click.y': 'Координата Y во вьюпорте (вместе с x)',
|
|
35
|
+
'tool.click.count': 'Сколько раз кликнуть; по умолчанию 1 (2 = двойной клик)',
|
|
36
|
+
|
|
37
|
+
// ── browser_input ──────────────────────────────────────────────────────
|
|
38
|
+
'tool.input.desc': 'Ввод на странице: type — набрать текст (сначала фокусирует selector, если он задан), key — нажать клавишу (сочетания вроде meta+a работают), select — выбрать пункт списка, upload — приложить файлы, focus — сфокусировать, hover — навести, scroll — прокрутить.',
|
|
39
|
+
'tool.input.action': 'Какое действие ввода выполнить',
|
|
40
|
+
'tool.input.text': 'Текст для ввода при action=type',
|
|
41
|
+
'tool.input.ref': '%ref; может заменить selector',
|
|
42
|
+
'tool.input.selector': 'CSS-селектор (для type по нему сначала кликают, чтобы сфокусировать; select/upload/focus/hover нужен он или ref)',
|
|
43
|
+
'tool.input.key': 'Клавиша для action=key, например Enter / Escape / "meta+a" / "ctrl+shift+k"',
|
|
44
|
+
'tool.input.value': 'value или текст пункта для action=select',
|
|
45
|
+
'tool.input.files': 'Абсолютные пути к локальным файлам для action=upload (только обычные, не скрытые файлы внутри рабочей папки сеанса или системного временного каталога)',
|
|
46
|
+
'tool.input.dy': 'Величина вертикальной прокрутки для action=scroll; по умолчанию 600 (положительная — вниз)',
|
|
47
|
+
'tool.input.dx': 'Величина горизонтальной прокрутки для action=scroll; по умолчанию 0',
|
|
48
|
+
'tool.input.x': 'Координата X во вьюпорте для action=hover, если selector не задан',
|
|
49
|
+
'tool.input.y': 'Координата Y во вьюпорте для action=hover, если selector не задан',
|
|
50
|
+
|
|
51
|
+
// ── browser_nav ────────────────────────────────────────────────────────
|
|
52
|
+
'tool.nav.desc': 'Перейти по URL (action=go, по умолчанию), либо назад, вперёд или перезагрузить. Все они дожидаются окончания загрузки страницы.',
|
|
53
|
+
'tool.nav.action': 'go переходит по url (по умолчанию); back / forward / reload url не нужен',
|
|
54
|
+
'tool.nav.url': 'Целевой URL при action=go',
|
|
55
|
+
|
|
56
|
+
// ── browser_screenshot ─────────────────────────────────────────────────
|
|
57
|
+
'tool.screenshot.desc': 'Сделать скриншот страницы; изображение сразу возвращается вам. mode=viewport — видимая область, full — вся страница, element — один элемент (нужен ref или selector). В кадр попадает и курсор на странице, так что вы видите ту же картинку, что и пользователь.',
|
|
58
|
+
'tool.screenshot.mode': 'Что именно снимать',
|
|
59
|
+
'tool.screenshot.ref': 'Элемент для снимка при mode=element: %ref',
|
|
60
|
+
'tool.screenshot.selector': 'Элемент для снимка при mode=element (CSS-селектор)',
|
|
61
|
+
'tool.screenshot.format': 'png (по умолчанию) или jpeg',
|
|
62
|
+
|
|
63
|
+
// ── browser_eval ───────────────────────────────────────────────────────
|
|
64
|
+
'tool.eval.desc': 'Выполнить фрагмент JS на странице и получить возвращённое значение. Полезно для состояния, до которого не добраться селекторами, для просмотра DOM и вызова собственных функций страницы. Возвращённое значение сериализуется в JSON. Внимание: код выполняется в контексте страницы — не используйте его для кликов (для этого browser_click).',
|
|
65
|
+
'tool.eval.expression': 'JS-выражение для выполнения; несколько операторов оберните в IIFE и верните результат',
|
|
66
|
+
|
|
67
|
+
// ── browser_wait ───────────────────────────────────────────────────────
|
|
68
|
+
'tool.wait.desc': 'Дождаться нужного состояния страницы, а затем продолжить — надёжнее, чем sleep. Задайте ровно одно: selector — ждать появления элемента (и его видимости), text — ждать появления фрагмента текста, url — ждать, пока URL будет содержать подстроку (удобно после редиректа или входа). gone=true наоборот ждёт исчезновения (например, спиннера).',
|
|
69
|
+
'tool.wait.selector': 'CSS-селектор',
|
|
70
|
+
'tool.wait.text': 'Текст, который должен появиться в видимом тексте страницы',
|
|
71
|
+
'tool.wait.url': 'Подстрока, которая должна быть в URL',
|
|
72
|
+
'tool.wait.gone': 'true = ждать исчезновения; по умолчанию false',
|
|
73
|
+
'tool.wait.timeoutMs': 'Тайм-аут в миллисекундах; по умолчанию 15000, максимум %max',
|
|
74
|
+
|
|
75
|
+
// ── browser_dialog ─────────────────────────────────────────────────────
|
|
76
|
+
'tool.dialog.desc': 'Обработать диалоги alert / confirm / prompt. Блокирующий диалог замораживает все последующие действия на странице, поэтому если browser_read(what=info) сообщает о диалоге, сначала вызовите этот инструмент.',
|
|
77
|
+
'tool.dialog.action': 'accept подтверждает, dismiss отменяет',
|
|
78
|
+
'tool.dialog.text': 'Текст, который ввести в диалог prompt',
|
|
79
|
+
|
|
80
|
+
// ── browser_drag ───────────────────────────────────────────────────────
|
|
81
|
+
'tool.drag.desc': 'Перетащить объект в другое место: сортируемые списки, карточки канбана, ползунки, перетаскивание файлов в поле, canvas и т. п. Начало и конец задаются одним из: ref (номер из snapshot), selector, text (видимый текст) или координаты x/y; у зоны приёма (рамки «перетащите сюда») обычно нет ref, поэтому проще всего найти её через toText. Поддерживаются и HTML5 drag-and-drop с draggable, и компоненты, которые тащат мышью; после перетаскивания сделайте скриншот или прочитайте страницу, чтобы проверить результат.',
|
|
82
|
+
'tool.drag.fromRef': 'Начало: %ref',
|
|
83
|
+
'tool.drag.fromSelector': 'Начало: CSS-селектор',
|
|
84
|
+
'tool.drag.fromText': 'Начало: найти элемент по видимому тексту',
|
|
85
|
+
'tool.drag.fromX': 'Начало: координата X во вьюпорте (вместе с fromY)',
|
|
86
|
+
'tool.drag.fromY': 'Начало: координата Y во вьюпорте',
|
|
87
|
+
'tool.drag.toRef': 'Конец: номер элемента',
|
|
88
|
+
'tool.drag.toSelector': 'Конец: CSS-селектор',
|
|
89
|
+
'tool.drag.toText': 'Конец: найти элемент по видимому тексту (лучший способ найти зону приёма)',
|
|
90
|
+
'tool.drag.toX': 'Конец: координата X во вьюпорте (вместе с toY)',
|
|
91
|
+
'tool.drag.toY': 'Конец: координата Y во вьюпорте',
|
|
92
|
+
'tool.drag.steps': 'На сколько шагов мыши разбить перетаскивание; по умолчанию 12 (для ползунков можно увеличить)',
|
|
93
|
+
|
|
94
|
+
// ── browser_download ───────────────────────────────────────────────────
|
|
95
|
+
'tool.download.desc': 'Скачать файл, на который указывает ссылка (счёт, отчёт, PDF, картинку …), на этот компьютер, с логинами пользователя в Chrome. Задайте одно из: ref (номер ссылки из snapshot), selector или url; относительный адрес считается от страницы, ссылки blob: / data: тоже работают. По умолчанию сохраняется в папку «Загрузки», с to=workdir — в рабочую папку сеанса; существующие файлы не перезаписываются — добавляется (1). Если кнопка загрузки не ссылка (файл появляется только после клика): кликните по ней через browser_click, затем найдите URL файла через browser_devtools action=network и передайте его сюда.',
|
|
96
|
+
'tool.download.selector': 'CSS-селектор (указывает на элемент с адресом: a / img / video / source …)',
|
|
97
|
+
'tool.download.url': 'URL для загрузки; относительный адрес подойдёт',
|
|
98
|
+
'tool.download.filename': 'Имя файла; по умолчанию берётся имя от сервера или из URL',
|
|
99
|
+
'tool.download.to': 'downloads (по умолчанию) — в папку «Загрузки»; workdir — в рабочую папку сеанса',
|
|
100
|
+
|
|
101
|
+
// ── browser_devtools ───────────────────────────────────────────────────
|
|
102
|
+
'tool.devtools.desc': 'Осмотреть страницу как в devtools: console — вывод консоли и ошибки JS; network — сетевые запросы (статус, время); response — тело, которое вернул конкретный запрос (JSON от API и т. п.); clear — очистить записи этой вкладки. Если страница «не реагирует на клики», «не показывает данные» или «белая», смотрите сначала здесь.',
|
|
103
|
+
'tool.devtools.action': 'Что смотреть',
|
|
104
|
+
'tool.devtools.level': 'action=console: error — только ошибки, warning — ошибки и предупреждения, по умолчанию all',
|
|
105
|
+
'tool.devtools.filter': 'console/network: оставить только записи, содержащие этот текст (URL, метод или содержимое — считается всё)',
|
|
106
|
+
'tool.devtools.reload': 'action=network: сначала перезагрузить страницу, чтобы поймать все запросы загрузки (записываются только запросы после подключения отладчика)',
|
|
107
|
+
'tool.devtools.request': 'action=response: номер после # в списке network',
|
|
108
|
+
'tool.devtools.limit': 'console/network: сколько записей (по умолчанию 40); response: сколько символов (по умолчанию 6000)',
|
|
109
|
+
|
|
110
|
+
// ── тексты ошибок ──────────────────────────────────────────────────────
|
|
111
|
+
'err.dirNotOwned': '%dir — каталог, который принадлежит не только текущему пользователю; использовать его нельзя',
|
|
112
|
+
'err.bridgeDown': 'Мост браузера не запущен (не найден %sock): Chrome не открыт или расширение не загружено.\n%hint',
|
|
113
|
+
'err.badJson': 'Хост вернул некорректный JSON',
|
|
114
|
+
'err.unknownHostError': 'Неизвестная ошибка',
|
|
115
|
+
'err.connect': 'Не удаётся подключиться к мосту браузера: %message\n%hint',
|
|
116
|
+
'err.closed': 'Соединение с мостом браузера закрыто',
|
|
117
|
+
'err.timeout': 'Истекло время ожидания моста браузера (%ms)',
|
|
118
|
+
'err.noActiveTab': 'Нет активной вкладки',
|
|
119
|
+
'err.badTab': 'tab должен быть id вкладки (число) или "active"; получено «%tab»',
|
|
120
|
+
'err.noTab': 'Не указана вкладка (tab). Сначала откройте (open) или найдите (list / find) нужную страницу через browser_tabs, затем передайте её id в tab; чтобы действовать на странице, которую смотрит пользователь, явно передайте tab="active". Без tab используется только вкладка, которую вы сами открыли или назвали, — страница пользователя не затрагивается',
|
|
121
|
+
'err.uploadAbs': 'upload требует абсолютные пути; получено: %path',
|
|
122
|
+
'err.uploadMissing': 'Файл не найден: %path',
|
|
123
|
+
'err.uploadHidden': 'Нельзя загрузить скрытый каталог / скрытый файл: %path',
|
|
124
|
+
'err.uploadOutsideCwd': 'Загружать можно только файлы из рабочей папки сеанса (%cwd) или системного временного каталога: %path',
|
|
125
|
+
'err.uploadOutside': 'Загружать можно только файлы из рабочей папки сеанса или системного временного каталога: %path',
|
|
126
|
+
'err.uploadNotFile': 'Это не обычный файл: %path',
|
|
127
|
+
'err.openNeedsUrl': 'action=open требует url',
|
|
128
|
+
'err.unknownAction': 'Неизвестное действие: %action',
|
|
129
|
+
'err.attrNeeds': 'what=attr требует selector и name',
|
|
130
|
+
'err.unknownWhat': 'Неизвестное what: %what',
|
|
131
|
+
'err.clickNeeds': 'Укажите одно из: ref, selector, text или x+y',
|
|
132
|
+
'err.shadowUnsupported': 'Номер %ref находится в shadow DOM или iframe, где %action пока не поддерживает номера — используйте browser_eval',
|
|
133
|
+
'err.typeNeedsText': 'action=type требует text',
|
|
134
|
+
'err.keyNeedsKey': 'action=key требует key',
|
|
135
|
+
'err.selectNeedsTarget': 'action=select требует ref или selector',
|
|
136
|
+
'err.selectNeedsValue': 'action=select требует value',
|
|
137
|
+
'err.uploadNeedsTarget': 'action=upload требует ref или selector',
|
|
138
|
+
'err.uploadNeedsFiles': 'action=upload требует files',
|
|
139
|
+
'err.focusNeedsTarget': 'action=focus требует ref или selector',
|
|
140
|
+
'err.hoverNeedsTarget': 'action=hover требует ref или selector, либо координаты x/y',
|
|
141
|
+
'err.navNeedsUrl': 'action=go требует url',
|
|
142
|
+
'err.shotNeedsTarget': 'mode=element требует ref или selector',
|
|
143
|
+
'err.shotZeroSize': 'У этого элемента нет размера (возможно, он скрыт) — снять его нельзя',
|
|
144
|
+
'err.waitNeedsOne': 'Укажите ровно одно из: selector / text / url',
|
|
145
|
+
'err.dragNeedsEnd': '%which: нужно одно из %ref, %sel, %txt или %xy',
|
|
146
|
+
'err.noWorkdir': 'Не удалось определить рабочую папку сеанса; уберите to=workdir, чтобы сохранить в папку «Загрузки»',
|
|
147
|
+
'which.start': 'Начало',
|
|
148
|
+
'which.end': 'Конец',
|
|
149
|
+
|
|
150
|
+
// ── подсказки, которые добавляются к ошибкам ───────────────────────────
|
|
151
|
+
'hint.extOpened': 'Я открыл для вас chrome://extensions (в фоновой вкладке)%store',
|
|
152
|
+
'hint.extOpenedStore': ', проверьте, что DSH Bridge включён',
|
|
153
|
+
'hint.copied': 'Путь к папке расширения уже в буфере обмена (%how)',
|
|
154
|
+
'hint.copiedMac': 'в окне выбора файлов нажмите ⌘⇧G, затем ⌘V и Enter',
|
|
155
|
+
'hint.copiedWin': 'вставьте его в адресную строку окна выбора файлов и нажмите Enter',
|
|
156
|
+
'hint.notes': '\n(%notes)',
|
|
157
|
+
'hint.notesSep': '; ',
|
|
158
|
+
}
|