slipwing 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +143 -3
- package/bin/agent-desktop-win32-x64.exe +0 -0
- package/bin/workflow.js +512 -0
- package/browser/LICENSE +201 -0
- package/browser/LICENSE-axe-core-THIRD-PARTY.txt +66 -0
- package/browser/LICENSE-axe-core.txt +362 -0
- package/browser/bin/agent-browser-win32-x64.exe +0 -0
- package/browser/skill-data/agentcore/SKILL.md +115 -0
- package/browser/skill-data/core/SKILL.md +279 -0
- package/browser/skill-data/core/references/authentication.md +413 -0
- package/browser/skill-data/core/references/commands.md +727 -0
- package/browser/skill-data/core/references/profiling.md +120 -0
- package/browser/skill-data/core/references/proxy-support.md +221 -0
- package/browser/skill-data/core/references/session-management.md +215 -0
- package/browser/skill-data/core/references/snapshot-refs.md +244 -0
- package/browser/skill-data/core/references/streaming.md +107 -0
- package/browser/skill-data/core/references/trust-boundaries.md +69 -0
- package/browser/skill-data/core/references/video-recording.md +254 -0
- package/browser/skill-data/core/references/webgpu.md +118 -0
- package/browser/skill-data/core/templates/authenticated-session.sh +109 -0
- package/browser/skill-data/core/templates/capture-workflow.sh +69 -0
- package/browser/skill-data/core/templates/form-automation.sh +63 -0
- package/browser/skill-data/derive-client/SKILL.md +88 -0
- package/browser/skill-data/dogfood/SKILL.md +224 -0
- package/browser/skill-data/dogfood/references/issue-taxonomy.md +109 -0
- package/browser/skill-data/dogfood/templates/dogfood-report-template.md +53 -0
- package/browser/skill-data/electron/SKILL.md +236 -0
- package/browser/skill-data/modern-web-guidance/SKILL.md +165 -0
- package/browser/skill-data/slack/SKILL.md +288 -0
- package/browser/skill-data/slack/references/slack-tasks.md +349 -0
- package/browser/skill-data/slack/templates/slack-report-template.md +163 -0
- package/browser/skill-data/vercel/SKILL.md +160 -0
- package/browser/skill-data/vercel-sandbox/SKILL.md +237 -0
- package/browser/skill-data/webmcp-gen/SKILL.md +52 -0
- package/browser/skills/agent-browser/SKILL.md +51 -0
- package/bundle.json +19 -0
- package/lib/browser-move.js +185 -0
- package/lib/bundle-version.js +32 -0
- package/lib/choose.js +382 -0
- package/lib/cli-options.js +47 -0
- package/lib/control-changes.js +47 -0
- package/lib/current-page.js +165 -0
- package/lib/error-code.js +19 -0
- package/lib/final-picture.js +31 -0
- package/lib/final-words.json +7 -0
- package/lib/flow-record.js +32 -0
- package/lib/host-client.js +65 -0
- package/lib/host-command.js +175 -0
- package/lib/host-paths.js +22 -0
- package/lib/host-server.js +383 -0
- package/lib/host-waits.js +12 -0
- package/lib/host-watch.js +340 -0
- package/lib/mcp-guide.js +45 -0
- package/lib/mcp-server.js +264 -0
- package/lib/notify.js +31 -0
- package/lib/page-choice.js +273 -0
- package/lib/page-input.js +141 -0
- package/lib/page-lease.js +87 -0
- package/lib/page-line.js +83 -0
- package/lib/page-pointer.js +191 -0
- package/lib/page-read.js +44 -0
- package/lib/platform.js +89 -0
- package/lib/png-mark.js +83 -0
- package/lib/prefs.js +228 -0
- package/lib/routine-approvals.js +67 -0
- package/lib/routine-command.js +150 -0
- package/lib/routine-effects.js +119 -0
- package/lib/routine-store.js +143 -0
- package/lib/script-args.js +48 -0
- package/lib/script-call.js +63 -0
- package/lib/script-desktop.js +731 -0
- package/lib/script-final.js +93 -0
- package/lib/script-fix.js +121 -0
- package/lib/script-input.js +25 -0
- package/lib/script-match.js +90 -0
- package/lib/script-picture.js +104 -0
- package/lib/script-repeat.js +43 -0
- package/lib/script-run.js +367 -0
- package/lib/script-screen.js +53 -0
- package/lib/script-visible.js +228 -0
- package/lib/script-wait.js +15 -0
- package/lib/script-web.js +338 -0
- package/lib/skill-command.js +81 -0
- package/lib/space.js +56 -0
- package/lib/text-match.js +18 -0
- package/lib/watch-helper.ps1 +200 -0
- package/lib/web-page.js +214 -0
- package/lib/window-move.js +213 -0
- package/lib/windows-bin.js +44 -0
- package/package.json +32 -5
- package/scripts/initialize-state.ps1 +13 -0
- package/skills/slipwing/SKILL.md +189 -0
- package/skills/slipwing/chrome.md +62 -0
- package/skills/slipwing/desktop.md +82 -0
- package/skills/slipwing/human.md +63 -0
- package/skills/slipwing/jobs.md +82 -0
- package/skills/slipwing/routines.md +73 -0
- package/skills/slipwing/watches.md +37 -0
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { setTimeout: delay } = require('node:timers/promises');
|
|
4
|
+
const { invoke, foregroundInterruption } = require('./script-call');
|
|
5
|
+
const { createWeb } = require('./script-web');
|
|
6
|
+
const { createDesktop } = require('./script-desktop');
|
|
7
|
+
const { createVisible, readingMs } = require('./script-visible');
|
|
8
|
+
const { readPage } = require('./page-read');
|
|
9
|
+
const { inputUses, inputRefused } = require('./script-input');
|
|
10
|
+
const { argsView, missingArgs } = require('./script-args');
|
|
11
|
+
const { scanFinals, guardFinals, finalRefused } = require('./script-final');
|
|
12
|
+
const { screenWeb } = require('./script-screen');
|
|
13
|
+
const { fixable } = require('./script-fix');
|
|
14
|
+
const { surfaceRefused } = require('./routine-approvals');
|
|
15
|
+
|
|
16
|
+
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
|
|
17
|
+
const SCENE_WAIT_MS = 8000;
|
|
18
|
+
const SUBJECT_LIMIT = 60;
|
|
19
|
+
|
|
20
|
+
const api = [
|
|
21
|
+
'A script is the body of an async function. It runs many steps in one call and returns one JSON reply.',
|
|
22
|
+
'Return a value to get it back as data.result. A step that fails stops the script; the reply then names the step',
|
|
23
|
+
'and carries data.scene, a fresh read of the page or window, so the next script can continue from there.',
|
|
24
|
+
'Values given with run --args JSON are read as args.name; a script that reads a name nobody gave stops with MISSING_ARGS.',
|
|
25
|
+
'',
|
|
26
|
+
'A target is the name shown in quotes by read(), a ref (@e5), or css:SELECTOR. When a name repeats, add',
|
|
27
|
+
'{near: "text in the same row or card"}, {nth: 2} or {role: "button"}.',
|
|
28
|
+
'Steps wait up to 4 s for a control that is not there yet, is disabled or is covered; {timeout: ms} changes that.',
|
|
29
|
+
'A click on a control named like 发送, 提交, 付款, 删除, Send, Submit, Pay or Delete, and any step given {final: "what it does"},',
|
|
30
|
+
'is a final step: without run --allow-final it is refused with FINAL_NOT_ALLOWED before anything is sent. {final: false} clears a name.',
|
|
31
|
+
'Names reach into frames and shadow DOM. css: selectors and web.text()/web.table() see the top document only.',
|
|
32
|
+
'read() lists controls, not messages. To see what an action produced, use waitText(), which returns the text.',
|
|
33
|
+
'A line in data.steps says what the step changed: a window that opened, closed or changed title, a page that went to another',
|
|
34
|
+
'address, a new tab or a dialog. A step that used the real mouse and keyboard says so, and data.input_used is then true.',
|
|
35
|
+
'Desktop clicks, ticks and unconfirmed fills also say which controls changed: "合计" value "0.00" -> "231.00", "需要发票" checked,',
|
|
36
|
+
'2 controls appeared: "确定", "取消". A value the step itself wrote shows only as value changed. "no control changed" covers',
|
|
37
|
+
'controls only: text a window merely draws is not compared, so read the window or waitText() before calling a step failed,',
|
|
38
|
+
'and never send a final step again on that line alone.',
|
|
39
|
+
'',
|
|
40
|
+
'The real mouse and keyboard (visible.*, human(), desktop.type, filling by picture, --headed) need run --allow-input. Without',
|
|
41
|
+
'it such a step is refused with code INPUT_NOT_ALLOWED before anything is sent: ask the user, then run the steps that are',
|
|
42
|
+
'left with --allow-input. Everything else runs in the background and leaves the mouse and keyboard alone.',
|
|
43
|
+
'',
|
|
44
|
+
'web (background browser, or your Chrome with --chrome):',
|
|
45
|
+
' await web.open(url) -> {url, title}',
|
|
46
|
+
' await web.read() -> controls only, with names and refs; web.read({all:true}) adds the page text',
|
|
47
|
+
' await web.fill(target, value) await web.type(target, text) (type sends real keys)',
|
|
48
|
+
' await web.click(target, {role, nth}) await web.press("Enter")',
|
|
49
|
+
' await web.select(target, option) await web.check(target) await web.uncheck(target)',
|
|
50
|
+
' await web.waitText(text, ms = 10000) -> the whole line or sentence that shows it, for example "订单号 D6176 已提交";',
|
|
51
|
+
' text already on the page counts at once, so wait for what the action produces.',
|
|
52
|
+
' waitText(["已签收", "没有找到"]) returns the first of several that shows',
|
|
53
|
+
' await web.waitFor(target, {timeout}) await web.has(target) -> true when the control is there and enabled',
|
|
54
|
+
' await web.waitIdle({timeout}) -> the page read once it stops changing; for when you cannot know what text will appear',
|
|
55
|
+
' await web.text() -> readable page text; web.text(target) -> text of one element',
|
|
56
|
+
' await web.value(target) await web.table(cssSelector?) -> rows of cell text',
|
|
57
|
+
' await web.eval("document.title") await web.url() await web.title()',
|
|
58
|
+
' await web.fetch(url) -> {url, via, text}: the text of another address, read without leaving the current page',
|
|
59
|
+
' await web.selection() -> the text the user selected on the page, or null',
|
|
60
|
+
' await web.cmd("scroll", "down", "600") -> any agent-browser command, returns its data',
|
|
61
|
+
'',
|
|
62
|
+
'desktop (windows are ids from desktop.windows(), or part of an app name or title):',
|
|
63
|
+
' await desktop.windows(filter?) -> [{id, app, title, minimized, focused}]',
|
|
64
|
+
' await desktop.apps(filter?) -> installed apps [{name, id, kind, path, window_open}]',
|
|
65
|
+
' await desktop.launch(nameOrId) -> {app, pid, window, title}: opens an installed app by its name, id or program name',
|
|
66
|
+
' await desktop.focused(window) -> {role, name, ref} of the focused control, or null',
|
|
67
|
+
' await desktop.selection(window, target?) -> the text selected in that control, else in the focused one or the first text field that has a selection, or null',
|
|
68
|
+
' await desktop.read(window) -> controls by name, without the title bar; {all:true} adds labels and status text; {picture:true} adds the text on screen; {refs:true} adds refs and the title bar',
|
|
69
|
+
' await desktop.click(window, target) await desktop.fill(window, target, value)',
|
|
70
|
+
' await desktop.select(window, field, option) -> picks an option of a drop-down or list, as fill does',
|
|
71
|
+
' await desktop.check(window, target) await desktop.uncheck(window, target)',
|
|
72
|
+
' await desktop.value(window, target) await desktop.has(window, target) await desktop.waitFor(window, target, {timeout})',
|
|
73
|
+
' await desktop.waitText(window, text, ms = 10000) -> the line that shows the text',
|
|
74
|
+
' await desktop.waitIdle(window, {timeout}) -> the window read once it stops changing',
|
|
75
|
+
' await desktop.cmd("press", "ctrl+s", "--app", "notepad") -> any agent-desktop command, returns its data',
|
|
76
|
+
'A name no control has is looked for in the window\'s picture right away, and a window with no control outside its',
|
|
77
|
+
'title bar is read from its picture; read() then lists that text as [picture x,y]. click by picture is first posted to',
|
|
78
|
+
'the window in the background and returns {via: "picture", background: true, text, x, y} when the window then changes;',
|
|
79
|
+
'FOREGROUND_TAKEN stops the run. Tell the user to switch back to their working window and check the last action before continuing.',
|
|
80
|
+
'CLICK_UNCONFIRMED means it may have arrived. Check the result before another click. Only a confirmed refusal of the',
|
|
81
|
+
'background method can fall back to the real mouse (needs --allow-input). fill by picture clicks, types, and returns false',
|
|
82
|
+
'when the typed text cannot be seen afterwards. The same text in several places needs {near} or {nth}.',
|
|
83
|
+
'{picture: false} keeps a step to controls; waitText takes it as a fourth argument.',
|
|
84
|
+
'',
|
|
85
|
+
'visible (the page in the Chrome window on screen, with the real mouse and keyboard; one helper is one thing a person does; needs --allow-input):',
|
|
86
|
+
' await visible.use(window?) -> {title, url, text, controls}: binds the tab on screen; later helpers bind again when the page changes',
|
|
87
|
+
' await visible.read() -> the same, read fresh',
|
|
88
|
+
' await visible.click(name, {role, nth, expectText}) await visible.hover(name)',
|
|
89
|
+
' await visible.choose(name) -> ticks a radio button or checkbox and confirms it: {changed, checked}; {off: true} clears a checkbox.',
|
|
90
|
+
' {gone: true} means the page moved on and the choice is no longer there to check',
|
|
91
|
+
' await visible.type(field, text, {multiline, replace, at}) -> true when the field shows the text. Text goes in at the caret, and a field',
|
|
92
|
+
' nobody clicked has its caret at the start: {at: "end"} appends, {multiline: true} lets a line break press Enter',
|
|
93
|
+
' await visible.scrollTo(text) -> turns the wheel until the text is on screen; {over: "text inside a panel"} scrolls that panel',
|
|
94
|
+
' await visible.scroll(lines = 3, {over}) -> positive is down',
|
|
95
|
+
' await visible.open(url) -> opens the address in a new tab of the user\'s Chrome and binds it; never reuses an open tab',
|
|
96
|
+
' await visible.select(field, option) -> picks one option of a dropdown on the screen page',
|
|
97
|
+
' await visible.press(keys) -> presses keys in that Chrome window, for example "enter" or "ctrl+a"',
|
|
98
|
+
' await visible.waitText(text) / waitFor(name) / waitIdle() / has(name) -> the same waits and checks as web.*, on the screen page',
|
|
99
|
+
'With --mode watch or record, web.* runs here on screen: the same script that runs in the background browser runs where the',
|
|
100
|
+
'user can follow it. web.eval, table, fetch, cmd, selection, value and {near} work in the background browser only.',
|
|
101
|
+
'',
|
|
102
|
+
'acting like a person (for a recording or a demonstration; slower, takes the mouse and keyboard, needs --allow-input):',
|
|
103
|
+
' human("natural") -> from here on visible.*, desktop.click and desktop.type move and type like a person;',
|
|
104
|
+
' "careful" is slower near small targets; human(false) turns it off',
|
|
105
|
+
' await readTime(text) -> waits about as long as reading that text takes; returns at once while human() is off.',
|
|
106
|
+
' Use it instead of sleep(): a wait should follow what is on screen, not a fixed number.',
|
|
107
|
+
' await desktop.type(window, target, text, {multiline, at}) -> real keys into a field (desktop.fill writes the value directly and needs no keys)',
|
|
108
|
+
' await desktop.sequence(window, [{click: name}, {type: [name, text]}, {press: "ctrl+s"}]) -> several of these in one go: the names are',
|
|
109
|
+
' looked up once and the hand does not stop between them (about 0.45 s instead of 1 s)',
|
|
110
|
+
'',
|
|
111
|
+
'other:',
|
|
112
|
+
' await sleep(ms) await waitFor(async () => condition, {timeout, interval}) log(...values) expect(condition, message)',
|
|
113
|
+
' await flow(command, options) -> any other slipwing command, for example flow("view", {window, output})',
|
|
114
|
+
'',
|
|
115
|
+
'Example:',
|
|
116
|
+
' await web.open("https://example.com/login");',
|
|
117
|
+
' await web.fill("邮箱", "a@example.com");',
|
|
118
|
+
' await web.click("下一步");',
|
|
119
|
+
' await web.waitText("验证码已发送");',
|
|
120
|
+
' return await web.read();',
|
|
121
|
+
].join('\n');
|
|
122
|
+
|
|
123
|
+
/** A misspelled helper answers with the helpers that exist, so the next script can be right. */
|
|
124
|
+
function named(name, helpers) {
|
|
125
|
+
return new Proxy(helpers, {
|
|
126
|
+
get(target, key) {
|
|
127
|
+
if (typeof key !== 'string' || key in target || key === 'then') return target[key];
|
|
128
|
+
throw Object.assign(new Error(name + '.' + key + ' is not a helper. ' + name + ' has: ' + Object.keys(target).sort().join(', ') + '.'), { code: 'INVALID_ARGS' });
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Commands started by a script keep the agent pointer on screen from the
|
|
135
|
+
* first real input to the end of the script, not just for their own run.
|
|
136
|
+
*/
|
|
137
|
+
function holding(env) {
|
|
138
|
+
return env.AGENT_DESKTOP_POINTER_HOLDER ? env : { ...env, AGENT_DESKTOP_POINTER_HOLDER: String(process.pid) };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function brief(subject) {
|
|
142
|
+
const text = typeof subject === 'string' ? subject : subject === undefined ? '' : JSON.stringify(subject);
|
|
143
|
+
return text.length > SUBJECT_LIMIT ? text.slice(0, SUBJECT_LIMIT) + '…' : text;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Runs a script against the page and desktop helpers and reports every step it took. */
|
|
147
|
+
async function runScript(source, { browser, native, flags = [], lease, env, timeout = 120000, flow, call = invoke, picture, allowInput: allowInputOption = false,
|
|
148
|
+
args = {}, allowFinal = false, onStep, watch = false, fix, finalsAtRunTime = false, hands, approvedRoutine = false, startPace, screen = false, openUrl } = {}) {
|
|
149
|
+
const handsFree = () => (typeof allowInputOption === 'function' ? allowInputOption() : allowInputOption);
|
|
150
|
+
let approvedOnce = false;
|
|
151
|
+
const finalAllowed = () => {
|
|
152
|
+
if (allowFinal) return true;
|
|
153
|
+
if (!approvedOnce) return false;
|
|
154
|
+
approvedOnce = false;
|
|
155
|
+
return true;
|
|
156
|
+
};
|
|
157
|
+
const watching = () => watch || Boolean(onStep);
|
|
158
|
+
const started = Date.now();
|
|
159
|
+
env = holding(env ?? process.env);
|
|
160
|
+
const steps = [], logs = [], warnings = [], children = new Set(), records = [], finals = [];
|
|
161
|
+
const touched = { apps: new Set(), hosts: new Set() };
|
|
162
|
+
let surface, foregroundStop, inputUsed = false, effects = [];
|
|
163
|
+
|
|
164
|
+
let notes = [];
|
|
165
|
+
/**
|
|
166
|
+
* Every command that takes the real mouse and keyboard passes here first. Without
|
|
167
|
+
* --allow-input it is refused before anything is sent; with it, the step is marked.
|
|
168
|
+
*/
|
|
169
|
+
const takeInput = what => {
|
|
170
|
+
if (!handsFree()) throw inputRefused('This step needs the real mouse and keyboard' + (what ? ' (' + what + ')' : '') + ': the window comes to the front and the pointer moves.');
|
|
171
|
+
hands?.using();
|
|
172
|
+
inputUsed = true;
|
|
173
|
+
if (!notes.includes('real mouse and keyboard')) notes.push('real mouse and keyboard');
|
|
174
|
+
};
|
|
175
|
+
const gate = args => { if (args.includes('--headed')) takeInput(); };
|
|
176
|
+
const step = async (name, subject, run) => {
|
|
177
|
+
if (foregroundStop) throw foregroundStop;
|
|
178
|
+
const at = Date.now();
|
|
179
|
+
surface = name.split('.')[0];
|
|
180
|
+
const label = name + (brief(subject) ? ' ' + brief(subject) : '');
|
|
181
|
+
notes = [];
|
|
182
|
+
effects = [];
|
|
183
|
+
const how = () => (notes.length ? ' (' + notes.join(', ') + ')' : '');
|
|
184
|
+
let recorded = false;
|
|
185
|
+
const record = ok => {
|
|
186
|
+
recorded = true;
|
|
187
|
+
const entry = { label, effects, input: notes.includes('real mouse and keyboard'), ms: Date.now() - at, ok };
|
|
188
|
+
records.push(entry);
|
|
189
|
+
return entry;
|
|
190
|
+
};
|
|
191
|
+
try {
|
|
192
|
+
const value = await run();
|
|
193
|
+
if (foregroundStop) throw foregroundStop;
|
|
194
|
+
const done = record(true);
|
|
195
|
+
if (onStep) await onStep(done);
|
|
196
|
+
steps.push(label + how() + ' ' + (Date.now() - at) + 'ms');
|
|
197
|
+
return value;
|
|
198
|
+
} catch (err) {
|
|
199
|
+
if (err?.code === 'FOREGROUND_TAKEN') foregroundStop ??= err;
|
|
200
|
+
err = foregroundStop ?? err;
|
|
201
|
+
if (!recorded) record(false);
|
|
202
|
+
steps.push(label + how() + ' ' + (Date.now() - at) + 'ms FAILED');
|
|
203
|
+
if (err && typeof err === 'object' && !err.step) err.step = label;
|
|
204
|
+
throw err;
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
const need = (binary, name, check = () => {}) => async (args, options) => {
|
|
208
|
+
if (foregroundStop) throw foregroundStop;
|
|
209
|
+
if (!binary) throw new Error(name + ' is not installed.');
|
|
210
|
+
check(args);
|
|
211
|
+
if (name !== 'agent-desktop') return call(binary, args, { env, children, ...options });
|
|
212
|
+
let data;
|
|
213
|
+
try { data = await call(binary, args, { env, children, ...options }); }
|
|
214
|
+
catch (err) { foregroundStop ??= foregroundInterruption(err); throw foregroundStop ?? err; }
|
|
215
|
+
foregroundStop ??= foregroundInterruption(data);
|
|
216
|
+
if (foregroundStop) throw foregroundStop;
|
|
217
|
+
return data;
|
|
218
|
+
};
|
|
219
|
+
const note = (text, effect) => {
|
|
220
|
+
if (text) notes.push(text);
|
|
221
|
+
if (effect) effects.push(effect);
|
|
222
|
+
};
|
|
223
|
+
const touch = ({ app, host }) => {
|
|
224
|
+
if (!approvedRoutine) {
|
|
225
|
+
const refused = surfaceRefused({ app, host });
|
|
226
|
+
if (refused) throw refused;
|
|
227
|
+
}
|
|
228
|
+
if (app) touched.apps.add(app);
|
|
229
|
+
if (host) touched.hosts.add(host);
|
|
230
|
+
};
|
|
231
|
+
const page = createWeb({
|
|
232
|
+
call: need(browser, 'agent-browser'), step, warn: text => warnings.push(text), note, flags: lease ? () => lease.flags() : flags, touch, watching,
|
|
233
|
+
fetchPage: url => readPage(browser, url, (binary, args, options) => need(binary, 'agent-browser')(args, options)),
|
|
234
|
+
});
|
|
235
|
+
let pace = startPace;
|
|
236
|
+
const desk = createDesktop({ call: need(native, 'agent-desktop', gate), step, warn: text => warnings.push(text), note, picture, pace: () => pace,
|
|
237
|
+
inputAllowed: handsFree, touch, watching, interrupted: () => Boolean(hands?.cutShort?.()) });
|
|
238
|
+
const seen = createVisible({ step, warn: text => warnings.push(text), pace: () => pace, takeInput,
|
|
239
|
+
pressKey: (window, key) => desk.desktop.sequence(window, [{ press: key }]),
|
|
240
|
+
...(openUrl ? { openUrl } : {}),
|
|
241
|
+
flow: (command, options) => {
|
|
242
|
+
if (!flow) throw new Error('The visible page helpers are not available here.');
|
|
243
|
+
return flow(command, options, gate);
|
|
244
|
+
} });
|
|
245
|
+
const webSurface = screen ? screenWeb(seen.visible) : page.web;
|
|
246
|
+
const guarded = guardFinals({ web: webSurface, desktop: desk.desktop, visible: seen.visible }, {
|
|
247
|
+
allowed: finalAllowed,
|
|
248
|
+
onFinal: final => finals.push(final),
|
|
249
|
+
mark: (on, callArgs) => (on === 'web' && !screen ? page.markTarget(callArgs[0]) : on === 'desktop' ? desk.markTarget(callArgs[0], callArgs[1]) : undefined),
|
|
250
|
+
});
|
|
251
|
+
const sceneOf = async on => {
|
|
252
|
+
try {
|
|
253
|
+
const look = on === 'desktop' ? desk.scene() : on === 'web' && !screen ? page.scene() : on === 'visible' || on === 'web' ? seen.scene() : undefined;
|
|
254
|
+
return await Promise.race([look, delay(SCENE_WAIT_MS)]);
|
|
255
|
+
} catch { return undefined; }
|
|
256
|
+
};
|
|
257
|
+
let sceneAtFix;
|
|
258
|
+
const surfaces = fix ? fixable(guarded, {
|
|
259
|
+
fixes: fix.fixes,
|
|
260
|
+
approvals: fix.approvals,
|
|
261
|
+
waitHands: hands?.wait,
|
|
262
|
+
allowOnce: () => { approvedOnce = true; },
|
|
263
|
+
ask: async info => {
|
|
264
|
+
sceneAtFix = await sceneOf(info.surface);
|
|
265
|
+
return fix.ask({ ...info, scene: sceneAtFix });
|
|
266
|
+
},
|
|
267
|
+
runPatch: patchSource => new AsyncFunction(...Object.keys(helpers), 'scene', String(patchSource))(...Object.values(helpers), sceneAtFix),
|
|
268
|
+
}) : guarded;
|
|
269
|
+
/**
|
|
270
|
+
* A person took over: typing in progress is stopped, since their keys would mix into it; a pointer movement in
|
|
271
|
+
* progress stops by itself when the cursor is moved, and any other command is left to finish. Whether something
|
|
272
|
+
* was cut short is the answer.
|
|
273
|
+
*/
|
|
274
|
+
hands?.bind?.({ abort: () => {
|
|
275
|
+
let cut = false;
|
|
276
|
+
for (const child of children) {
|
|
277
|
+
if (child.spawnargs?.includes('--headed') && child.spawnargs.includes('type')) { child.kill(); cut = true; }
|
|
278
|
+
}
|
|
279
|
+
return cut;
|
|
280
|
+
} });
|
|
281
|
+
const helpers = {
|
|
282
|
+
args: argsView(args),
|
|
283
|
+
web: named('web', surfaces.web),
|
|
284
|
+
desktop: named('desktop', surfaces.desktop),
|
|
285
|
+
visible: named('visible', surfaces.visible),
|
|
286
|
+
human: value => {
|
|
287
|
+
if (![false, undefined, 'natural', 'careful'].includes(value)) throw Object.assign(new Error('human() takes "natural", "careful" or false.'), { code: 'INVALID_ARGS' });
|
|
288
|
+
if (value && !handsFree() && !hands) throw inputRefused('human("' + value + '") moves the real mouse and keyboard.');
|
|
289
|
+
pace = value || undefined;
|
|
290
|
+
},
|
|
291
|
+
readTime: text => (pace ? delay(readingMs(text) * (pace === 'careful' ? 1.3 : 1)) : Promise.resolve()),
|
|
292
|
+
flow: (command, options = {}) => step('flow.' + command, '', () => {
|
|
293
|
+
if (!flow || command === 'run') throw new Error('flow() cannot run "' + command + '".');
|
|
294
|
+
return flow(String(command), options, gate);
|
|
295
|
+
}),
|
|
296
|
+
sleep: ms => delay(ms),
|
|
297
|
+
waitFor: async (condition, { timeout: wait = 10000, interval = 200 } = {}) => {
|
|
298
|
+
const until = Date.now() + wait;
|
|
299
|
+
for (;;) {
|
|
300
|
+
const value = await condition();
|
|
301
|
+
if (value) return value;
|
|
302
|
+
if (Date.now() >= until) throw Object.assign(new Error('The condition did not become true within ' + wait + ' ms.'), { code: 'TIMEOUT' });
|
|
303
|
+
await delay(interval);
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
log: (...values) => { logs.push(values.map(v => typeof v === 'string' ? v : JSON.stringify(v)).join(' ')); },
|
|
307
|
+
expect: (condition, message) => {
|
|
308
|
+
if (!condition) throw Object.assign(new Error(message ?? 'An expectation in the script was not met.'), { code: 'EXPECTATION_FAILED' });
|
|
309
|
+
},
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
const report = () => ({
|
|
313
|
+
...(warnings.length ? { warnings } : {}), ...(logs.length ? { logs } : {}), steps,
|
|
314
|
+
...(inputUsed ? { input_used: true } : {}), ...(finals.length ? { finals } : {}), ...browserOfItsOwn(), elapsed_ms: Date.now() - started,
|
|
315
|
+
});
|
|
316
|
+
const browserOfItsOwn = () => {
|
|
317
|
+
const name = lease?.own();
|
|
318
|
+
return name ? { browser_session: name, browser_note: 'Another run was using the shared browser, so this run had a browser of its own. ' +
|
|
319
|
+
'It stays 10 minutes after its last step; a next script continues on its page with run --session ' + name + '.' } : {};
|
|
320
|
+
};
|
|
321
|
+
const trail = () => ({ records, apps: [...touched.apps], hosts: [...touched.hosts] });
|
|
322
|
+
const withTrail = (target, value = trail()) => Object.defineProperty(target, 'trail', { value, enumerable: false });
|
|
323
|
+
let body;
|
|
324
|
+
try { body = new AsyncFunction(...Object.keys(helpers), source); } catch (err) {
|
|
325
|
+
throw Object.assign(new Error('The script does not parse: ' + err.message), { code: 'INVALID_ARGS', report: report() });
|
|
326
|
+
}
|
|
327
|
+
const missing = missingArgs(source, args);
|
|
328
|
+
if (missing.length) {
|
|
329
|
+
throw Object.assign(new Error('The script reads arguments that were not given: ' + missing.join(', ') + '. Pass them with --args JSON.'),
|
|
330
|
+
{ code: 'MISSING_ARGS', details: { needs: missing }, report: report() });
|
|
331
|
+
}
|
|
332
|
+
const seenFinals = allowFinal || finalsAtRunTime ? [] : scanFinals(source);
|
|
333
|
+
if (seenFinals.length) {
|
|
334
|
+
throw Object.assign(finalRefused('This script has final steps (' + seenFinals.map(f => f.what + ': ' + f.why).join('; ') + '), so none of it ran.',
|
|
335
|
+
{ finals: seenFinals }), { report: report() });
|
|
336
|
+
}
|
|
337
|
+
const uses = handsFree() || hands ? [] : inputUses(source);
|
|
338
|
+
if (uses.length) {
|
|
339
|
+
throw Object.assign(inputRefused('This script uses the real mouse and keyboard (' + uses.join(', ') + '), so none of it ran.',
|
|
340
|
+
'Ask the user first; when they agree, run it again with --allow-input.'), { report: report() });
|
|
341
|
+
}
|
|
342
|
+
let timer;
|
|
343
|
+
const expired = new Promise((_, reject) => {
|
|
344
|
+
timer = setTimeout(() => reject(Object.assign(new Error('The script did not finish within ' + timeout + ' ms.'), { code: 'TIMEOUT' })), timeout);
|
|
345
|
+
});
|
|
346
|
+
try {
|
|
347
|
+
const result = await Promise.race([body(...Object.values(helpers)), expired]);
|
|
348
|
+
if (foregroundStop) throw foregroundStop;
|
|
349
|
+
return withTrail({ result: result === undefined ? null : result, ...report() });
|
|
350
|
+
} catch (thrown) {
|
|
351
|
+
const err = foregroundStop ?? (thrown instanceof Error ? thrown : new Error(String(thrown)));
|
|
352
|
+
for (const child of children) child.kill();
|
|
353
|
+
let scene;
|
|
354
|
+
try {
|
|
355
|
+
const look = surface === 'desktop' ? desk.scene() : surface === 'web' ? page.scene() : surface === 'visible' ? seen.scene() : undefined;
|
|
356
|
+
scene = await Promise.race([look, delay(SCENE_WAIT_MS)]);
|
|
357
|
+
} catch { /* The page or window may be gone. */ }
|
|
358
|
+
err.report = { ...(err.step ? { step: err.step } : {}), ...report(), ...(scene ? { scene } : {}) };
|
|
359
|
+
withTrail(err);
|
|
360
|
+
throw err;
|
|
361
|
+
} finally {
|
|
362
|
+
clearTimeout(timer);
|
|
363
|
+
await lease?.release();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
module.exports = { runScript, api };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { setTimeout: delay } = require('node:timers/promises');
|
|
4
|
+
|
|
5
|
+
/** Helpers only the background browser has; on screen they are refused rather than run against another page. */
|
|
6
|
+
const BACKGROUND_ONLY = ['eval', 'table', 'fetch', 'cmd', 'selection', 'value'];
|
|
7
|
+
|
|
8
|
+
function refused(message) {
|
|
9
|
+
return Object.assign(new Error(message), { code: 'INVALID_ARGS' });
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* web.* for the ways of working that happen on screen (watch and record): the same helper names, done in the Chrome
|
|
14
|
+
* window the user can see, through visible.* with the real mouse and keyboard at the script's pace. A script written
|
|
15
|
+
* for the background browser runs unchanged where the user can follow it.
|
|
16
|
+
*/
|
|
17
|
+
function screenWeb(visible) {
|
|
18
|
+
const plain = (name, options) => {
|
|
19
|
+
if (options?.near !== undefined) throw refused('web.' + name + ' {near} works in the background browser only; on screen use {nth} or {role}.');
|
|
20
|
+
};
|
|
21
|
+
const backgroundOnly = name => () => {
|
|
22
|
+
throw refused('web.' + name + ' works in the background browser only. On screen, read the page with web.read() or web.text(), or run this part with --mode background.');
|
|
23
|
+
};
|
|
24
|
+
const web = {
|
|
25
|
+
open: url => visible.open(url),
|
|
26
|
+
read: () => visible.read(),
|
|
27
|
+
text: async target => {
|
|
28
|
+
if (target !== undefined) backgroundOnly('text(target)')();
|
|
29
|
+
return (await visible.read()).text;
|
|
30
|
+
},
|
|
31
|
+
fill: (target, value, options) => { plain('fill', options); return visible.type(target, String(value), { replace: true }); },
|
|
32
|
+
type: (target, text, options = {}) => { plain('type', options); return visible.type(target, text, { multiline: options.multiline, at: options.at }); },
|
|
33
|
+
click: (target, options = {}) => { plain('click', options); return visible.click(target, { role: options.role, nth: options.nth, expectText: options.expectText }); },
|
|
34
|
+
select: (target, ...choices) => {
|
|
35
|
+
if (choices.length !== 1) throw refused('On screen web.select picks one option at a time.');
|
|
36
|
+
return visible.select(target, choices[0]);
|
|
37
|
+
},
|
|
38
|
+
check: (target, options) => { plain('check', options); return visible.choose(target); },
|
|
39
|
+
uncheck: (target, options) => { plain('uncheck', options); return visible.choose(target, { off: true }); },
|
|
40
|
+
press: key => visible.press(key),
|
|
41
|
+
waitText: (text, timeout) => visible.waitText(text, timeout),
|
|
42
|
+
waitFor: (target, options = {}) => visible.waitFor(target, { timeout: options.timeout }),
|
|
43
|
+
waitIdle: options => visible.waitIdle(options),
|
|
44
|
+
has: target => visible.has(target),
|
|
45
|
+
url: async () => (await visible.read()).url,
|
|
46
|
+
title: async () => (await visible.read()).title,
|
|
47
|
+
sleep: ms => delay(ms),
|
|
48
|
+
};
|
|
49
|
+
for (const name of BACKGROUND_ONLY) web[name] = backgroundOnly(name);
|
|
50
|
+
return web;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = { screenWeb, BACKGROUND_ONLY };
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { setTimeout: delay } = require('node:timers/promises');
|
|
4
|
+
const { waitArgs } = require('./script-wait');
|
|
5
|
+
|
|
6
|
+
const TICKS = ['radiobutton', 'checkbox', 'switch'];
|
|
7
|
+
const CONFIRM_MS = 2500;
|
|
8
|
+
const MAX_READ_MS = 12000;
|
|
9
|
+
const VIEW_LIMIT = 6000;
|
|
10
|
+
const REBIND = /navigated|Read the selected page again|no longer selected/i;
|
|
11
|
+
const OPEN_WAIT_MS = 15000;
|
|
12
|
+
const TEXT_WAIT_MS = 10000;
|
|
13
|
+
|
|
14
|
+
/** Only web addresses are opened, so a script cannot start a program through the browser's command line. */
|
|
15
|
+
function checkedUrl(url) {
|
|
16
|
+
let parsed;
|
|
17
|
+
try { parsed = new URL(String(url)); } catch { parsed = undefined; }
|
|
18
|
+
if (!parsed || !['http:', 'https:'].includes(parsed.protocol) || /["\s]/.test(String(url))) {
|
|
19
|
+
throw Object.assign(new Error('visible.open takes an http or https address.'), { code: 'INVALID_ARGS' });
|
|
20
|
+
}
|
|
21
|
+
return parsed.href;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The tab opened for an address is the one that was not there before and shows the same site. Two pages of one site
|
|
26
|
+
* that differ only in an order number or a query look alike, so the address alone never picks the tab.
|
|
27
|
+
*/
|
|
28
|
+
function openedTab(page, known, asked) {
|
|
29
|
+
if (!page.instance || known.has(page.instance)) return false;
|
|
30
|
+
try { return new URL(page.url).host === new URL(asked).host; } catch { return false; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Opens an address in a new tab of the user's Chrome; Chrome starts if it is not running. The address travels in an
|
|
35
|
+
* environment variable, so no shell ever parses it. The starter is not detached: started detached, Start-Process
|
|
36
|
+
* returned 0 and Chrome opened nothing (measured on Windows 11 26200 with Chrome running and with it closed).
|
|
37
|
+
*/
|
|
38
|
+
function openInChrome(address) {
|
|
39
|
+
const { spawn } = require('node:child_process');
|
|
40
|
+
spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', 'Start-Process chrome -ArgumentList $env:AGENT_DESKTOP_OPEN_URL'],
|
|
41
|
+
{ windowsHide: true, stdio: 'ignore', env: { ...process.env, AGENT_DESKTOP_OPEN_URL: address } }).on('error', () => {});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** How long a person takes to read `text`: Chinese by the character, other text by the word. */
|
|
45
|
+
function readingMs(text, random = Math.random) {
|
|
46
|
+
const value = String(text ?? '');
|
|
47
|
+
const han = (value.match(/[㐀-鿿]/g) ?? []).length;
|
|
48
|
+
const words = (value.replace(/[㐀-鿿]/g, ' ').match(/[\p{L}\p{N}]+/gu) ?? []).length;
|
|
49
|
+
if (!han && !words) return 0;
|
|
50
|
+
return Math.round(Math.min(350 + han * 130 + words * 250, MAX_READ_MS) * (0.85 + 0.3 * random()));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Helpers for the page in the browser window the user can see, acted on with the real mouse and
|
|
55
|
+
* keyboard. One helper is one thing a person does: tick a choice, type into a field, scroll until a
|
|
56
|
+
* text shows. `pace()` is the human pace the script asked for, if any. Every command is marked
|
|
57
|
+
* `visible`, so none of them is handed to a background browser connection.
|
|
58
|
+
*/
|
|
59
|
+
function createVisible({ flow, step, warn, pace, takeInput = () => {}, pressKey, openUrl = openInChrome }) {
|
|
60
|
+
let handle, windowId;
|
|
61
|
+
const human = () => ({ visible: true, ...(pace() ? { human: pace() } : {}) });
|
|
62
|
+
|
|
63
|
+
async function bind(window = windowId) {
|
|
64
|
+
const page = await flow('current', { visible: true, ...(window ? { window } : {}) });
|
|
65
|
+
handle = page.page;
|
|
66
|
+
windowId = page.window;
|
|
67
|
+
return page;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A page that changed since it was bound is bound again, as long as nothing was sent yet. */
|
|
71
|
+
async function on(run) {
|
|
72
|
+
if (!handle) await bind();
|
|
73
|
+
try { return await run(handle); } catch (err) {
|
|
74
|
+
if (err.disposition || !REBIND.test(err.message)) throw err;
|
|
75
|
+
await bind();
|
|
76
|
+
return run(handle);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* A control further down or up the page is scrolled to with the wheel, the way a person gets to it,
|
|
82
|
+
* and the action is tried once more. Nothing was sent when a control is reported as not on screen.
|
|
83
|
+
*/
|
|
84
|
+
async function reaching(name, run) {
|
|
85
|
+
try { return await on(run); } catch (err) {
|
|
86
|
+
if (err.code !== 'NOT_ON_SCREEN') throw err;
|
|
87
|
+
}
|
|
88
|
+
for (const lines of ['4', '-4']) {
|
|
89
|
+
const report = await on(page => flow('wheel', { page, until: name, lines, ...human() }));
|
|
90
|
+
if (report.verified) return on(run);
|
|
91
|
+
}
|
|
92
|
+
throw Object.assign(new Error('"' + name + '" is on the page, but scrolling did not bring it onto the screen.'), { code: 'ELEMENT_NOT_FOUND' });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const shown = page => ({ title: page.title, url: page.url, text: page.text,
|
|
96
|
+
controls: page.controls.map(({ role, name, checked }) => ({ role, name, ...(checked ? { checked } : {}) })) });
|
|
97
|
+
|
|
98
|
+
const visible = {
|
|
99
|
+
use: window => step('visible.use', window ?? '', async () => shown(await bind(window))),
|
|
100
|
+
read: () => step('visible.read', '', async () => shown(await bind())),
|
|
101
|
+
click: (name, { role, nth, expectText } = {}) => step('visible.click', name, async () => {
|
|
102
|
+
takeInput('visible.click');
|
|
103
|
+
return reaching(name, page => flow('click',
|
|
104
|
+
{ page, on: name, role, nth: nth === undefined ? undefined : String(nth), 'expect-text': expectText, ...human() }));
|
|
105
|
+
}),
|
|
106
|
+
hover: (name, { role, nth } = {}) => step('visible.hover', name, async () => {
|
|
107
|
+
takeInput('visible.hover');
|
|
108
|
+
return reaching(name, page => flow('point', { page, on: name, role, nth: nth === undefined ? undefined : String(nth), ...human() }));
|
|
109
|
+
}),
|
|
110
|
+
choose: (name, { off = false } = {}) => step('visible.choose', name, async () => {
|
|
111
|
+
const find = page => page.controls.filter(control => control.name === name && TICKS.includes(control.role));
|
|
112
|
+
const boxes = find(await bind());
|
|
113
|
+
if (boxes.length !== 1) {
|
|
114
|
+
throw Object.assign(new Error((boxes.length ? boxes.length + ' choices are' : 'No radio button or checkbox is') + ' named "' + name + '" on this page.'),
|
|
115
|
+
{ code: boxes.length ? 'AMBIGUOUS_TARGET' : 'ELEMENT_NOT_FOUND' });
|
|
116
|
+
}
|
|
117
|
+
const wanted = !off;
|
|
118
|
+
if (off && boxes[0].role === 'radiobutton') throw Object.assign(new Error('A radio button is cleared by choosing another one.'), { code: 'INVALID_ARGS' });
|
|
119
|
+
if (Boolean(boxes[0].checked) === wanted) return { changed: false, checked: wanted };
|
|
120
|
+
takeInput('visible.choose');
|
|
121
|
+
await reaching(name, page => flow('click', { page, on: name, role: boxes[0].role, ...human() }));
|
|
122
|
+
const until = Date.now() + CONFIRM_MS;
|
|
123
|
+
let seen = 0;
|
|
124
|
+
for (;;) {
|
|
125
|
+
const now = find(await bind());
|
|
126
|
+
seen += now.length;
|
|
127
|
+
if (now.length === 1 && Boolean(now[0].checked) === wanted) return { changed: true, checked: wanted };
|
|
128
|
+
if (Date.now() >= until) break;
|
|
129
|
+
await delay(150);
|
|
130
|
+
}
|
|
131
|
+
if (!seen) return { changed: true, checked: null, gone: true };
|
|
132
|
+
warn('visible.choose "' + name + '" was clicked, but the page does not show it as ' + (wanted ? 'selected' : 'cleared') + '.');
|
|
133
|
+
return { changed: false, checked: !wanted };
|
|
134
|
+
}),
|
|
135
|
+
type: (field, text, { multiline, replace, at } = {}) => step('visible.type', field, async () => {
|
|
136
|
+
takeInput('visible.type');
|
|
137
|
+
const report = await on(page => flow('type', { page, field, value: String(text), multiline: multiline || undefined, replace: replace || undefined, at, ...human() }));
|
|
138
|
+
if (!report.verified) warn('visible.type "' + field + '" sent the keys, but the field does not show the text. ' + (report.message ?? ''));
|
|
139
|
+
return report.verified;
|
|
140
|
+
}),
|
|
141
|
+
scrollTo: (text, { over, lines } = {}) => step('visible.scrollTo', text, async () => {
|
|
142
|
+
takeInput('visible.scrollTo');
|
|
143
|
+
const report = await on(page => flow('wheel', { page, over, until: String(text), lines: lines === undefined ? undefined : String(lines), ...human() }));
|
|
144
|
+
if (!report.verified) throw Object.assign(new Error('"' + text + '" did not come into view. ' + (report.message ?? '')), { code: 'ELEMENT_NOT_FOUND' });
|
|
145
|
+
return true;
|
|
146
|
+
}),
|
|
147
|
+
scroll: (lines = 3, { over } = {}) => step('visible.scroll', lines, async () => {
|
|
148
|
+
takeInput('visible.scroll');
|
|
149
|
+
const report = await on(page => flow('wheel', { page, over, lines: String(lines), ...human() }));
|
|
150
|
+
return Boolean(report.verified);
|
|
151
|
+
}),
|
|
152
|
+
open: url => step('visible.open', url, async () => {
|
|
153
|
+
const address = checkedUrl(url);
|
|
154
|
+
takeInput('visible.open');
|
|
155
|
+
let known = new Set();
|
|
156
|
+
try { known = new Set((await bind()).instances ?? []); } catch { /* No Chrome window is open yet. */ }
|
|
157
|
+
openUrl(address);
|
|
158
|
+
const until = Date.now() + OPEN_WAIT_MS;
|
|
159
|
+
for (;;) {
|
|
160
|
+
try {
|
|
161
|
+
const page = await bind(null);
|
|
162
|
+
if (openedTab(page, known, address)) return shown(page);
|
|
163
|
+
} catch { /* The new tab may not be readable yet. */ }
|
|
164
|
+
if (Date.now() >= until) throw Object.assign(new Error('Chrome did not show ' + address + ' within ' + OPEN_WAIT_MS / 1000 + ' s.'),
|
|
165
|
+
{ code: 'TIMEOUT', suggestion: 'Bring Chrome forward and check whether the requested tab opened before opening it again.' });
|
|
166
|
+
await delay(250);
|
|
167
|
+
}
|
|
168
|
+
}),
|
|
169
|
+
select: (field, value) => step('visible.select', field, async () => {
|
|
170
|
+
takeInput('visible.select');
|
|
171
|
+
return on(page => flow('choose', { page, field, value: String(value) }));
|
|
172
|
+
}),
|
|
173
|
+
press: key => step('visible.press', key, async () => {
|
|
174
|
+
if (!pressKey) throw new Error('visible.press is not available here.');
|
|
175
|
+
takeInput('visible.press');
|
|
176
|
+
if (!windowId) await bind();
|
|
177
|
+
await pressKey(windowId, String(key));
|
|
178
|
+
return true;
|
|
179
|
+
}),
|
|
180
|
+
waitText: (text, limit) => step('visible.waitText', text, async () => {
|
|
181
|
+
const { timeout } = waitArgs(limit, {}, TEXT_WAIT_MS);
|
|
182
|
+
const until = Date.now() + timeout;
|
|
183
|
+
const texts = (Array.isArray(text) ? text : [text]).map(String);
|
|
184
|
+
for (;;) {
|
|
185
|
+
const page = await bind();
|
|
186
|
+
const line = [...page.text.split('\n'), ...page.controls.map(c => c.name)].find(l => texts.some(one => l.includes(one)));
|
|
187
|
+
if (line) return line;
|
|
188
|
+
if (Date.now() >= until) throw Object.assign(new Error(texts.map(one => '"' + one + '"').join(' or ') + ' did not show on the screen page within ' + timeout + ' ms.'), { code: 'TIMEOUT' });
|
|
189
|
+
await delay(300);
|
|
190
|
+
}
|
|
191
|
+
}),
|
|
192
|
+
waitFor: (name, { timeout = TEXT_WAIT_MS } = {}) => step('visible.waitFor', name, async () => {
|
|
193
|
+
const until = Date.now() + timeout;
|
|
194
|
+
for (;;) {
|
|
195
|
+
const page = await bind();
|
|
196
|
+
if (page.controls.some(c => c.name === name)) return true;
|
|
197
|
+
if (Date.now() >= until) throw Object.assign(new Error('"' + name + '" did not show on the screen page within ' + timeout + ' ms.'), { code: 'TIMEOUT' });
|
|
198
|
+
await delay(300);
|
|
199
|
+
}
|
|
200
|
+
}),
|
|
201
|
+
waitIdle: ({ timeout = TEXT_WAIT_MS, quiet = 600 } = {}) => step('visible.waitIdle', '', async () => {
|
|
202
|
+
const until = Date.now() + timeout;
|
|
203
|
+
let last, since = Date.now();
|
|
204
|
+
for (;;) {
|
|
205
|
+
const page = shown(await bind());
|
|
206
|
+
const now = JSON.stringify(page);
|
|
207
|
+
if (now !== last) { last = now; since = Date.now(); }
|
|
208
|
+
else if (Date.now() - since >= quiet) return page;
|
|
209
|
+
if (Date.now() >= until) { warn('visible.waitIdle: the screen page was still changing after ' + timeout + ' ms.'); return page; }
|
|
210
|
+
await delay(200);
|
|
211
|
+
}
|
|
212
|
+
}),
|
|
213
|
+
has: name => step('visible.has', name, async () => {
|
|
214
|
+
const page = await bind();
|
|
215
|
+
return page.controls.some(c => c.name === name) || page.text.includes(name);
|
|
216
|
+
}),
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
async function scene() {
|
|
220
|
+
const page = shown(await bind());
|
|
221
|
+
const view = [page.text, ...page.controls.map(control => '- ' + control.role + ' "' + control.name + '"' + (control.checked ? ' [checked]' : ''))].join('\n');
|
|
222
|
+
return { surface: 'visible', url: page.url, title: page.title, view: view.length > VIEW_LIMIT ? view.slice(0, VIEW_LIMIT) + '\n… (cut)' : view };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return { visible, scene };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
module.exports = { createVisible, readingMs };
|