@lynx-js/devtool-connector 0.9.5 → 0.13.1

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.
Files changed (49) hide show
  1. package/LICENSE +1 -1
  2. package/dist/346.js +635 -0
  3. package/dist/390.js +262 -35
  4. package/dist/556.js +9 -4
  5. package/dist/61.js +3432 -0
  6. package/dist/63.js +112 -30
  7. package/dist/712.js +28 -2
  8. package/dist/872.js +552 -122
  9. package/dist/962.js +25 -17
  10. package/dist/client-discovery-errors.d.ts +1 -0
  11. package/dist/client-id.d.ts +9 -2
  12. package/dist/command/client.d.ts +28 -0
  13. package/dist/command/contract.d.ts +255 -0
  14. package/dist/command/core.d.ts +32 -0
  15. package/dist/command/index.d.ts +20 -0
  16. package/dist/command/index.js +224 -0
  17. package/dist/command/query.d.ts +5 -0
  18. package/dist/command/reactlynx/controller.d.ts +71 -0
  19. package/dist/command/reactlynx/model.d.ts +48 -0
  20. package/dist/command/reactlynx/protocol.d.ts +40 -0
  21. package/dist/command/reactlynx/session.d.ts +43 -0
  22. package/dist/command/reactlynx/types.d.ts +73 -0
  23. package/dist/command/ref-actions.d.ts +17 -0
  24. package/dist/command/result.d.ts +29 -0
  25. package/dist/command/screenshot-annotation.d.ts +22 -0
  26. package/dist/command/screenshot.d.ts +28 -0
  27. package/dist/command/snapshot.d.ts +79 -0
  28. package/dist/command/targets.d.ts +15 -0
  29. package/dist/daemon/device-connection.d.ts +3 -1
  30. package/dist/daemon/entry.js +11 -0
  31. package/dist/daemon/index.d.ts +1 -0
  32. package/dist/daemon/index.js +3 -0
  33. package/dist/daemon/manager.d.ts +11 -9
  34. package/dist/daemon/protocol.d.ts +24 -3
  35. package/dist/daemon/server.d.ts +1 -0
  36. package/dist/index.d.ts +6 -2
  37. package/dist/index.js +2 -454
  38. package/dist/streams/customized.d.ts +2 -1
  39. package/dist/transport/android.d.ts +1 -1
  40. package/dist/transport/desktop.d.ts +1 -1
  41. package/dist/transport/index.js +2 -2
  42. package/dist/transport/ios.d.ts +1 -1
  43. package/dist/transport/transport.d.ts +7 -1
  44. package/dist/transport/ws-stream.d.ts +9 -0
  45. package/dist/types.d.ts +35 -0
  46. package/package.json +10 -2
  47. package/dist/187.js +0 -272
  48. package/dist/43.js +0 -20
  49. package/dist/677.js +0 -19
package/dist/61.js ADDED
@@ -0,0 +1,3432 @@
1
+ import { setTimeout as promises_setTimeout } from "node:timers/promises";
2
+ import { ReadableStream } from "node:stream/web";
3
+ import { createDebug } from "obug";
4
+ import * as __rspack_external_jpeg_js_11f36cdf from "jpeg-js";
5
+ const DevNodeType = {
6
+ Group: 0,
7
+ Element: 1,
8
+ ClassComponent: 2,
9
+ FunctionComponent: 3,
10
+ ForwardRef: 4,
11
+ Memo: 5,
12
+ Suspense: 6,
13
+ Context: 7,
14
+ Consumer: 8,
15
+ Portal: 9
16
+ };
17
+ const MsgType = {
18
+ ADD_ROOT: 1,
19
+ ADD_VNODE: 2,
20
+ REMOVE_VNODE: 3,
21
+ UPDATE_VNODE_TIMINGS: 4,
22
+ REORDER_CHILDREN: 5,
23
+ RENDER_REASON: 6,
24
+ COMMIT_STATS: 7,
25
+ HOC_NODES: 8
26
+ };
27
+ const COMMIT_STATS_VALUE_COUNT = 74;
28
+ function createRendererState() {
29
+ return {
30
+ tree: new Map(),
31
+ roots: []
32
+ };
33
+ }
34
+ function parseStringTable(slice) {
35
+ const len = slice[0];
36
+ const strings = [];
37
+ if (len > 0) for(let i = 1; i < len; i++){
38
+ const strLen = slice[i];
39
+ let start = i + 1;
40
+ const end = i + strLen + 1;
41
+ let str = '';
42
+ for(; start < end; start++){
43
+ const code = slice[start];
44
+ if ('number' == typeof code && code >= 0 && code <= 0x10ffff) str += String.fromCodePoint(code);
45
+ else str += '?';
46
+ }
47
+ strings.push(str);
48
+ i += strLen;
49
+ }
50
+ return strings;
51
+ }
52
+ function applyOperationV2(state, ops) {
53
+ const { tree, roots } = state;
54
+ let i = ops[1] + 1;
55
+ const strings = parseStringTable(ops.slice(1, i + 1));
56
+ for(i += 1; i < ops.length; i++)switch(ops[i]){
57
+ case MsgType.ADD_ROOT:
58
+ {
59
+ const rootId = ops[i + 1];
60
+ if (!roots.includes(rootId)) roots.push(rootId);
61
+ i += 1;
62
+ break;
63
+ }
64
+ case MsgType.ADD_VNODE:
65
+ {
66
+ const id = ops[i + 1];
67
+ const type = ops[i + 2];
68
+ const parentId = ops[i + 3];
69
+ const owner = ops[i + 4];
70
+ const nameId = ops[i + 5];
71
+ const keyId = ops[i + 6];
72
+ const startTime = ops[i + 7] / 1000;
73
+ const endTime = ops[i + 8] / 1000;
74
+ const parent = tree.get(parentId);
75
+ if (parent) parent.children.push(id);
76
+ tree.set(id, {
77
+ id,
78
+ type,
79
+ name: strings[nameId - 1] ?? '',
80
+ key: keyId > 0 ? strings[keyId - 1] ?? '' : '',
81
+ parent: parentId,
82
+ owner,
83
+ children: [],
84
+ startTime,
85
+ endTime
86
+ });
87
+ i += 8;
88
+ break;
89
+ }
90
+ case MsgType.UPDATE_VNODE_TIMINGS:
91
+ {
92
+ const id = ops[i + 1];
93
+ const node = tree.get(id);
94
+ if (node) {
95
+ node.startTime = ops[i + 2] / 1000;
96
+ node.endTime = ops[i + 3] / 1000;
97
+ }
98
+ i += 3;
99
+ break;
100
+ }
101
+ case MsgType.REMOVE_VNODE:
102
+ {
103
+ const unmounts = ops[i + 1];
104
+ i += 2;
105
+ const len = i + unmounts;
106
+ for(; i < len; i++){
107
+ const nodeId = ops[i];
108
+ const node = tree.get(nodeId);
109
+ if (!node) continue;
110
+ const parent = tree.get(node.parent);
111
+ if (parent) {
112
+ const index = parent.children.indexOf(nodeId);
113
+ if (index > -1) parent.children.splice(index, 1);
114
+ }
115
+ const stack = [
116
+ nodeId
117
+ ];
118
+ while(stack.length > 0){
119
+ const current = stack.pop();
120
+ const currentNode = tree.get(current);
121
+ if (!currentNode) continue;
122
+ tree.delete(current);
123
+ stack.push(...currentNode.children);
124
+ }
125
+ const rootIndex = roots.indexOf(nodeId);
126
+ if (rootIndex > -1) roots.splice(rootIndex, 1);
127
+ }
128
+ if (len > 0) i--;
129
+ break;
130
+ }
131
+ case MsgType.REORDER_CHILDREN:
132
+ {
133
+ const parentId = ops[i + 1];
134
+ const count = ops[i + 2];
135
+ const node = tree.get(parentId);
136
+ if (node) node.children = ops.slice(i + 3, i + 3 + count);
137
+ i = i + 2 + count;
138
+ break;
139
+ }
140
+ case MsgType.RENDER_REASON:
141
+ {
142
+ const count = ops[i + 3];
143
+ i = i + 3 + count;
144
+ break;
145
+ }
146
+ case MsgType.COMMIT_STATS:
147
+ {
148
+ const lastStatsIndex = i + COMMIT_STATS_VALUE_COUNT;
149
+ if (lastStatsIndex >= ops.length) throw new Error(`Malformed operation_v2 commit-stats at index ${i}: expected ${COMMIT_STATS_VALUE_COUNT} values`);
150
+ i = lastStatsIndex;
151
+ break;
152
+ }
153
+ case MsgType.HOC_NODES:
154
+ {
155
+ const count = ops[i + 2];
156
+ i = i + 2 + count;
157
+ break;
158
+ }
159
+ default:
160
+ throw new Error(`Unknown operation_v2 op ${ops[i]} at index ${i}`);
161
+ }
162
+ }
163
+ function applyRootOrder(state, rootOrder) {
164
+ state.roots = [
165
+ ...rootOrder
166
+ ];
167
+ }
168
+ function typeTag(type) {
169
+ switch(type){
170
+ case DevNodeType.FunctionComponent:
171
+ return 'fn';
172
+ case DevNodeType.ClassComponent:
173
+ return 'cls';
174
+ case DevNodeType.ForwardRef:
175
+ return 'fRef';
176
+ case DevNodeType.Memo:
177
+ return 'memo';
178
+ case DevNodeType.Suspense:
179
+ return 'susp';
180
+ case DevNodeType.Context:
181
+ return 'ctx';
182
+ case DevNodeType.Consumer:
183
+ return 'cons';
184
+ case DevNodeType.Portal:
185
+ return 'portal';
186
+ case DevNodeType.Element:
187
+ return 'host';
188
+ case DevNodeType.Group:
189
+ return 'group';
190
+ default:
191
+ return '?';
192
+ }
193
+ }
194
+ const SHELL_NAMES = new Set([
195
+ 'Fragment',
196
+ 'Root',
197
+ 'Anonymous'
198
+ ]);
199
+ const PIPE = '│ ';
200
+ const TEE = '├─ ';
201
+ const ELBOW = '└─ ';
202
+ const SPACE = ' ';
203
+ function isShell(node) {
204
+ return SHELL_NAMES.has(node.name);
205
+ }
206
+ function visibleChildren(context, node) {
207
+ const output = [];
208
+ for (const childId of node.children){
209
+ const child = context.state.tree.get(childId);
210
+ if (child) if (context.hideShells && isShell(child)) output.push(...visibleChildren(context, child));
211
+ else output.push(child);
212
+ }
213
+ return output;
214
+ }
215
+ function formatRef(context, node) {
216
+ const label = context.labelOf.get(node.id) ?? '@c?';
217
+ const key = node.key ? ` key=${node.key}` : '';
218
+ return `${label} [${typeTag(node.type)}] ${node.name}${key}`;
219
+ }
220
+ function walk(context, node, prefix, isLast, isRoot, depth) {
221
+ const connector = isRoot ? '' : isLast ? ELBOW : TEE;
222
+ context.lines.push(`${prefix}${connector}${formatRef(context, node)}`);
223
+ if (depth >= context.maxDepth) return;
224
+ const children = visibleChildren(context, node);
225
+ const childPrefix = isRoot ? '' : prefix + (isLast ? SPACE : PIPE);
226
+ children.forEach((child, index)=>{
227
+ walk(context, child, childPrefix, index === children.length - 1, false, depth + 1);
228
+ });
229
+ }
230
+ function formatReactLynxTree(state, options = {}) {
231
+ const context = {
232
+ state,
233
+ labels: [],
234
+ labelOf: new Map(),
235
+ maxDepth: options.maxDepth ?? 1 / 0,
236
+ lines: [],
237
+ hideShells: options.hideShells ?? true
238
+ };
239
+ const visibleRoots = [];
240
+ for (const rootId of state.roots){
241
+ const root = state.tree.get(rootId);
242
+ if (root) if (context.hideShells && isShell(root)) visibleRoots.push(...visibleChildren(context, root));
243
+ else visibleRoots.push(root);
244
+ }
245
+ const assign = (node, depth)=>{
246
+ context.labels.push(node.id);
247
+ context.labelOf.set(node.id, `@c${context.labels.length}`);
248
+ if (depth >= context.maxDepth) return;
249
+ for (const child of visibleChildren(context, node))assign(child, depth + 1);
250
+ };
251
+ for (const root of visibleRoots)assign(root, 1);
252
+ visibleRoots.forEach((root, index)=>{
253
+ walk(context, root, '', index === visibleRoots.length - 1, true, 1);
254
+ });
255
+ return {
256
+ text: context.lines.join('\n'),
257
+ labels: context.labels
258
+ };
259
+ }
260
+ function serializeRendererState(state) {
261
+ return {
262
+ roots: [
263
+ ...state.roots
264
+ ],
265
+ nodes: [
266
+ ...state.tree.values()
267
+ ].map((node)=>({
268
+ ...node,
269
+ children: [
270
+ ...node.children
271
+ ]
272
+ }))
273
+ };
274
+ }
275
+ function deserializeRendererState(value) {
276
+ return {
277
+ roots: [
278
+ ...value.roots
279
+ ],
280
+ tree: new Map(value.nodes.map((node)=>[
281
+ node.id,
282
+ {
283
+ ...node,
284
+ children: [
285
+ ...node.children
286
+ ]
287
+ }
288
+ ]))
289
+ };
290
+ }
291
+ function buildSubstringMatcher(pattern) {
292
+ const needle = pattern.toLowerCase();
293
+ return (name)=>name.toLowerCase().includes(needle);
294
+ }
295
+ function buildRegexMatcher(pattern) {
296
+ let expression;
297
+ try {
298
+ expression = new RegExp(pattern);
299
+ } catch (error) {
300
+ throw new Error(`--regex pattern is invalid: ${error instanceof Error ? error.message : String(error)}`, {
301
+ cause: error
302
+ });
303
+ }
304
+ return (name)=>expression.test(name);
305
+ }
306
+ function findReactLynxComponents(state, matcher, options) {
307
+ const formatted = options.formatted ?? formatReactLynxTree(state, {
308
+ hideShells: options.hideShells
309
+ });
310
+ const idToLabel = new Map();
311
+ formatted.labels.forEach((id, index)=>{
312
+ idToLabel.set(id, `@c${index + 1}`);
313
+ });
314
+ const matches = [];
315
+ for (const id of formatted.labels){
316
+ const node = state.tree.get(id);
317
+ if (!node || !matcher(node.name)) continue;
318
+ const ancestors = [];
319
+ let cursorId = node.parent;
320
+ while(-1 !== cursorId){
321
+ const cursor = state.tree.get(cursorId);
322
+ if (!cursor) break;
323
+ const label = idToLabel.get(cursorId);
324
+ if (label) ancestors.unshift({
325
+ label,
326
+ name: cursor.name
327
+ });
328
+ cursorId = cursor.parent;
329
+ }
330
+ matches.push({
331
+ label: idToLabel.get(id) ?? '@c?',
332
+ id: node.id,
333
+ name: node.name,
334
+ type: node.type,
335
+ key: node.key,
336
+ ancestors
337
+ });
338
+ if (matches.length >= options.limit) break;
339
+ }
340
+ return matches;
341
+ }
342
+ function parseReactLynxComponentRef(ref) {
343
+ const labelMatch = /^@c(\d+)$/u.exec(ref);
344
+ if (labelMatch) {
345
+ const index = Number.parseInt(labelMatch[1], 10);
346
+ if (!Number.isFinite(index) || index < 1) throw new Error(`Invalid label ${ref}; expected @c1, @c2, ...`);
347
+ return {
348
+ kind: 'label',
349
+ index
350
+ };
351
+ }
352
+ const numeric = Number.parseInt(ref, 10);
353
+ if (!Number.isFinite(numeric) || String(numeric) !== ref.trim()) throw new Error(`Invalid <ref> ${JSON.stringify(ref)}; expected @cN or a numeric id.`);
354
+ return {
355
+ kind: 'id',
356
+ id: numeric
357
+ };
358
+ }
359
+ function parseReactLynxLinkRef(ref) {
360
+ const trimmed = ref.trim();
361
+ const elementMatch = /^@?e(\d+)$/u.exec(trimmed);
362
+ if (elementMatch) {
363
+ const index = Number.parseInt(elementMatch[1], 10);
364
+ if (!Number.isFinite(index) || index < 1) throw new Error(`Invalid element ref ${ref}; expected @e1, @e2, ...`);
365
+ return {
366
+ kind: 'element',
367
+ ref: `@e${index}`
368
+ };
369
+ }
370
+ const component = parseReactLynxComponentRef(trimmed);
371
+ return 'label' === component.kind ? {
372
+ kind: 'component-label',
373
+ index: component.index
374
+ } : {
375
+ kind: 'component-id',
376
+ id: component.id
377
+ };
378
+ }
379
+ function buildReactLynxUpdatePath(userPath) {
380
+ if (0 === userPath.length) throw new Error('<path> must not be empty. Use dot notation, e.g. `count`, `user.name`, `items.0.title`.');
381
+ for (const prefix of [
382
+ 'root.',
383
+ 'props.',
384
+ 'state.',
385
+ 'context.'
386
+ ])if (userPath.startsWith(prefix)) throw new Error(`<path> ${JSON.stringify(userPath)} must not start with \`${prefix}\`. The CLI prepends \`root.\` automatically; pass paths starting at the field name, e.g. \`count\`.`);
387
+ if (userPath.split('.').some((segment)=>0 === segment.length)) throw new Error(`<path> ${JSON.stringify(userPath)} contains an empty segment. Dot notation must look like \`a.b.c\`, not \`a..b\` or \`.a\`.`);
388
+ return `root.${userPath}`;
389
+ }
390
+ function _ts_add_disposable_resource(env, value, async) {
391
+ if (null != value) {
392
+ if ("object" != typeof value && "function" != typeof value) throw new TypeError("Object expected.");
393
+ var dispose, inner;
394
+ if (async) {
395
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
396
+ dispose = value[Symbol.asyncDispose];
397
+ }
398
+ if (void 0 === dispose) {
399
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
400
+ dispose = value[Symbol.dispose];
401
+ if (async) inner = dispose;
402
+ }
403
+ if ("function" != typeof dispose) throw new TypeError("Object not disposable.");
404
+ if (inner) dispose = function() {
405
+ try {
406
+ inner.call(this);
407
+ } catch (e) {
408
+ return Promise.reject(e);
409
+ }
410
+ };
411
+ env.stack.push({
412
+ value: value,
413
+ dispose: dispose,
414
+ async: async
415
+ });
416
+ } else if (async) env.stack.push({
417
+ async: true
418
+ });
419
+ return value;
420
+ }
421
+ function session_ts_dispose_resources(env) {
422
+ var _SuppressedError = "function" == typeof SuppressedError ? SuppressedError : function(error, suppressed, message) {
423
+ var e = new Error(message);
424
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
425
+ };
426
+ return (session_ts_dispose_resources = function(env) {
427
+ function fail(e) {
428
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
429
+ env.hasError = true;
430
+ }
431
+ var r, s = 0;
432
+ function next() {
433
+ while(r = env.stack.pop())try {
434
+ if (!r.async && 1 === s) return s = 0, env.stack.push(r), Promise.resolve().then(next);
435
+ if (r.dispose) {
436
+ var result = r.dispose.call(r.value);
437
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
438
+ fail(e);
439
+ return next();
440
+ });
441
+ } else s |= 1;
442
+ } catch (e) {
443
+ fail(e);
444
+ }
445
+ if (1 === s) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
446
+ if (env.hasError) throw env.error;
447
+ }
448
+ return next();
449
+ })(env);
450
+ }
451
+ const debug = createDebug('devtool-mcp-server:reactlynx');
452
+ const PREACT_EVENT = 'PreactDevtools';
453
+ const SOURCE_PAGE_HOOK = 'preact-page-hook';
454
+ const SOURCE_DEVTOOLS_TO_CLIENT = 'preact-devtools-to-client';
455
+ const DEFAULT_REACTLYNX_IDLE_MS = 700;
456
+ const DEFAULT_REACTLYNX_MAX_MS = 5000;
457
+ function buildReactLynxOutboundFrame(type, data) {
458
+ return {
459
+ method: 'Lynx.sendVMEvent',
460
+ params: {
461
+ vmType: 'JSContext',
462
+ event: PREACT_EVENT,
463
+ data: JSON.stringify({
464
+ source: SOURCE_DEVTOOLS_TO_CLIENT,
465
+ type,
466
+ data: data ?? null
467
+ })
468
+ }
469
+ };
470
+ }
471
+ async function raceRead(read, timeoutMs) {
472
+ let timer;
473
+ const timeout = new Promise((resolve)=>{
474
+ timer = setTimeout(resolve, timeoutMs, 'timeout');
475
+ timer.unref();
476
+ });
477
+ try {
478
+ return await Promise.race([
479
+ read,
480
+ timeout
481
+ ]);
482
+ } finally{
483
+ if (void 0 !== timer) clearTimeout(timer);
484
+ }
485
+ }
486
+ async function* readUntilIdle(stream, options) {
487
+ const reader = stream.getReader();
488
+ const startedAt = Date.now();
489
+ let terminated = false;
490
+ let pendingRead;
491
+ try {
492
+ for(;;){
493
+ const elapsedMs = Date.now() - startedAt;
494
+ if (elapsedMs >= options.maxMs) {
495
+ await reader.cancel();
496
+ terminated = true;
497
+ return;
498
+ }
499
+ pendingRead ??= reader.read();
500
+ const idleMs = 'function' == typeof options.idleMs ? options.idleMs() : options.idleMs;
501
+ const remainingMs = options.maxMs - elapsedMs;
502
+ const deadlineWins = remainingMs <= idleMs;
503
+ const result = await raceRead(pendingRead, Math.min(idleMs, remainingMs));
504
+ if ('timeout' === result) {
505
+ if (deadlineWins || Date.now() - startedAt >= options.maxMs) {
506
+ await reader.cancel();
507
+ terminated = true;
508
+ return;
509
+ }
510
+ if (options.onIdle?.()) continue;
511
+ await reader.cancel();
512
+ terminated = true;
513
+ return;
514
+ }
515
+ pendingRead = void 0;
516
+ if (result.done) {
517
+ terminated = true;
518
+ return;
519
+ }
520
+ yield result.value;
521
+ }
522
+ } finally{
523
+ if (!terminated) await reader.cancel().catch(()=>{});
524
+ reader.releaseLock();
525
+ }
526
+ }
527
+ async function runReactLynxSession(options) {
528
+ const env = {
529
+ stack: [],
530
+ error: void 0,
531
+ hasError: false
532
+ };
533
+ try {
534
+ const { connector, clientId, sessionId, outbound, sendInit = true, onEnvelope = ()=>'continue', afterSnapshot, awaitEnvelope = false, snapshotIdleMs = DEFAULT_REACTLYNX_IDLE_MS, idleMs = DEFAULT_REACTLYNX_IDLE_MS, maxMs = DEFAULT_REACTLYNX_MAX_MS, signal } = options;
535
+ let stopRequested = false;
536
+ let cancelInput = ()=>{};
537
+ let inputTerminated = false;
538
+ let inputTerminalReason;
539
+ let assertInputWritable = ()=>{
540
+ throw new Error('ReactLynx input stream is not ready');
541
+ };
542
+ let sendInput = ()=>{
543
+ throw new Error('ReactLynx input stream is not ready');
544
+ };
545
+ const input = new ReadableStream({
546
+ start (controller) {
547
+ if (sendInit) controller.enqueue(buildReactLynxOutboundFrame('init'));
548
+ for (const frame of outbound)controller.enqueue(frame);
549
+ assertInputWritable = ()=>{
550
+ if (!inputTerminated) return;
551
+ if (void 0 !== inputTerminalReason) throw inputTerminalReason;
552
+ throw new Error('ReactLynx input stream is no longer writable');
553
+ };
554
+ sendInput = (frame)=>{
555
+ assertInputWritable();
556
+ try {
557
+ controller.enqueue(frame);
558
+ } catch (error) {
559
+ inputTerminated = true;
560
+ inputTerminalReason = error;
561
+ throw error;
562
+ }
563
+ };
564
+ cancelInput = ()=>{
565
+ if (inputTerminated) return;
566
+ inputTerminated = true;
567
+ try {
568
+ controller.close();
569
+ } catch (error) {
570
+ inputTerminalReason = error;
571
+ }
572
+ };
573
+ },
574
+ cancel (reason) {
575
+ inputTerminated = true;
576
+ inputTerminalReason = reason;
577
+ }
578
+ });
579
+ const stream = _ts_add_disposable_resource(env, await connector.sendCDPStream(clientId, sessionId, input, signal ? {
580
+ signal
581
+ } : void 0), true);
582
+ const state = createRendererState();
583
+ let framesSeen = 0;
584
+ let operationFrames = 0;
585
+ let rootOrderFrames = 0;
586
+ const envelopeTypes = new Set();
587
+ let snapshotPending = void 0 !== afterSnapshot;
588
+ try {
589
+ for await (const value of readUntilIdle(stream, {
590
+ idleMs: ()=>snapshotPending ? snapshotIdleMs : idleMs,
591
+ maxMs,
592
+ onIdle: ()=>{
593
+ if (!snapshotPending || !afterSnapshot) return awaitEnvelope;
594
+ snapshotPending = false;
595
+ assertInputWritable();
596
+ const followUp = afterSnapshot(state);
597
+ if (!followUp) {
598
+ stopRequested = true;
599
+ return false;
600
+ }
601
+ sendInput(buildReactLynxOutboundFrame(followUp[0], followUp[1]));
602
+ return true;
603
+ }
604
+ })){
605
+ if ('object' != typeof value || null === value) continue;
606
+ if ('Lynx.onVMEvent' !== value.method) continue;
607
+ const params = value.params ?? {};
608
+ if (params.event !== PREACT_EVENT) continue;
609
+ let envelope;
610
+ try {
611
+ const parsed = JSON.parse(params.data ?? 'null');
612
+ if ('object' != typeof parsed || null === parsed) continue;
613
+ envelope = parsed;
614
+ } catch {
615
+ continue;
616
+ }
617
+ if (envelope.source === SOURCE_PAGE_HOOK) {
618
+ framesSeen += 1;
619
+ envelopeTypes.add(envelope.type);
620
+ debug('frame %d: type=%s dataSize=%s', framesSeen, envelope.type, Array.isArray(envelope.data) ? envelope.data.length : typeof envelope.data);
621
+ if ('operation_v2' === envelope.type && Array.isArray(envelope.data)) {
622
+ operationFrames += 1;
623
+ applyOperationV2(state, envelope.data);
624
+ } else if ('root-order' === envelope.type && Array.isArray(envelope.data)) {
625
+ rootOrderFrames += 1;
626
+ applyRootOrder(state, envelope.data);
627
+ }
628
+ if ('stop' === onEnvelope(envelope)) {
629
+ stopRequested = true;
630
+ break;
631
+ }
632
+ }
633
+ }
634
+ } finally{
635
+ cancelInput();
636
+ }
637
+ debug('session done: stop=%s frames=%d op=%d root=%d types=%o', stopRequested, framesSeen, operationFrames, rootOrderFrames, [
638
+ ...envelopeTypes
639
+ ]);
640
+ return {
641
+ state,
642
+ framesSeen,
643
+ operationFrames,
644
+ rootOrderFrames,
645
+ envelopeTypes
646
+ };
647
+ } catch (e) {
648
+ env.error = e;
649
+ env.hasError = true;
650
+ } finally{
651
+ const result = session_ts_dispose_resources(env);
652
+ if (result) await result;
653
+ }
654
+ }
655
+ function reactLynxEmptyTreeDiagnostic(result) {
656
+ if (0 === result.framesSeen) return "saw 0 frames -- the App is silent on the PreactDevtools channel. Most likely `@lynx-js/preact-devtools` is not installed, the bundle is a production build, or `setupReactLynx()` has not run yet. Look for `[PREACT DEVTOOLS] Devtools initialized successfully` in the device console.";
657
+ if (0 === result.operationFrames) return `saw ${result.framesSeen} frame(s) but no \`operation_v2\` -- \`@lynx-js/preact-devtools\` is loaded but does not honor \`refresh\`. Upgrade to a build with the \`document.body\` and \`preactDevtoolsCtx.Node\` fixes.`;
658
+ return `saw ${result.framesSeen} frame(s) including ${result.operationFrames} \`operation_v2\` but the resulting tree is empty (every node was unmounted).`;
659
+ }
660
+ class ReactLynxActionError extends Error {
661
+ reason;
662
+ recoverable;
663
+ nextActions;
664
+ constructor(message, options){
665
+ super(message);
666
+ this.name = 'ReactLynxActionError';
667
+ this.reason = options.reason;
668
+ this.recoverable = options.recoverable ?? true;
669
+ this.nextActions = options.nextActions ?? [];
670
+ }
671
+ }
672
+ function labelViewKey(showShells) {
673
+ return showShells ? 'shells' : 'compact';
674
+ }
675
+ function cacheInfo(target) {
676
+ return {
677
+ status: target.status,
678
+ generation: target.entry.generation,
679
+ capturedAt: target.entry.capturedAt
680
+ };
681
+ }
682
+ function controller_envelopeTypes(result) {
683
+ return [
684
+ ...result.envelopeTypes
685
+ ].sort().join(',') || '(none)';
686
+ }
687
+ function parseParameter(operation) {
688
+ try {
689
+ return operation();
690
+ } catch (error) {
691
+ throw new ReactLynxActionError(error instanceof Error ? error.message : String(error), {
692
+ reason: 'bad-params',
693
+ recoverable: false
694
+ });
695
+ }
696
+ }
697
+ async function waitForTurn(turn, signal) {
698
+ signal.throwIfAborted();
699
+ let onAbort;
700
+ const aborted = new Promise((_resolve, reject)=>{
701
+ onAbort = ()=>reject(signal.reason);
702
+ signal.addEventListener('abort', onAbort, {
703
+ once: true
704
+ });
705
+ });
706
+ try {
707
+ await Promise.race([
708
+ turn,
709
+ aborted
710
+ ]);
711
+ } finally{
712
+ if (onAbort) signal.removeEventListener('abort', onAbort);
713
+ }
714
+ }
715
+ class ReactLynxController {
716
+ #cache = new Map();
717
+ #generations = new Map();
718
+ #sessionTails = new Map();
719
+ #key(clientId, sessionId) {
720
+ return `${clientId}:${sessionId}`;
721
+ }
722
+ async #withSession(target, signal, operation) {
723
+ const key = this.#key(target.clientId, target.sessionId);
724
+ const previous = this.#sessionTails.get(key) ?? Promise.resolve();
725
+ let release;
726
+ const gate = new Promise((resolve)=>{
727
+ release = resolve;
728
+ });
729
+ const tail = previous.catch(()=>{}).then(()=>gate);
730
+ this.#sessionTails.set(key, tail);
731
+ try {
732
+ await waitForTurn(previous.catch(()=>{}), signal);
733
+ signal.throwIfAborted();
734
+ return await operation();
735
+ } finally{
736
+ release();
737
+ tail.then(()=>{
738
+ if (this.#sessionTails.get(key) === tail) this.#sessionTails.delete(key);
739
+ });
740
+ }
741
+ }
742
+ async #capture(connector, target, signal) {
743
+ const result = await runReactLynxSession({
744
+ connector,
745
+ clientId: target.clientId,
746
+ sessionId: target.sessionId,
747
+ outbound: [
748
+ buildReactLynxOutboundFrame('refresh')
749
+ ],
750
+ signal
751
+ });
752
+ if (0 === result.state.tree.size) throw new ReactLynxActionError(reactLynxEmptyTreeDiagnostic(result), {
753
+ reason: 'reactlynx-empty-tree',
754
+ nextActions: [
755
+ 'Verify that this is a ReactLynx development build with @lynx-js/preact-devtools enabled.',
756
+ 'Run `agent-lynx reactlynx tree` again after the page has settled.'
757
+ ]
758
+ });
759
+ const key = this.#key(target.clientId, target.sessionId);
760
+ const generation = (this.#generations.get(key) ?? 0) + 1;
761
+ this.#generations.set(key, generation);
762
+ const entry = {
763
+ state: result.state,
764
+ capturedAt: Date.now(),
765
+ generation,
766
+ labelViews: new Map()
767
+ };
768
+ this.#cache.set(key, entry);
769
+ return entry;
770
+ }
771
+ async #cachedTarget(connector, target, refresh, signal) {
772
+ const key = this.#key(target.clientId, target.sessionId);
773
+ const existing = refresh ? void 0 : this.#cache.get(key);
774
+ if (existing) return {
775
+ ...target,
776
+ entry: existing,
777
+ status: 'reused'
778
+ };
779
+ const entry = await this.#capture(connector, target, signal);
780
+ return {
781
+ ...target,
782
+ entry,
783
+ status: 'refreshed'
784
+ };
785
+ }
786
+ #labels(entry, showShells) {
787
+ const key = labelViewKey(showShells);
788
+ const existing = entry.labelViews.get(key);
789
+ if (existing) return existing;
790
+ const labels = formatReactLynxTree(entry.state, {
791
+ hideShells: !showShells
792
+ }).labels;
793
+ entry.labelViews.set(key, labels);
794
+ return labels;
795
+ }
796
+ #linkedComponent(entry, id, showShells) {
797
+ const node = entry.state.tree.get(id);
798
+ if (!node) return;
799
+ const index = this.#labels(entry, showShells).indexOf(id);
800
+ return {
801
+ ref: index < 0 ? null : `@c${index + 1}`,
802
+ id: node.id,
803
+ type: node.type,
804
+ name: node.name,
805
+ key: node.key
806
+ };
807
+ }
808
+ #evict(target) {
809
+ this.#cache.delete(this.#key(target.clientId, target.sessionId));
810
+ }
811
+ getCache(clientId, sessionId) {
812
+ const entry = this.#cache.get(this.#key(clientId, sessionId));
813
+ if (!entry) return;
814
+ const compactLabels = entry.labelViews.get('compact');
815
+ const shellLabels = entry.labelViews.get('shells');
816
+ return {
817
+ capturedAt: entry.capturedAt,
818
+ generation: entry.generation,
819
+ nodeCount: entry.state.tree.size,
820
+ ...compactLabels ? {
821
+ compactLabels: [
822
+ ...compactLabels
823
+ ]
824
+ } : {},
825
+ ...shellLabels ? {
826
+ shellLabels: [
827
+ ...shellLabels
828
+ ]
829
+ } : {}
830
+ };
831
+ }
832
+ tree(connector, target, options, signal) {
833
+ return this.#withSession(target, signal, async ()=>{
834
+ const cached = await this.#cachedTarget(connector, target, true, signal);
835
+ const formatted = formatReactLynxTree(cached.entry.state, {
836
+ hideShells: !options.showShells,
837
+ ...void 0 === options.depth ? {} : {
838
+ maxDepth: options.depth
839
+ }
840
+ });
841
+ cached.entry.labelViews.set(labelViewKey(options.showShells), formatted.labels);
842
+ const serialized = serializeRendererState(cached.entry.state);
843
+ return {
844
+ ...target,
845
+ cache: cacheInfo(cached),
846
+ labels: formatted.labels,
847
+ roots: serialized.roots,
848
+ nodes: serialized.nodes
849
+ };
850
+ });
851
+ }
852
+ find(connector, target, options, signal) {
853
+ return this.#withSession(target, signal, async ()=>{
854
+ const matcher = parseParameter(()=>options.regex ? buildRegexMatcher(options.pattern) : buildSubstringMatcher(options.pattern));
855
+ const cached = await this.#cachedTarget(connector, target, options.refresh, signal);
856
+ const formatted = formatReactLynxTree(cached.entry.state, {
857
+ hideShells: !options.showShells
858
+ });
859
+ const matches = findReactLynxComponents(cached.entry.state, matcher, {
860
+ hideShells: !options.showShells,
861
+ limit: options.limit,
862
+ formatted
863
+ });
864
+ if (0 === matches.length) throw new ReactLynxActionError(`No components match ${options.regex ? 'regex' : 'substring'} ${JSON.stringify(options.pattern)} (searched ${cached.entry.state.tree.size} components${options.showShells ? '' : ', shells hidden'}).`, {
865
+ reason: 'reactlynx-no-match',
866
+ nextActions: [
867
+ 'Try a broader pattern or run `agent-lynx reactlynx tree`.'
868
+ ]
869
+ });
870
+ cached.entry.labelViews.set(labelViewKey(options.showShells), formatted.labels);
871
+ return {
872
+ ...target,
873
+ cache: cacheInfo(cached),
874
+ componentCount: cached.entry.state.tree.size,
875
+ matches
876
+ };
877
+ });
878
+ }
879
+ component(connector, target, options, signal) {
880
+ return this.#withSession(target, signal, async ()=>{
881
+ const parsed = parseParameter(()=>parseReactLynxComponentRef(options.ref));
882
+ if ('id' === parsed.kind) {
883
+ const component = await this.#inspect(connector, target, parsed.id, signal);
884
+ return {
885
+ ...target,
886
+ cache: {
887
+ status: 'not-used'
888
+ },
889
+ ref: options.ref,
890
+ id: parsed.id,
891
+ component
892
+ };
893
+ }
894
+ const cached = await this.#cachedTarget(connector, target, options.refresh, signal);
895
+ const labels = this.#labels(cached.entry, options.showShells);
896
+ const id = labels[parsed.index - 1];
897
+ if (void 0 === id) throw new ReactLynxActionError(`Label ${options.ref} does not exist; the cached tree has ${labels.length} labelled component(s).`, {
898
+ reason: 'reactlynx-ref-not-found',
899
+ nextActions: [
900
+ 'Run `agent-lynx reactlynx tree`, then retry with one of its labels.'
901
+ ]
902
+ });
903
+ try {
904
+ const component = await this.#inspect(connector, target, id, signal);
905
+ return {
906
+ ...target,
907
+ cache: cacheInfo(cached),
908
+ ref: options.ref,
909
+ id,
910
+ component
911
+ };
912
+ } catch (error) {
913
+ this.#evict(target);
914
+ throw error;
915
+ }
916
+ });
917
+ }
918
+ componentForElement(connector, target, options, signal) {
919
+ return this.#withSession(target, signal, async ()=>{
920
+ let cached = await this.#cachedTarget(connector, target, options.refresh, signal);
921
+ const id = await this.#componentIdForUniqueId(connector, target, options.uniqueId, signal);
922
+ if (!cached.entry.state.tree.has(id) && 'reused' === cached.status) cached = {
923
+ ...target,
924
+ entry: await this.#capture(connector, target, signal),
925
+ status: 'refreshed'
926
+ };
927
+ const component = this.#linkedComponent(cached.entry, id, options.showShells);
928
+ if (!component) throw new ReactLynxActionError(`Mapped component id ${id} is absent from the current ReactLynx tree.`, {
929
+ reason: 'reactlynx-stale-component',
930
+ nextActions: [
931
+ 'Run `agent-lynx reactlynx tree`, then retry the link.'
932
+ ]
933
+ });
934
+ return {
935
+ cache: cacheInfo(cached),
936
+ component
937
+ };
938
+ });
939
+ }
940
+ elementForComponent(connector, target, options, signal) {
941
+ return this.#withSession(target, signal, async ()=>{
942
+ const parsed = parseParameter(()=>parseReactLynxComponentRef(options.ref));
943
+ let cached = await this.#cachedTarget(connector, target, options.refresh, signal);
944
+ let id;
945
+ if ('label' === parsed.kind) {
946
+ const labels = this.#labels(cached.entry, options.showShells);
947
+ const resolved = labels[parsed.index - 1];
948
+ if (void 0 === resolved) throw new ReactLynxActionError(`Label ${options.ref} does not exist; the cached tree has ${labels.length} labelled component(s).`, {
949
+ reason: 'reactlynx-ref-not-found',
950
+ nextActions: [
951
+ 'Run `agent-lynx reactlynx tree`, then retry with one of its labels.'
952
+ ]
953
+ });
954
+ id = resolved;
955
+ } else {
956
+ id = parsed.id;
957
+ if (!cached.entry.state.tree.has(id) && 'reused' === cached.status) cached = {
958
+ ...target,
959
+ entry: await this.#capture(connector, target, signal),
960
+ status: 'refreshed'
961
+ };
962
+ }
963
+ const component = this.#linkedComponent(cached.entry, id, options.showShells);
964
+ if (!component) throw new ReactLynxActionError(`Component id ${id} is absent from the current ReactLynx tree.`, {
965
+ reason: 'reactlynx-ref-not-found',
966
+ nextActions: [
967
+ 'Run `agent-lynx reactlynx tree`, then retry the link.'
968
+ ]
969
+ });
970
+ const uniqueId = await this.#uniqueIdForComponent(connector, target, id, signal);
971
+ return {
972
+ cache: cacheInfo(cached),
973
+ component,
974
+ uniqueId
975
+ };
976
+ });
977
+ }
978
+ update(connector, target, options, signal) {
979
+ return this.#withSession(target, signal, async ()=>{
980
+ const path = parseParameter(()=>buildReactLynxUpdatePath(options.path));
981
+ const parsed = parseParameter(()=>parseReactLynxComponentRef(options.ref));
982
+ let id;
983
+ let cached;
984
+ if ('id' === parsed.kind) id = parsed.id;
985
+ else {
986
+ cached = await this.#cachedTarget(connector, target, options.refresh, signal);
987
+ const labels = this.#labels(cached.entry, options.showShells);
988
+ const resolved = labels[parsed.index - 1];
989
+ if (void 0 === resolved) throw new ReactLynxActionError(`Label ${options.ref} does not exist; the cached tree has ${labels.length} labelled component(s).`, {
990
+ reason: 'reactlynx-ref-not-found',
991
+ nextActions: [
992
+ 'Run `agent-lynx reactlynx tree`, then retry with one of its labels.'
993
+ ]
994
+ });
995
+ id = resolved;
996
+ }
997
+ try {
998
+ const component = await this.#update(connector, target, options.kind, {
999
+ id,
1000
+ path,
1001
+ value: options.value
1002
+ }, signal);
1003
+ return {
1004
+ ...target,
1005
+ cache: cached ? cacheInfo(cached) : {
1006
+ status: 'not-used'
1007
+ },
1008
+ ref: options.ref,
1009
+ id,
1010
+ component
1011
+ };
1012
+ } catch (error) {
1013
+ if (cached) this.#evict(target);
1014
+ throw error;
1015
+ }
1016
+ });
1017
+ }
1018
+ async #inspect(connector, target, id, signal) {
1019
+ let component;
1020
+ const result = await runReactLynxSession({
1021
+ connector,
1022
+ clientId: target.clientId,
1023
+ sessionId: target.sessionId,
1024
+ outbound: [
1025
+ buildReactLynxOutboundFrame('inspect', id)
1026
+ ],
1027
+ awaitEnvelope: true,
1028
+ idleMs: 1000,
1029
+ maxMs: 5000,
1030
+ signal,
1031
+ onEnvelope: (envelope)=>{
1032
+ if ('inspect-result' === envelope.type && 'object' == typeof envelope.data && null !== envelope.data && envelope.data.id === id) {
1033
+ component = envelope.data;
1034
+ return 'stop';
1035
+ }
1036
+ return 'continue';
1037
+ }
1038
+ });
1039
+ if (component) return component;
1040
+ throw new ReactLynxActionError(`No \`inspect-result\` for id ${id} after ${result.framesSeen} frame(s) (types=${controller_envelopeTypes(result)}). The component may be stale, the session may not be ReactLynx, or the App's @lynx-js/preact-devtools may not support inspect.`, {
1041
+ reason: 'reactlynx-no-response',
1042
+ nextActions: [
1043
+ 'Run `agent-lynx reactlynx tree` to refresh component refs, then retry.'
1044
+ ]
1045
+ });
1046
+ }
1047
+ async #componentIdForUniqueId(connector, target, uniqueId, signal) {
1048
+ let id;
1049
+ const result = await runReactLynxSession({
1050
+ connector,
1051
+ clientId: target.clientId,
1052
+ sessionId: target.sessionId,
1053
+ outbound: [
1054
+ buildReactLynxOutboundFrame('element-picked', {
1055
+ uniqueId
1056
+ })
1057
+ ],
1058
+ awaitEnvelope: true,
1059
+ idleMs: 1000,
1060
+ maxMs: 5000,
1061
+ signal,
1062
+ onEnvelope: (envelope)=>{
1063
+ if ('element-picked-vnode-id' !== envelope.type) return 'continue';
1064
+ const candidate = envelope.data?.id;
1065
+ if ('number' != typeof candidate || !Number.isFinite(candidate)) return 'continue';
1066
+ id = candidate;
1067
+ return 'stop';
1068
+ }
1069
+ });
1070
+ if (void 0 !== id) return id;
1071
+ throw new ReactLynxActionError(`No ReactLynx component mapping was returned for DOM uniqueId ${uniqueId} after ${result.framesSeen} frame(s) (types=${controller_envelopeTypes(result)}). The element may not be React-owned, or the App-side identity mapping may not be ready.`, {
1072
+ reason: 'reactlynx-component-not-found',
1073
+ nextActions: [
1074
+ 'Retry after the page has settled, or run `agent-lynx reactlynx tree --refresh`.'
1075
+ ]
1076
+ });
1077
+ }
1078
+ async #uniqueIdForComponent(connector, target, id, signal) {
1079
+ let uniqueId;
1080
+ const result = await runReactLynxSession({
1081
+ connector,
1082
+ clientId: target.clientId,
1083
+ sessionId: target.sessionId,
1084
+ outbound: [
1085
+ buildReactLynxOutboundFrame('highlight', id)
1086
+ ],
1087
+ awaitEnvelope: true,
1088
+ idleMs: 1000,
1089
+ maxMs: 5000,
1090
+ signal,
1091
+ onEnvelope: (envelope)=>{
1092
+ if ('preact-devtools-highlight' !== envelope.type) return 'continue';
1093
+ const candidate = envelope.data?.uniqueId;
1094
+ if ('number' != typeof candidate || !Number.isFinite(candidate)) return 'continue';
1095
+ uniqueId = candidate;
1096
+ return 'stop';
1097
+ }
1098
+ });
1099
+ if (void 0 !== uniqueId) return uniqueId;
1100
+ throw new ReactLynxActionError(`No host element mapping was returned for component id ${id} after ${result.framesSeen} frame(s) (types=${controller_envelopeTypes(result)}). The component may render null or a Fragment, or its host element may be offscreen in a virtual list.`, {
1101
+ reason: 'reactlynx-element-not-found',
1102
+ nextActions: [
1103
+ 'Make the component visible, or retry with `--refresh` after the page has settled.'
1104
+ ]
1105
+ });
1106
+ }
1107
+ async #update(connector, target, kind, payload, signal) {
1108
+ let confirmation;
1109
+ const result = await runReactLynxSession({
1110
+ connector,
1111
+ clientId: target.clientId,
1112
+ sessionId: target.sessionId,
1113
+ outbound: [
1114
+ buildReactLynxOutboundFrame(kind, payload)
1115
+ ],
1116
+ awaitEnvelope: true,
1117
+ idleMs: 1000,
1118
+ maxMs: 5000,
1119
+ signal,
1120
+ onEnvelope: (envelope)=>{
1121
+ if ('inspect-result' === envelope.type && 'object' == typeof envelope.data && null !== envelope.data && envelope.data.id === payload.id) {
1122
+ confirmation = envelope.data;
1123
+ return 'stop';
1124
+ }
1125
+ return 'continue';
1126
+ }
1127
+ });
1128
+ if (confirmation) return confirmation;
1129
+ throw new ReactLynxActionError(`No confirmation \`inspect-result\` for id ${payload.id} after ${result.framesSeen} frame(s) (types=${controller_envelopeTypes(result)}). The component may be stale or the App may not support \`${kind}\`.`, {
1130
+ reason: 'reactlynx-no-response',
1131
+ nextActions: [
1132
+ 'Run `agent-lynx reactlynx tree`, verify the component/path, then retry.'
1133
+ ]
1134
+ });
1135
+ }
1136
+ }
1137
+ function ok(action, data) {
1138
+ return {
1139
+ ok: true,
1140
+ action,
1141
+ data
1142
+ };
1143
+ }
1144
+ function stringifyCause(cause) {
1145
+ if (cause instanceof Error) return void 0 === cause.cause ? cause.message : stringifyCause(cause.cause);
1146
+ if ('string' == typeof cause) return cause;
1147
+ try {
1148
+ const serialized = JSON.stringify(cause);
1149
+ if (void 0 !== serialized) return serialized;
1150
+ } catch {}
1151
+ return String(cause);
1152
+ }
1153
+ function result_fail(action, message, options = {}) {
1154
+ const error = {
1155
+ message,
1156
+ recoverable: options.recoverable ?? false,
1157
+ nextActions: options.nextActions ?? []
1158
+ };
1159
+ if (void 0 !== options.cause) error.cause = stringifyCause(options.cause);
1160
+ if (void 0 !== options.reason) error.reason = options.reason;
1161
+ return {
1162
+ ok: false,
1163
+ action,
1164
+ error
1165
+ };
1166
+ }
1167
+ const SNAPSHOT_REF_HIT_NODE_IDS = Symbol('snapshotRefHitNodeIds');
1168
+ const SNAPSHOT_REF_VISIBLE_BOX = Symbol('snapshotRefVisibleBox');
1169
+ const SNAPSHOT_REF_NEEDS_HIT_TEST = Symbol('snapshotRefNeedsHitTest');
1170
+ const SNAPSHOT_REF_ANNOTATION_ROLE = Symbol('snapshotRefAnnotationRole');
1171
+ const INTERACTIVE_TAGS = new Set([
1172
+ 'view',
1173
+ 'text',
1174
+ 'image',
1175
+ 'scroll-view',
1176
+ 'list',
1177
+ 'x-input',
1178
+ 'input',
1179
+ 'textarea'
1180
+ ]);
1181
+ const SCROLLABLE_TAGS = new Set([
1182
+ 'scroll-view',
1183
+ 'list',
1184
+ 'x-scroll-view',
1185
+ 'x-list'
1186
+ ]);
1187
+ const EDITABLE_TAGS = new Set([
1188
+ 'input',
1189
+ 'textarea',
1190
+ 'x-input',
1191
+ 'x-textarea'
1192
+ ]);
1193
+ const SURFACED_ATTRS = [
1194
+ 'id',
1195
+ 'class',
1196
+ 'lynx-test-tag',
1197
+ 'value',
1198
+ 'placeholder',
1199
+ 'disabled',
1200
+ 'name',
1201
+ 'type'
1202
+ ];
1203
+ const PROTOCOL_ATTR_ALIASES = {
1204
+ classSelector: 'class',
1205
+ idSelector: 'id'
1206
+ };
1207
+ const ACTION_EVENT_ATTR = /^(?:capture-)?(?:bind|catch)(?:tap|longpress|touchstart|touchmove|touchend|input|change|confirm|submit)$/u;
1208
+ function getAttr(node, name) {
1209
+ const attrs = node.attributes ?? [];
1210
+ for(let i = 0; i + 1 < attrs.length; i += 2)if (attrs[i] === name) return attrs[i + 1];
1211
+ }
1212
+ function hasActionEvent(node) {
1213
+ const attrs = node.attributes ?? [];
1214
+ for(let index = 0; index + 1 < attrs.length; index += 2)if (ACTION_EVENT_ATTR.test(attrs[index])) return true;
1215
+ return false;
1216
+ }
1217
+ function surfacedAttributes(node) {
1218
+ const result = {};
1219
+ for (const name of SURFACED_ATTRS){
1220
+ const value = getAttr(node, name);
1221
+ if (void 0 !== value) result[name] = value;
1222
+ }
1223
+ for (const [protocolName, publicName] of Object.entries(PROTOCOL_ATTR_ALIASES)){
1224
+ if (void 0 !== result[publicName]) continue;
1225
+ const value = getAttr(node, protocolName);
1226
+ if (void 0 !== value) result[publicName] = value;
1227
+ }
1228
+ return result;
1229
+ }
1230
+ function quadBounds(quad) {
1231
+ const xs = [
1232
+ quad[0],
1233
+ quad[2],
1234
+ quad[4],
1235
+ quad[6]
1236
+ ];
1237
+ const ys = [
1238
+ quad[1],
1239
+ quad[3],
1240
+ quad[5],
1241
+ quad[7]
1242
+ ];
1243
+ return {
1244
+ minX: Math.min(...xs),
1245
+ maxX: Math.max(...xs),
1246
+ minY: Math.min(...ys),
1247
+ maxY: Math.max(...ys)
1248
+ };
1249
+ }
1250
+ function centerOfQuad(quad) {
1251
+ const { minX, maxX, minY, maxY } = quadBounds(quad);
1252
+ return {
1253
+ x: Math.round((minX + maxX) / 2),
1254
+ y: Math.round((minY + maxY) / 2)
1255
+ };
1256
+ }
1257
+ function boxOfQuad(quad) {
1258
+ const { minX, maxX, minY, maxY } = quadBounds(quad);
1259
+ return {
1260
+ x: Math.round(minX),
1261
+ y: Math.round(minY),
1262
+ width: Math.round(maxX - minX),
1263
+ height: Math.round(maxY - minY)
1264
+ };
1265
+ }
1266
+ function collectText(node, depth = 0) {
1267
+ if (depth > 3) return '';
1268
+ const finish = (value)=>0 === depth ? value.trim() : value;
1269
+ if (3 === node.nodeType && node.nodeValue) return finish(node.nodeValue);
1270
+ const tag = tagName(node);
1271
+ const ownText = getAttr(node, 'text');
1272
+ if (('text' === tag || 'raw-text' === tag) && ownText) return finish(ownText);
1273
+ const ownValue = getAttr(node, 'value');
1274
+ if (EDITABLE_TAGS.has(tag) && ownValue) return finish(ownValue);
1275
+ if (SCROLLABLE_TAGS.has(tag)) return '';
1276
+ const parts = [];
1277
+ for (const child of node.children ?? []){
1278
+ const childTag = tagName(child);
1279
+ const childQuad = boxQuad(child);
1280
+ const childHasOwnRef = void 0 !== childQuad && childQuad.length >= 8 && isInteractive(child) && boxOfQuad(childQuad).width > 0 && boxOfQuad(childQuad).height > 0;
1281
+ if ('text' !== tag && 3 !== child.nodeType && 'text' !== childTag && 'raw-text' !== childTag) continue;
1282
+ if ('text' !== tag && childHasOwnRef) continue;
1283
+ const text = collectText(child, depth + 1);
1284
+ if (text) parts.push(text);
1285
+ }
1286
+ return finish(parts.join(''));
1287
+ }
1288
+ function collectNodeIds(node, result = new Set()) {
1289
+ result.add(node.nodeId);
1290
+ for (const child of node.children ?? [])collectNodeIds(child, result);
1291
+ return result;
1292
+ }
1293
+ function tagName(node) {
1294
+ return (node.localName || node.nodeName || '').toLowerCase();
1295
+ }
1296
+ function boxQuad(node) {
1297
+ const model = node.box_model ?? node.boxModel;
1298
+ return model?.content ?? model?.border;
1299
+ }
1300
+ function visuallyOrderedChildren(node) {
1301
+ const children = node.children ?? [];
1302
+ if (!SCROLLABLE_TAGS.has(tagName(node)) || children.length < 2) return children;
1303
+ const decorated = children.map((child, index)=>{
1304
+ const quad = boxQuad(child);
1305
+ return {
1306
+ child,
1307
+ index,
1308
+ box: quad && quad.length >= 8 ? boxOfQuad(quad) : void 0
1309
+ };
1310
+ });
1311
+ if (decorated.some((item)=>void 0 === item.box)) return children;
1312
+ return decorated.sort((left, right)=>{
1313
+ const leftBox = left.box;
1314
+ const rightBox = right.box;
1315
+ return leftBox.y - rightBox.y || leftBox.x - rightBox.x || left.index - right.index;
1316
+ }).map((item)=>item.child);
1317
+ }
1318
+ function isInteractive(node) {
1319
+ const tag = tagName(node);
1320
+ if (!INTERACTIVE_TAGS.has(tag)) return false;
1321
+ if (hasActionEvent(node)) return true;
1322
+ if (void 0 !== getAttr(node, 'lynx-test-tag')) return true;
1323
+ return 'text' === tag || 'image' === tag || 'view' === tag || EDITABLE_TAGS.has(tag) || SCROLLABLE_TAGS.has(tag);
1324
+ }
1325
+ function annotationRole(node) {
1326
+ const tag = tagName(node);
1327
+ if (EDITABLE_TAGS.has(tag)) return 'editable';
1328
+ if (hasActionEvent(node)) return 'action';
1329
+ if (SCROLLABLE_TAGS.has(tag)) return 'scrollable';
1330
+ if (void 0 !== getAttr(node, 'lynx-test-tag')) return 'target';
1331
+ return 'generic';
1332
+ }
1333
+ function intersectBoxes(a, b) {
1334
+ const x = Math.max(a.x, b.x);
1335
+ const y = Math.max(a.y, b.y);
1336
+ const right = Math.min(a.x + a.width, b.x + b.width);
1337
+ const bottom = Math.min(a.y + a.height, b.y + b.height);
1338
+ if (right <= x || bottom <= y) return null;
1339
+ return {
1340
+ x,
1341
+ y,
1342
+ width: right - x,
1343
+ height: bottom - y
1344
+ };
1345
+ }
1346
+ function applyClip(clip, box) {
1347
+ if (void 0 === clip) return box;
1348
+ if (null === clip) return null;
1349
+ return intersectBoxes(clip, box);
1350
+ }
1351
+ function sameBox(left, right) {
1352
+ if (null === left || null === right) return left === right;
1353
+ return left.x === right.x && left.y === right.y && left.width === right.width && left.height === right.height;
1354
+ }
1355
+ function centerOfBox(box) {
1356
+ return {
1357
+ x: Math.round(box.x + box.width / 2),
1358
+ y: Math.round(box.y + box.height / 2)
1359
+ };
1360
+ }
1361
+ function computeFlags(node, box, clip) {
1362
+ const tag = tagName(node);
1363
+ const visibleBox = void 0 === clip ? box : applyClip(clip, box);
1364
+ const visible = box.width > 0 && box.height > 0 && null !== visibleBox;
1365
+ return {
1366
+ interactive: isInteractive(node),
1367
+ visible,
1368
+ offscreen: void 0 !== clip && !visible,
1369
+ scrollable: SCROLLABLE_TAGS.has(tag),
1370
+ disabled: void 0 !== getAttr(node, 'disabled'),
1371
+ editable: EDITABLE_TAGS.has(tag)
1372
+ };
1373
+ }
1374
+ function deriveViewport(root) {
1375
+ const findFirstBox = (node, depth)=>{
1376
+ const quad = boxQuad(node);
1377
+ if (quad && quad.length >= 8) {
1378
+ const box = boxOfQuad(quad);
1379
+ if (box.width > 0 && box.height > 0) return box;
1380
+ }
1381
+ if (depth > 4) return;
1382
+ for (const child of node.children ?? []){
1383
+ const box = findFirstBox(child, depth + 1);
1384
+ if (box) return box;
1385
+ }
1386
+ };
1387
+ return findFirstBox(root, 0);
1388
+ }
1389
+ function buildRefs(root, viewport) {
1390
+ const refs = [];
1391
+ let counter = 0;
1392
+ const visit = (node, parentRef, clip, needsHitTest)=>{
1393
+ let childParentRef = parentRef;
1394
+ const quad = boxQuad(node);
1395
+ const box = quad && quad.length >= 8 ? boxOfQuad(quad) : void 0;
1396
+ if (box && isInteractive(node)) {
1397
+ if (box.width > 0 && box.height > 0) {
1398
+ const visibleBox = void 0 === clip ? box : applyClip(clip, box);
1399
+ counter += 1;
1400
+ const ref = {
1401
+ ref: `@e${counter}`,
1402
+ tag: tagName(node),
1403
+ text: collectText(node).slice(0, 80),
1404
+ nodeId: node.nodeId,
1405
+ center: centerOfBox(visibleBox ?? box),
1406
+ box,
1407
+ flags: computeFlags(node, box, clip),
1408
+ attributes: surfacedAttributes(node),
1409
+ [SNAPSHOT_REF_HIT_NODE_IDS]: collectNodeIds(node),
1410
+ [SNAPSHOT_REF_NEEDS_HIT_TEST]: needsHitTest,
1411
+ [SNAPSHOT_REF_ANNOTATION_ROLE]: annotationRole(node)
1412
+ };
1413
+ if (visibleBox) ref[SNAPSHOT_REF_VISIBLE_BOX] = visibleBox;
1414
+ if (void 0 !== parentRef) ref.parentRef = parentRef;
1415
+ if (void 0 !== node.backendNodeId) ref.backendNodeId = node.backendNodeId;
1416
+ refs.push(ref);
1417
+ childParentRef = ref.ref;
1418
+ }
1419
+ }
1420
+ let childClip = clip;
1421
+ let childNeedsHitTest = needsHitTest;
1422
+ if (box && box.width > 0 && box.height > 0 && SCROLLABLE_TAGS.has(tagName(node))) {
1423
+ const nextClip = applyClip(clip, box);
1424
+ if (void 0 === clip || !sameBox(nextClip, clip)) childNeedsHitTest = true;
1425
+ childClip = nextClip;
1426
+ }
1427
+ for (const child of visuallyOrderedChildren(node))visit(child, childParentRef, childClip, childNeedsHitTest);
1428
+ };
1429
+ visit(root, void 0, viewport, false);
1430
+ const siblingsByBox = new Map();
1431
+ for (const ref of refs){
1432
+ if (!ref.flags.visible) continue;
1433
+ const key = `${ref.parentRef ?? '<root>'}:${ref.box.x}:${ref.box.y}:${ref.box.width}:${ref.box.height}`;
1434
+ const siblings = siblingsByBox.get(key);
1435
+ if (siblings) siblings.push(ref);
1436
+ else siblingsByBox.set(key, [
1437
+ ref
1438
+ ]);
1439
+ }
1440
+ for (const siblings of siblingsByBox.values())if (!(siblings.length < 2)) for (const ref of siblings)ref[SNAPSHOT_REF_NEEDS_HIT_TEST] = true;
1441
+ return refs;
1442
+ }
1443
+ function hitTestPoints(box) {
1444
+ const fractions = [
1445
+ [
1446
+ 0.5,
1447
+ 0.5
1448
+ ],
1449
+ [
1450
+ 0.25,
1451
+ 0.25
1452
+ ],
1453
+ [
1454
+ 0.75,
1455
+ 0.25
1456
+ ],
1457
+ [
1458
+ 0.25,
1459
+ 0.75
1460
+ ],
1461
+ [
1462
+ 0.75,
1463
+ 0.75
1464
+ ]
1465
+ ];
1466
+ const points = fractions.map(([x, y])=>({
1467
+ x: Math.round(box.x + box.width * x),
1468
+ y: Math.round(box.y + box.height * y)
1469
+ }));
1470
+ return points.filter((point, index)=>points.findIndex((candidate)=>candidate.x === point.x && candidate.y === point.y) === index);
1471
+ }
1472
+ async function isPaintedRef(connector, clientId, sessionId, ref, signal) {
1473
+ let unresolvedBackendHit = false;
1474
+ for (const point of hitTestPoints(ref[SNAPSHOT_REF_VISIBLE_BOX] ?? ref.box)){
1475
+ signal?.throwIfAborted();
1476
+ let located;
1477
+ try {
1478
+ located = await connector.sendCDPMessage(clientId, sessionId, 'DOM.getNodeForLocation', point);
1479
+ } catch {
1480
+ signal?.throwIfAborted();
1481
+ return;
1482
+ }
1483
+ if (void 0 !== located.backendNodeId && 0 !== located.backendNodeId && located.backendNodeId === ref.backendNodeId) return true;
1484
+ if (void 0 !== located.nodeId && 0 !== located.nodeId) {
1485
+ if (located.nodeId === ref.nodeId || ref[SNAPSHOT_REF_HIT_NODE_IDS]?.has(located.nodeId)) return true;
1486
+ } else if (void 0 !== located.backendNodeId && 0 !== located.backendNodeId) unresolvedBackendHit = true;
1487
+ }
1488
+ return unresolvedBackendHit ? void 0 : false;
1489
+ }
1490
+ async function refinePaintVisibility(connector, clientId, sessionId, refs, signal) {
1491
+ const candidates = refs.filter((ref)=>ref.flags.visible && true === ref[SNAPSHOT_REF_NEEDS_HIT_TEST]);
1492
+ const concurrency = 8;
1493
+ for(let index = 0; index < candidates.length; index += concurrency){
1494
+ const batch = candidates.slice(index, index + concurrency);
1495
+ const verdicts = await Promise.all(batch.map((ref)=>isPaintedRef(connector, clientId, sessionId, ref, signal)));
1496
+ signal?.throwIfAborted();
1497
+ for(let offset = 0; offset < batch.length; offset += 1){
1498
+ if (false !== verdicts[offset]) continue;
1499
+ const ref = batch[offset];
1500
+ ref.flags = {
1501
+ ...ref.flags,
1502
+ visible: false
1503
+ };
1504
+ }
1505
+ if (verdicts.every((verdict)=>void 0 === verdict)) break;
1506
+ }
1507
+ }
1508
+ function firstStringProperty(records, names) {
1509
+ for (const record of records)for (const name of names){
1510
+ const value = record?.[name];
1511
+ if ('string' == typeof value) return value;
1512
+ }
1513
+ }
1514
+ async function enrichEditableValues(connector, clientId, sessionId, refs, signal) {
1515
+ const editableRefs = refs.filter((ref)=>ref.flags.visible && ref.flags.editable && !ref.attributes['type']?.toLowerCase().includes('password'));
1516
+ if (0 === editableRefs.length) return;
1517
+ try {
1518
+ await connector.sendCDPMessage(clientId, sessionId, 'UITree.enable');
1519
+ } catch {
1520
+ signal?.throwIfAborted();
1521
+ return;
1522
+ }
1523
+ signal?.throwIfAborted();
1524
+ for (const ref of editableRefs){
1525
+ let info;
1526
+ try {
1527
+ info = await connector.sendCDPMessage(clientId, sessionId, 'UITree.getUIInfoForNode', {
1528
+ UINodeId: ref.nodeId
1529
+ });
1530
+ } catch {
1531
+ signal?.throwIfAborted();
1532
+ continue;
1533
+ }
1534
+ signal?.throwIfAborted();
1535
+ const value = firstStringProperty([
1536
+ info.readonlyProps,
1537
+ info.ui?.readonlyProps,
1538
+ info.view?.readonlyProps
1539
+ ], [
1540
+ 'value',
1541
+ 'text',
1542
+ 'mText',
1543
+ 'mSpannable',
1544
+ 'mTransformed'
1545
+ ]);
1546
+ if (void 0 !== value) {
1547
+ ref.attributes = {
1548
+ ...ref.attributes,
1549
+ value
1550
+ };
1551
+ ref.text = (value || ref.attributes['placeholder'] || ref.text).slice(0, 80);
1552
+ }
1553
+ }
1554
+ }
1555
+ function filterSnapshotRefs(refs, predicate) {
1556
+ const refsByLabel = new Map(refs.map((ref)=>[
1557
+ ref.ref,
1558
+ ref
1559
+ ]));
1560
+ const retained = refs.filter(predicate);
1561
+ const retainedLabels = new Set(retained.map((ref)=>ref.ref));
1562
+ return retained.map((ref)=>{
1563
+ let parentRef = ref.parentRef;
1564
+ const visited = new Set();
1565
+ while(void 0 !== parentRef && !retainedLabels.has(parentRef)){
1566
+ if (visited.has(parentRef)) {
1567
+ parentRef = void 0;
1568
+ break;
1569
+ }
1570
+ visited.add(parentRef);
1571
+ parentRef = refsByLabel.get(parentRef)?.parentRef;
1572
+ }
1573
+ if (parentRef === ref.parentRef) return ref;
1574
+ const reparented = {
1575
+ ...ref
1576
+ };
1577
+ if (void 0 === parentRef) delete reparented.parentRef;
1578
+ else reparented.parentRef = parentRef;
1579
+ return reparented;
1580
+ });
1581
+ }
1582
+ async function buildSnapshotStructure(connector, clientId, sessionId, signal) {
1583
+ signal?.throwIfAborted();
1584
+ await connector.sendCDPMessage(clientId, sessionId, 'DOM.enable', {
1585
+ useCompression: false
1586
+ });
1587
+ signal?.throwIfAborted();
1588
+ const result = await connector.sendCDPMessage(clientId, sessionId, 'DOM.getDocumentWithBoxModel');
1589
+ signal?.throwIfAborted();
1590
+ if ('string' == typeof result.root) throw new Error('DOM.getDocumentWithBoxModel returned a compressed tree. Retry after DOM.enable with useCompression:false.');
1591
+ const viewport = deriveViewport(result.root);
1592
+ const refs = buildRefs(result.root, viewport);
1593
+ return {
1594
+ viewport,
1595
+ refs
1596
+ };
1597
+ }
1598
+ async function enrichSnapshot(connector, clientId, sessionId, snapshot, signal) {
1599
+ await refinePaintVisibility(connector, clientId, sessionId, snapshot.refs, signal);
1600
+ await enrichEditableValues(connector, clientId, sessionId, snapshot.refs, signal);
1601
+ return snapshot;
1602
+ }
1603
+ async function buildSnapshot(connector, clientId, sessionId, signal) {
1604
+ const snapshot = await buildSnapshotStructure(connector, clientId, sessionId, signal);
1605
+ return enrichSnapshot(connector, clientId, sessionId, snapshot, signal);
1606
+ }
1607
+ function normalizeRef(ref) {
1608
+ return ref.startsWith('@') ? ref : `@${ref}`;
1609
+ }
1610
+ function reasonResult(action, reason, message, nextActions) {
1611
+ return result_fail(action, message, {
1612
+ reason,
1613
+ recoverable: true,
1614
+ nextActions
1615
+ });
1616
+ }
1617
+ async function resolveBackendNodeId(connector, clientId, sessionId, backendNodeId, signal) {
1618
+ try {
1619
+ const result = await connector.sendCDPMessage(clientId, sessionId, 'DOM.pushNodesByBackendIdsToFrontend', {
1620
+ backendNodeIds: [
1621
+ backendNodeId
1622
+ ]
1623
+ });
1624
+ signal?.throwIfAborted();
1625
+ const nodeId = result.nodeIds?.[0];
1626
+ return void 0 !== nodeId && 0 !== nodeId ? nodeId : void 0;
1627
+ } catch {
1628
+ signal?.throwIfAborted();
1629
+ return;
1630
+ }
1631
+ }
1632
+ async function validateRef(action, connector, clientId, sessionId, ref, options = {}, signal) {
1633
+ signal?.throwIfAborted();
1634
+ if (ref.flags.offscreen) return reasonResult(action, 'offscreen', `Ref ${ref.ref} is offscreen; scroll it into view first.`, [
1635
+ `agent-lynx scroll ${ref.ref} --direction down`,
1636
+ 'agent-lynx snapshot'
1637
+ ]);
1638
+ if (ref.flags.disabled) return reasonResult(action, 'disabled', `Ref ${ref.ref} is disabled.`, [
1639
+ 'agent-lynx snapshot'
1640
+ ]);
1641
+ if (options.requireEditable && !ref.flags.editable) return reasonResult(action, 'not-editable', `Ref ${ref.ref} (${ref.tag}) is not an editable field.`, [
1642
+ 'agent-lynx snapshot'
1643
+ ]);
1644
+ const located = await connector.sendCDPMessage(clientId, sessionId, 'DOM.getNodeForLocation', {
1645
+ x: ref.center.x,
1646
+ y: ref.center.y
1647
+ });
1648
+ signal?.throwIfAborted();
1649
+ if (!located || (void 0 === located.nodeId || 0 === located.nodeId) && (void 0 === located.backendNodeId || 0 === located.backendNodeId)) return reasonResult(action, 'stale-ref', `Ref ${ref.ref} no longer resolves to a node.`, [
1650
+ 'agent-lynx snapshot'
1651
+ ]);
1652
+ let locatedNodeId = void 0 !== located.nodeId && 0 !== located.nodeId ? located.nodeId : void 0;
1653
+ if (void 0 === locatedNodeId && void 0 !== located.backendNodeId && 0 !== located.backendNodeId) locatedNodeId = await resolveBackendNodeId(connector, clientId, sessionId, located.backendNodeId, signal);
1654
+ const backendMatches = void 0 !== located.backendNodeId && 0 !== located.backendNodeId && located.backendNodeId === ref.backendNodeId;
1655
+ const frontendMatches = void 0 !== locatedNodeId && (locatedNodeId === ref.nodeId || ref[SNAPSHOT_REF_HIT_NODE_IDS]?.has(locatedNodeId) === true);
1656
+ if (!backendMatches && !frontendMatches) return reasonResult(action, 'covered', `Ref ${ref.ref} is covered: (${ref.center.x},${ref.center.y}) hit node ${locatedNodeId ?? `backend:${located.backendNodeId}`}, expected ${ref.nodeId}.`, [
1657
+ 'agent-lynx snapshot'
1658
+ ]);
1659
+ if (!ref.flags.visible) return reasonResult(action, 'not-visible', `Ref ${ref.ref} is not visible.`, [
1660
+ 'agent-lynx snapshot'
1661
+ ]);
1662
+ let liveNodeId = locatedNodeId === ref.nodeId || backendMatches ? locatedNodeId : void 0;
1663
+ if (void 0 === liveNodeId && options.requireEditable && void 0 !== ref.backendNodeId) liveNodeId = await resolveBackendNodeId(connector, clientId, sessionId, ref.backendNodeId, signal);
1664
+ if (options.requireEditable && void 0 === liveNodeId) return reasonResult(action, 'stale-ref', `Ref ${ref.ref} no longer resolves to a live editable node.`, [
1665
+ 'agent-lynx snapshot'
1666
+ ]);
1667
+ return {
1668
+ ok: true,
1669
+ nodeId: liveNodeId ?? ref.nodeId
1670
+ };
1671
+ }
1672
+ function selectEditableTextExpression(nodeId, selectionEnd) {
1673
+ const select = `(()=>{if(!lynx||typeof lynx.createSelectorQuery!=="function")return false;const query=lynx.createSelectorQuery();if(!query||typeof query.selectUniqueID!=="function")return false;query.selectUniqueID(${nodeId}).invoke({method:"setSelectionRange",params:{selectionStart:0,selectionEnd:${selectionEnd}}}).exec();return true})()`;
1674
+ return `(function(){var __a=globalThis.multiApps&&globalThis.multiApps[globalThis.currentDebugAppId||globalThis.currentAppId];var lynx=__a&&__a.lynx;return(${select});})()`;
1675
+ }
1676
+ async function selectEditableText(connector, clientId, sessionId, nodeId, selectionEnd, signal) {
1677
+ const result = await connector.sendCDPMessage(clientId, sessionId, 'Runtime.evaluate', {
1678
+ expression: selectEditableTextExpression(nodeId, selectionEnd),
1679
+ returnByValue: true
1680
+ });
1681
+ signal.throwIfAborted();
1682
+ if (void 0 !== result.exceptionDetails || result.result?.value !== true) throw new Error(`Unable to select the existing value for editable node ${nodeId}.`);
1683
+ await promises_setTimeout(50, void 0, {
1684
+ signal
1685
+ });
1686
+ }
1687
+ async function sendTouch(connector, clientId, sessionId, event) {
1688
+ await connector.sendCDPMessage(clientId, sessionId, 'Input.emulateTouchFromMouseEvent', {
1689
+ ...event
1690
+ });
1691
+ }
1692
+ async function withPressedTouch(connector, clientId, sessionId, pressPoint, releasePoint, signal, operation) {
1693
+ signal.throwIfAborted();
1694
+ let failed = false;
1695
+ let failure;
1696
+ try {
1697
+ await sendTouch(connector, clientId, sessionId, {
1698
+ type: 'mousePressed',
1699
+ x: pressPoint.x,
1700
+ y: pressPoint.y,
1701
+ timestamp: Date.now(),
1702
+ button: 'left',
1703
+ clickCount: 1
1704
+ });
1705
+ signal.throwIfAborted();
1706
+ await operation();
1707
+ } catch (error) {
1708
+ failed = true;
1709
+ failure = error;
1710
+ }
1711
+ try {
1712
+ await sendTouch(connector, clientId, sessionId, {
1713
+ type: 'mouseReleased',
1714
+ x: releasePoint.x,
1715
+ y: releasePoint.y,
1716
+ timestamp: Date.now(),
1717
+ button: 'left',
1718
+ clickCount: 1
1719
+ });
1720
+ } catch (error) {
1721
+ if (!failed) {
1722
+ failed = true;
1723
+ failure = error;
1724
+ }
1725
+ }
1726
+ if (failed) throw failure;
1727
+ }
1728
+ async function touchTap(connector, clientId, sessionId, point, signal) {
1729
+ await withPressedTouch(connector, clientId, sessionId, point, point, signal, async ()=>{
1730
+ signal.throwIfAborted();
1731
+ });
1732
+ }
1733
+ async function touchLongPress(connector, clientId, sessionId, point, durationMs, signal) {
1734
+ await withPressedTouch(connector, clientId, sessionId, point, point, signal, async ()=>{
1735
+ await promises_setTimeout(durationMs, void 0, {
1736
+ signal
1737
+ });
1738
+ });
1739
+ }
1740
+ async function touchSwipe(connector, clientId, sessionId, from, to, signal, steps = 8) {
1741
+ await withPressedTouch(connector, clientId, sessionId, from, to, signal, async ()=>{
1742
+ for(let i = 1; i <= steps; i++){
1743
+ signal.throwIfAborted();
1744
+ const progress = i / steps;
1745
+ await sendTouch(connector, clientId, sessionId, {
1746
+ type: 'mouseMoved',
1747
+ x: Math.round(from.x + (to.x - from.x) * progress),
1748
+ y: Math.round(from.y + (to.y - from.y) * progress),
1749
+ timestamp: Date.now(),
1750
+ button: 'left',
1751
+ clickCount: 1
1752
+ });
1753
+ await promises_setTimeout(16, void 0, {
1754
+ signal
1755
+ });
1756
+ }
1757
+ });
1758
+ }
1759
+ async function setValue(connector, clientId, sessionId, nodeId, value, signal, currentValue) {
1760
+ signal.throwIfAborted();
1761
+ await connector.sendCDPMessage(clientId, sessionId, 'DOM.focus', {
1762
+ nodeId
1763
+ });
1764
+ signal.throwIfAborted();
1765
+ if (void 0 !== currentValue && currentValue.length > 0) await selectEditableText(connector, clientId, sessionId, nodeId, currentValue.length, signal);
1766
+ await connector.sendCDPMessage(clientId, sessionId, 'Input.insertText', {
1767
+ text: value
1768
+ });
1769
+ signal.throwIfAborted();
1770
+ }
1771
+ function screenshot_ts_add_disposable_resource(env, value, async) {
1772
+ if (null != value) {
1773
+ if ("object" != typeof value && "function" != typeof value) throw new TypeError("Object expected.");
1774
+ var dispose, inner;
1775
+ if (async) {
1776
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
1777
+ dispose = value[Symbol.asyncDispose];
1778
+ }
1779
+ if (void 0 === dispose) {
1780
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
1781
+ dispose = value[Symbol.dispose];
1782
+ if (async) inner = dispose;
1783
+ }
1784
+ if ("function" != typeof dispose) throw new TypeError("Object not disposable.");
1785
+ if (inner) dispose = function() {
1786
+ try {
1787
+ inner.call(this);
1788
+ } catch (e) {
1789
+ return Promise.reject(e);
1790
+ }
1791
+ };
1792
+ env.stack.push({
1793
+ value: value,
1794
+ dispose: dispose,
1795
+ async: async
1796
+ });
1797
+ } else if (async) env.stack.push({
1798
+ async: true
1799
+ });
1800
+ return value;
1801
+ }
1802
+ function screenshot_ts_dispose_resources(env) {
1803
+ var _SuppressedError = "function" == typeof SuppressedError ? SuppressedError : function(error, suppressed, message) {
1804
+ var e = new Error(message);
1805
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1806
+ };
1807
+ return (screenshot_ts_dispose_resources = function(env) {
1808
+ function fail(e) {
1809
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
1810
+ env.hasError = true;
1811
+ }
1812
+ var r, s = 0;
1813
+ function next() {
1814
+ while(r = env.stack.pop())try {
1815
+ if (!r.async && 1 === s) return s = 0, env.stack.push(r), Promise.resolve().then(next);
1816
+ if (r.dispose) {
1817
+ var result = r.dispose.call(r.value);
1818
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
1819
+ fail(e);
1820
+ return next();
1821
+ });
1822
+ } else s |= 1;
1823
+ } catch (e) {
1824
+ fail(e);
1825
+ }
1826
+ if (1 === s) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
1827
+ if (env.hasError) throw env.error;
1828
+ }
1829
+ return next();
1830
+ })(env);
1831
+ }
1832
+ function deferred() {
1833
+ let resolve;
1834
+ const promise = new Promise((done)=>{
1835
+ resolve = done;
1836
+ });
1837
+ return {
1838
+ promise,
1839
+ resolve
1840
+ };
1841
+ }
1842
+ function combineSignals(signals) {
1843
+ const controller = new AbortController();
1844
+ const listeners = [];
1845
+ for (const signal of signals){
1846
+ if (signal.aborted) {
1847
+ controller.abort(signal.reason);
1848
+ break;
1849
+ }
1850
+ const listener = ()=>controller.abort(signal.reason);
1851
+ signal.addEventListener('abort', listener, {
1852
+ once: true
1853
+ });
1854
+ listeners.push({
1855
+ signal,
1856
+ listener
1857
+ });
1858
+ }
1859
+ return {
1860
+ signal: controller.signal,
1861
+ dispose () {
1862
+ for (const entry of listeners)entry.signal.removeEventListener('abort', entry.listener);
1863
+ }
1864
+ };
1865
+ }
1866
+ class ScreenshotTimeoutError extends Error {
1867
+ constructor(timeoutMs){
1868
+ super(`Failed to capture screenshot, no Page.screencastFrame event received within ${timeoutMs / 1000} seconds.`);
1869
+ this.name = 'ScreenshotTimeoutError';
1870
+ }
1871
+ }
1872
+ async function captureScreenshotFrame(connector, clientId, sessionId, options = {}) {
1873
+ const timeoutMs = options.timeoutMs ?? 10000;
1874
+ const timeoutController = new AbortController();
1875
+ const combinedSignal = options.signal ? combineSignals([
1876
+ options.signal,
1877
+ timeoutController.signal
1878
+ ]) : void 0;
1879
+ const signal = combinedSignal?.signal ?? timeoutController.signal;
1880
+ const timeout = setTimeout(()=>{
1881
+ timeoutController.abort(new ScreenshotTimeoutError(timeoutMs));
1882
+ }, timeoutMs);
1883
+ timeout.unref();
1884
+ const frame = deferred();
1885
+ const ack = deferred();
1886
+ const aborted = new Promise((_resolve, reject)=>{
1887
+ signal.addEventListener('abort', ()=>reject(signal.reason), {
1888
+ once: true
1889
+ });
1890
+ });
1891
+ try {
1892
+ const env = {
1893
+ stack: [],
1894
+ error: void 0,
1895
+ hasError: false
1896
+ };
1897
+ try {
1898
+ const stream = screenshot_ts_add_disposable_resource(env, await connector.sendCDPStream(clientId, sessionId, new ReadableStream({
1899
+ async start (controller) {
1900
+ try {
1901
+ controller.enqueue({
1902
+ method: 'Page.startScreencast',
1903
+ params: {
1904
+ format: 'jpeg',
1905
+ quality: options.quality ?? 80,
1906
+ mode: true === options.fullscreen ? 'fullscreen' : 'lynxview'
1907
+ }
1908
+ });
1909
+ await Promise.race([
1910
+ frame.promise,
1911
+ aborted
1912
+ ]);
1913
+ controller.enqueue({
1914
+ method: 'Page.screencastFrameAck'
1915
+ });
1916
+ } finally{
1917
+ controller.close();
1918
+ ack.resolve();
1919
+ }
1920
+ }
1921
+ }), {
1922
+ signal
1923
+ }), true);
1924
+ for await (const { method, params } of stream){
1925
+ if ('Page.screencastFrame' !== method) continue;
1926
+ const { data, metadata } = params;
1927
+ if ('string' == typeof data && 0 !== data.length) {
1928
+ frame.resolve();
1929
+ await ack.promise;
1930
+ return null !== metadata && 'object' == typeof metadata ? {
1931
+ data,
1932
+ metadata: metadata
1933
+ } : {
1934
+ data
1935
+ };
1936
+ }
1937
+ }
1938
+ const error = new ScreenshotTimeoutError(timeoutMs);
1939
+ timeoutController.abort(error);
1940
+ throw error;
1941
+ } catch (e) {
1942
+ env.error = e;
1943
+ env.hasError = true;
1944
+ } finally{
1945
+ const result = screenshot_ts_dispose_resources(env);
1946
+ if (result) await result;
1947
+ }
1948
+ } catch (error) {
1949
+ if (timeoutController.signal.aborted && options.signal?.aborted !== true) {
1950
+ const reason = timeoutController.signal.reason;
1951
+ if (reason instanceof ScreenshotTimeoutError) throw reason;
1952
+ }
1953
+ throw error;
1954
+ } finally{
1955
+ combinedSignal?.dispose();
1956
+ clearTimeout(timeout);
1957
+ }
1958
+ }
1959
+ async function captureScreenshot(connector, clientId, sessionId, options = {}) {
1960
+ return (await captureScreenshotFrame(connector, clientId, sessionId, options)).data;
1961
+ }
1962
+ class ScreenshotAnnotationError extends Error {
1963
+ constructor(message, options){
1964
+ super(message, options);
1965
+ this.name = 'ScreenshotAnnotationError';
1966
+ }
1967
+ }
1968
+ function screenshot_annotation_intersectBoxes(left, right) {
1969
+ const x = Math.max(left.x, right.x);
1970
+ const y = Math.max(left.y, right.y);
1971
+ const maxX = Math.min(left.x + left.width, right.x + right.width);
1972
+ const maxY = Math.min(left.y + left.height, right.y + right.height);
1973
+ if (maxX <= x || maxY <= y) return null;
1974
+ return {
1975
+ x,
1976
+ y,
1977
+ width: maxX - x,
1978
+ height: maxY - y
1979
+ };
1980
+ }
1981
+ function clamp(value, min, max) {
1982
+ return Math.min(max, Math.max(min, value));
1983
+ }
1984
+ const ANNOTATION_PALETTE = [
1985
+ [
1986
+ 230,
1987
+ 0,
1988
+ 82
1989
+ ],
1990
+ [
1991
+ 0,
1992
+ 130,
1993
+ 220
1994
+ ],
1995
+ [
1996
+ 242,
1997
+ 145,
1998
+ 0
1999
+ ],
2000
+ [
2001
+ 124,
2002
+ 77,
2003
+ 255
2004
+ ]
2005
+ ];
2006
+ function rgba(color, alpha) {
2007
+ return [
2008
+ color[0],
2009
+ color[1],
2010
+ color[2],
2011
+ alpha
2012
+ ];
2013
+ }
2014
+ function blendPixel(image, x, y, color) {
2015
+ if (x < 0 || y < 0 || x >= image.width || y >= image.height) return;
2016
+ const offset = (y * image.width + x) * 4;
2017
+ const alpha = color[3] / 255;
2018
+ image.data[offset] = Math.round(color[0] * alpha + image.data[offset] * (1 - alpha));
2019
+ image.data[offset + 1] = Math.round(color[1] * alpha + image.data[offset + 1] * (1 - alpha));
2020
+ image.data[offset + 2] = Math.round(color[2] * alpha + image.data[offset + 2] * (1 - alpha));
2021
+ image.data[offset + 3] = 255;
2022
+ }
2023
+ function fillRect(image, box, color) {
2024
+ const x = clamp(Math.floor(box.x), 0, image.width);
2025
+ const y = clamp(Math.floor(box.y), 0, image.height);
2026
+ const right = clamp(Math.ceil(box.x + box.width), 0, image.width);
2027
+ const bottom = clamp(Math.ceil(box.y + box.height), 0, image.height);
2028
+ for(let pixelY = y; pixelY < bottom; pixelY += 1)for(let pixelX = x; pixelX < right; pixelX += 1)blendPixel(image, pixelX, pixelY, color);
2029
+ }
2030
+ function strokeRect(image, box, thickness, color) {
2031
+ fillRect(image, {
2032
+ x: box.x,
2033
+ y: box.y,
2034
+ width: box.width,
2035
+ height: thickness
2036
+ }, color);
2037
+ fillRect(image, {
2038
+ x: box.x,
2039
+ y: box.y + box.height - thickness,
2040
+ width: box.width,
2041
+ height: thickness
2042
+ }, color);
2043
+ const verticalHeight = Math.max(0, box.height - 2 * thickness);
2044
+ fillRect(image, {
2045
+ x: box.x,
2046
+ y: box.y + thickness,
2047
+ width: thickness,
2048
+ height: verticalHeight
2049
+ }, color);
2050
+ fillRect(image, {
2051
+ x: box.x + box.width - thickness,
2052
+ y: box.y + thickness,
2053
+ width: thickness,
2054
+ height: verticalHeight
2055
+ }, color);
2056
+ }
2057
+ const GLYPHS = {
2058
+ 0: [
2059
+ '111',
2060
+ '101',
2061
+ '101',
2062
+ '101',
2063
+ '111'
2064
+ ],
2065
+ 1: [
2066
+ '010',
2067
+ '110',
2068
+ '010',
2069
+ '010',
2070
+ '111'
2071
+ ],
2072
+ 2: [
2073
+ '111',
2074
+ '001',
2075
+ '111',
2076
+ '100',
2077
+ '111'
2078
+ ],
2079
+ 3: [
2080
+ '111',
2081
+ '001',
2082
+ '111',
2083
+ '001',
2084
+ '111'
2085
+ ],
2086
+ 4: [
2087
+ '101',
2088
+ '101',
2089
+ '111',
2090
+ '001',
2091
+ '001'
2092
+ ],
2093
+ 5: [
2094
+ '111',
2095
+ '100',
2096
+ '111',
2097
+ '001',
2098
+ '111'
2099
+ ],
2100
+ 6: [
2101
+ '111',
2102
+ '100',
2103
+ '111',
2104
+ '101',
2105
+ '111'
2106
+ ],
2107
+ 7: [
2108
+ '111',
2109
+ '001',
2110
+ '010',
2111
+ '010',
2112
+ '010'
2113
+ ],
2114
+ 8: [
2115
+ '111',
2116
+ '101',
2117
+ '111',
2118
+ '101',
2119
+ '111'
2120
+ ],
2121
+ 9: [
2122
+ '111',
2123
+ '101',
2124
+ '111',
2125
+ '001',
2126
+ '111'
2127
+ ],
2128
+ '[': [
2129
+ '110',
2130
+ '100',
2131
+ '100',
2132
+ '100',
2133
+ '110'
2134
+ ],
2135
+ ']': [
2136
+ '011',
2137
+ '001',
2138
+ '001',
2139
+ '001',
2140
+ '011'
2141
+ ]
2142
+ };
2143
+ function labelMetrics(text, scale) {
2144
+ const padding = scale;
2145
+ const glyphWidth = 3 * scale;
2146
+ const glyphHeight = 5 * scale;
2147
+ const spacing = scale;
2148
+ const width = 2 * padding + text.length * glyphWidth + Math.max(0, text.length - 1) * spacing;
2149
+ const height = 2 * padding + glyphHeight;
2150
+ return {
2151
+ width,
2152
+ height,
2153
+ padding,
2154
+ glyphWidth,
2155
+ glyphHeight,
2156
+ spacing
2157
+ };
2158
+ }
2159
+ function drawLabel(image, text, box, scale, color) {
2160
+ const metrics = labelMetrics(text, scale);
2161
+ fillRect(image, box, rgba(color, 235));
2162
+ let cursorX = box.x + metrics.padding;
2163
+ for (const character of text){
2164
+ const glyph = GLYPHS[character];
2165
+ if (glyph) glyph.forEach((row, rowIndex)=>{
2166
+ for(let column = 0; column < row.length; column += 1)if ('1' === row[column]) fillRect(image, {
2167
+ x: cursorX + column * scale,
2168
+ y: box.y + metrics.padding + rowIndex * scale,
2169
+ width: scale,
2170
+ height: scale
2171
+ }, [
2172
+ 255,
2173
+ 255,
2174
+ 255,
2175
+ 255
2176
+ ]);
2177
+ });
2178
+ cursorX += metrics.glyphWidth + metrics.spacing;
2179
+ }
2180
+ }
2181
+ function annotationNumber(ref) {
2182
+ const match = /^@e([1-9]\d*)$/u.exec(ref);
2183
+ if (!match) return null;
2184
+ const number = Number.parseInt(match[1], 10);
2185
+ return Number.isSafeInteger(number) ? number : null;
2186
+ }
2187
+ function screenshot_annotation_annotationRole(ref) {
2188
+ const internalRole = ref[SNAPSHOT_REF_ANNOTATION_ROLE];
2189
+ if (void 0 !== internalRole) return internalRole;
2190
+ if (ref.flags.editable) return 'editable';
2191
+ if (ref.flags.scrollable) return 'scrollable';
2192
+ if (void 0 !== ref.attributes['lynx-test-tag']) return 'target';
2193
+ return 'generic';
2194
+ }
2195
+ function boxArea(box) {
2196
+ return Math.max(0, box.width) * Math.max(0, box.height);
2197
+ }
2198
+ function overlapArea(left, right) {
2199
+ const intersection = screenshot_annotation_intersectBoxes(left, right);
2200
+ return null === intersection ? 0 : boxArea(intersection);
2201
+ }
2202
+ function isAncestor(ancestorRef, descendant, refsByLabel) {
2203
+ const visited = new Set();
2204
+ let parentRef = descendant.parentRef;
2205
+ while(void 0 !== parentRef && !visited.has(parentRef)){
2206
+ if (parentRef === ancestorRef) return true;
2207
+ visited.add(parentRef);
2208
+ parentRef = refsByLabel.get(parentRef)?.parentRef;
2209
+ }
2210
+ return false;
2211
+ }
2212
+ function representsSameTarget(left, right, refsByLabel) {
2213
+ if (!isAncestor(left.ref.ref, right.ref, refsByLabel) && !isAncestor(right.ref.ref, left.ref, refsByLabel)) return false;
2214
+ const leftArea = boxArea(left.visibleBox);
2215
+ const rightArea = boxArea(right.visibleBox);
2216
+ const smallerArea = Math.min(leftArea, rightArea);
2217
+ const largerArea = Math.max(leftArea, rightArea);
2218
+ if (smallerArea <= 0 || largerArea <= 0) return false;
2219
+ return overlapArea(left.visibleBox, right.visibleBox) / smallerArea >= 0.95 && smallerArea / largerArea >= 0.7;
2220
+ }
2221
+ const ROLE_PRIORITY = {
2222
+ editable: 4,
2223
+ action: 3,
2224
+ target: 2,
2225
+ scrollable: 1
2226
+ };
2227
+ function selectAnnotationRefs(refs, viewport) {
2228
+ const refsByLabel = new Map(refs.map((ref)=>[
2229
+ ref.ref,
2230
+ ref
2231
+ ]));
2232
+ const candidates = [];
2233
+ for (const ref of refs){
2234
+ if (!ref.flags.interactive || !ref.flags.visible) continue;
2235
+ const number = annotationNumber(ref.ref);
2236
+ const visibleBox = screenshot_annotation_intersectBoxes(ref.box, viewport);
2237
+ const role = screenshot_annotation_annotationRole(ref);
2238
+ if (null !== number && null !== visibleBox && 'generic' !== role) candidates.push({
2239
+ ref,
2240
+ number,
2241
+ role,
2242
+ visibleBox
2243
+ });
2244
+ }
2245
+ const retained = [];
2246
+ for (const candidate of [
2247
+ ...candidates
2248
+ ].sort((left, right)=>ROLE_PRIORITY[right.role] - ROLE_PRIORITY[left.role] || boxArea(right.visibleBox) - boxArea(left.visibleBox) || left.number - right.number))if (!retained.some((existing)=>representsSameTarget(existing, candidate, refsByLabel))) retained.push(candidate);
2249
+ return [
2250
+ ...retained
2251
+ ].sort((left, right)=>left.number - right.number);
2252
+ }
2253
+ function isSignificantOverlap(left, right) {
2254
+ if (left.badgeOnly || right.badgeOnly) return false;
2255
+ const smallerArea = Math.min(boxArea(left.annotation.box), boxArea(right.annotation.box));
2256
+ return smallerArea > 0 && overlapArea(left.annotation.box, right.annotation.box) / smallerArea >= 0.1;
2257
+ }
2258
+ function assignAnnotationColors(entries) {
2259
+ const result = [];
2260
+ for (const entry of entries){
2261
+ const used = new Set(result.filter((existing)=>isSignificantOverlap(existing, {
2262
+ ...entry,
2263
+ colorIndex: 0
2264
+ })).map((existing)=>existing.colorIndex));
2265
+ const available = ANNOTATION_PALETTE.findIndex((_color, index)=>!used.has(index));
2266
+ result.push({
2267
+ ...entry,
2268
+ colorIndex: available >= 0 ? available : result.length % ANNOTATION_PALETTE.length
2269
+ });
2270
+ }
2271
+ return result;
2272
+ }
2273
+ function containedLabelBox(image, x, y, metrics) {
2274
+ return {
2275
+ x: clamp(Math.round(x), 0, Math.max(0, image.width - metrics.width)),
2276
+ y: clamp(Math.round(y), 0, Math.max(0, image.height - metrics.height)),
2277
+ width: metrics.width,
2278
+ height: metrics.height
2279
+ };
2280
+ }
2281
+ function uniqueBoxes(boxes) {
2282
+ const seen = new Set();
2283
+ return boxes.filter((box)=>{
2284
+ const key = `${box.x}:${box.y}:${box.width}:${box.height}`;
2285
+ if (seen.has(key)) return false;
2286
+ seen.add(key);
2287
+ return true;
2288
+ });
2289
+ }
2290
+ function placeLabel(image, target, metrics, occupiedLabels, blockedTargets, badgeOnly) {
2291
+ const left = target.x;
2292
+ const right = target.x + target.width - metrics.width;
2293
+ const above = target.y - metrics.height;
2294
+ const below = target.y + target.height;
2295
+ const insideTop = target.y;
2296
+ const insideBottom = target.y + target.height - metrics.height;
2297
+ const positions = badgeOnly ? [
2298
+ [
2299
+ right,
2300
+ insideTop
2301
+ ],
2302
+ [
2303
+ left,
2304
+ insideTop
2305
+ ],
2306
+ [
2307
+ right,
2308
+ insideBottom
2309
+ ],
2310
+ [
2311
+ left,
2312
+ insideBottom
2313
+ ]
2314
+ ] : [
2315
+ [
2316
+ left,
2317
+ above
2318
+ ],
2319
+ [
2320
+ right,
2321
+ above
2322
+ ],
2323
+ [
2324
+ left,
2325
+ below
2326
+ ],
2327
+ [
2328
+ right,
2329
+ below
2330
+ ],
2331
+ [
2332
+ left,
2333
+ insideTop
2334
+ ],
2335
+ [
2336
+ right,
2337
+ insideTop
2338
+ ]
2339
+ ];
2340
+ const boxes = uniqueBoxes(positions.map(([x, y])=>containedLabelBox(image, x, y, metrics)));
2341
+ return boxes.reduce((best, candidate, index)=>{
2342
+ const occupiedPenalty = 1000 * occupiedLabels.reduce((sum, box)=>sum + overlapArea(candidate, box), 0);
2343
+ const blockedPenalty = 5 * blockedTargets.reduce((sum, box)=>sum + overlapArea(candidate, box), 0);
2344
+ const ownTargetPenalty = overlapArea(candidate, target);
2345
+ const score = occupiedPenalty + blockedPenalty + ownTargetPenalty + index;
2346
+ return score < best.score ? {
2347
+ box: candidate,
2348
+ score
2349
+ } : best;
2350
+ }, {
2351
+ box: boxes[0],
2352
+ score: 1 / 0
2353
+ }).box;
2354
+ }
2355
+ function annotateScreenshot(options) {
2356
+ if (options.viewport.width <= 0 || options.viewport.height <= 0) throw new ScreenshotAnnotationError('The snapshot viewport must have positive dimensions.');
2357
+ if (!Number.isFinite(options.frame.x) || !Number.isFinite(options.frame.y) || !Number.isFinite(options.frame.width) || !Number.isFinite(options.frame.height) || options.frame.width <= 0 || options.frame.height <= 0) throw new ScreenshotAnnotationError('The screencast frame must have finite, positive bounds.');
2358
+ let image;
2359
+ try {
2360
+ image = __rspack_external_jpeg_js_11f36cdf.decode(options.jpeg, {
2361
+ useTArray: true,
2362
+ formatAsRGBA: true,
2363
+ maxResolutionInMP: 32,
2364
+ maxMemoryUsageInMB: 256
2365
+ });
2366
+ } catch (error) {
2367
+ throw new ScreenshotAnnotationError('The captured frame is not a decodable JPEG.', {
2368
+ cause: error
2369
+ });
2370
+ }
2371
+ if (image.width <= 0 || image.height <= 0) throw new ScreenshotAnnotationError('The captured JPEG has invalid dimensions.');
2372
+ const scaleX = image.width / options.frame.width;
2373
+ const scaleY = image.height / options.frame.height;
2374
+ const scaleDifference = Math.abs(scaleX - scaleY) / Math.max(scaleX, scaleY);
2375
+ if (scaleDifference > 0.02) throw new ScreenshotAnnotationError('The screencast frame metadata does not match the captured JPEG aspect ratio.');
2376
+ const entries = [];
2377
+ for (const candidate of selectAnnotationRefs(options.refs, options.viewport)){
2378
+ const { ref, number, role, visibleBox } = candidate;
2379
+ const frameVisibleBox = screenshot_annotation_intersectBoxes(visibleBox, options.frame);
2380
+ if (null === frameVisibleBox) continue;
2381
+ const x = clamp(Math.floor((frameVisibleBox.x - options.frame.x) * scaleX), 0, image.width);
2382
+ const y = clamp(Math.floor((frameVisibleBox.y - options.frame.y) * scaleY), 0, image.height);
2383
+ const right = clamp(Math.ceil((frameVisibleBox.x + frameVisibleBox.width - options.frame.x) * scaleX), 0, image.width);
2384
+ const bottom = clamp(Math.ceil((frameVisibleBox.y + frameVisibleBox.height - options.frame.y) * scaleY), 0, image.height);
2385
+ if (!(right <= x) && !(bottom <= y)) entries.push({
2386
+ annotation: {
2387
+ ref: ref.ref,
2388
+ number,
2389
+ tag: ref.tag,
2390
+ ...ref.text ? {
2391
+ text: ref.text
2392
+ } : {},
2393
+ box: {
2394
+ x,
2395
+ y,
2396
+ width: right - x,
2397
+ height: bottom - y
2398
+ }
2399
+ },
2400
+ badgeOnly: 'scrollable' === role && boxArea(visibleBox) / boxArea(options.viewport) >= 0.65
2401
+ });
2402
+ }
2403
+ const renderAnnotations = assignAnnotationColors(entries);
2404
+ const annotations = renderAnnotations.map((entry)=>entry.annotation);
2405
+ const deviceScale = Math.max(1, Math.min(scaleX, scaleY));
2406
+ const strokeWidth = clamp(Math.round(deviceScale), 2, 4);
2407
+ const glyphScale = clamp(Math.round(1.25 * deviceScale), 2, 4);
2408
+ for (const entry of renderAnnotations){
2409
+ if (entry.badgeOnly) continue;
2410
+ const color = ANNOTATION_PALETTE[entry.colorIndex];
2411
+ strokeRect(image, entry.annotation.box, strokeWidth, rgba(color, 220));
2412
+ }
2413
+ const blockedTargets = renderAnnotations.filter((entry)=>!entry.badgeOnly).map((entry)=>entry.annotation.box);
2414
+ const occupiedLabels = [];
2415
+ for (const entry of renderAnnotations){
2416
+ const text = `[${entry.annotation.number}]`;
2417
+ const metrics = labelMetrics(text, glyphScale);
2418
+ const ownTargetIndex = blockedTargets.indexOf(entry.annotation.box);
2419
+ const otherTargets = ownTargetIndex < 0 ? blockedTargets : blockedTargets.filter((_target, index)=>index !== ownTargetIndex);
2420
+ const labelBox = placeLabel(image, entry.annotation.box, metrics, occupiedLabels, otherTargets, entry.badgeOnly);
2421
+ drawLabel(image, text, labelBox, glyphScale, ANNOTATION_PALETTE[entry.colorIndex]);
2422
+ occupiedLabels.push(labelBox);
2423
+ }
2424
+ try {
2425
+ const encoded = __rspack_external_jpeg_js_11f36cdf.encode(image, options.quality ?? 90);
2426
+ return {
2427
+ jpeg: Buffer.from(encoded.data),
2428
+ width: image.width,
2429
+ height: image.height,
2430
+ annotations
2431
+ };
2432
+ } catch (error) {
2433
+ throw new ScreenshotAnnotationError('Failed to encode the annotated JPEG.', {
2434
+ cause: error
2435
+ });
2436
+ }
2437
+ }
2438
+ function stringParam(params, key) {
2439
+ const value = params[key];
2440
+ return 'string' == typeof value && '' !== value.trim() ? value.trim() : void 0;
2441
+ }
2442
+ function numberParam(params, key) {
2443
+ const value = params[key];
2444
+ if ('number' == typeof value && Number.isFinite(value)) return value;
2445
+ if ('string' == typeof value && '' !== value.trim()) {
2446
+ const parsed = Number(value);
2447
+ if (Number.isFinite(parsed)) return parsed;
2448
+ }
2449
+ }
2450
+ function isHeadlessClientId(clientId) {
2451
+ return clientId.startsWith('headless:');
2452
+ }
2453
+ function targetFailure(action, message, nextActions) {
2454
+ return result_fail(action, message, {
2455
+ reason: 'target-not-found',
2456
+ recoverable: true,
2457
+ nextActions
2458
+ });
2459
+ }
2460
+ async function resolveSessionTarget(action, params, connector) {
2461
+ let clientId = stringParam(params, 'clientId');
2462
+ if (void 0 !== params['clientId'] && !clientId) return {
2463
+ ok: false,
2464
+ result: result_fail(action, 'clientId must be a non-empty string when provided.', {
2465
+ reason: 'bad-params'
2466
+ })
2467
+ };
2468
+ if (!clientId) {
2469
+ const clients = await connector.listClients();
2470
+ const firstClient = clients.find((client)=>!isHeadlessClientId(client.id));
2471
+ if (!firstClient) {
2472
+ const headlessAvailable = clients.some((client)=>isHeadlessClientId(client.id));
2473
+ return {
2474
+ ok: false,
2475
+ result: targetFailure(action, headlessAvailable ? 'No real-device clients found. The built-in headless runtime is available but is never auto-selected.' : 'No available clients found.', headlessAvailable ? [
2476
+ 'Retry with an explicit headless client, for example `--client headless:0`.'
2477
+ ] : [
2478
+ 'Connect a Lynx client, then retry the command.',
2479
+ 'Run `agent-lynx list-clients` to verify discovery.'
2480
+ ])
2481
+ };
2482
+ }
2483
+ clientId = firstClient.id;
2484
+ }
2485
+ let sessionId = numberParam(params, 'sessionId');
2486
+ if (void 0 !== params['sessionId'] && void 0 === sessionId) return {
2487
+ ok: false,
2488
+ result: result_fail(action, 'sessionId must be a finite number when provided.', {
2489
+ reason: 'bad-params'
2490
+ })
2491
+ };
2492
+ if (void 0 === sessionId) {
2493
+ const sessions = await connector.sendListSessionMessage(clientId);
2494
+ if (0 === sessions.length) return {
2495
+ ok: false,
2496
+ result: targetFailure(action, isHeadlessClientId(clientId) ? `No sessions found for headless client ${clientId}. The headless runtime has no page open yet.` : `No available sessions found for client: ${clientId}`, isHeadlessClientId(clientId) ? [
2497
+ `Open a page first with \`agent-lynx open --client ${clientId} <url>\`.`
2498
+ ] : [
2499
+ `Open or reload a Lynx page on ${clientId}.`,
2500
+ `Run \`agent-lynx list-sessions --client ${clientId}\`.`
2501
+ ])
2502
+ };
2503
+ const latest = sessions.reduce((max, session)=>session.session_id > max.session_id ? session : max);
2504
+ sessionId = latest.session_id;
2505
+ }
2506
+ return {
2507
+ ok: true,
2508
+ params: {
2509
+ ...params,
2510
+ clientId,
2511
+ sessionId
2512
+ }
2513
+ };
2514
+ }
2515
+ function core_str(params, key) {
2516
+ const value = params[key];
2517
+ return 'string' == typeof value ? value : void 0;
2518
+ }
2519
+ function screencastFrameBounds(metadata) {
2520
+ const width = metadata?.deviceWidth;
2521
+ const height = metadata?.deviceHeight;
2522
+ if ('number' != typeof width || !Number.isFinite(width) || width <= 0 || 'number' != typeof height || !Number.isFinite(height) || height <= 0) return;
2523
+ return {
2524
+ x: 0,
2525
+ y: 0,
2526
+ width,
2527
+ height
2528
+ };
2529
+ }
2530
+ function num(params, key) {
2531
+ const value = params[key];
2532
+ if ('number' == typeof value && Number.isFinite(value)) return value;
2533
+ if ('string' == typeof value && '' !== value.trim()) {
2534
+ const parsed = Number(value);
2535
+ if (Number.isFinite(parsed)) return parsed;
2536
+ }
2537
+ }
2538
+ function bool(params, key) {
2539
+ const value = params[key];
2540
+ if ('boolean' == typeof value) return value;
2541
+ if ('string' != typeof value) return;
2542
+ if ('true' === value || '1' === value) return true;
2543
+ if ('false' === value || '0' === value) return false;
2544
+ }
2545
+ function strList(params, key) {
2546
+ const value = params[key];
2547
+ if (Array.isArray(value)) return value.filter((item)=>'string' == typeof item);
2548
+ if ('string' == typeof value) return value.split(',').map((item)=>item.trim()).filter(Boolean);
2549
+ }
2550
+ function invalidNumber(params, key) {
2551
+ return Object.hasOwn(params, key) && void 0 === num(params, key);
2552
+ }
2553
+ function invalidBoolean(params, key) {
2554
+ return Object.hasOwn(params, key) && void 0 === bool(params, key);
2555
+ }
2556
+ function isUnsupportedCdpMethod(error) {
2557
+ if (!(error instanceof Error) || 'object' != typeof error.cause || null === error.cause) return false;
2558
+ const response = error.cause;
2559
+ return response.error?.code === -32601;
2560
+ }
2561
+ function sameSnapshotNode(left, right) {
2562
+ if (void 0 !== left.backendNodeId && void 0 !== right.backendNodeId) return left.backendNodeId === right.backendNodeId;
2563
+ return left.nodeId === right.nodeId;
2564
+ }
2565
+ const WAIT_DEADLINE = Symbol('waitDeadline');
2566
+ async function runBeforeDeadline(deadline, signal, operation) {
2567
+ const remaining = deadline - Date.now();
2568
+ if (remaining <= 0) return WAIT_DEADLINE;
2569
+ const operationController = new AbortController();
2570
+ const timerController = new AbortController();
2571
+ const operationSignal = AbortSignal.any([
2572
+ signal,
2573
+ operationController.signal
2574
+ ]);
2575
+ const timerSignal = AbortSignal.any([
2576
+ signal,
2577
+ timerController.signal
2578
+ ]);
2579
+ const operationPromise = operation(operationSignal);
2580
+ const timeoutPromise = promises_setTimeout(remaining, WAIT_DEADLINE, {
2581
+ signal: timerSignal
2582
+ });
2583
+ try {
2584
+ return await Promise.race([
2585
+ operationPromise,
2586
+ timeoutPromise
2587
+ ]);
2588
+ } finally{
2589
+ operationController.abort(new Error('Wait deadline elapsed.'));
2590
+ timerController.abort();
2591
+ await timeoutPromise.catch(()=>{});
2592
+ }
2593
+ }
2594
+ function gestureBox(box, viewport) {
2595
+ if (!viewport) return box;
2596
+ const x = Math.max(box.x, viewport.x);
2597
+ const y = Math.max(box.y, viewport.y);
2598
+ const right = Math.min(box.x + box.width, viewport.x + viewport.width);
2599
+ const bottom = Math.min(box.y + box.height, viewport.y + viewport.height);
2600
+ return right > x && bottom > y ? {
2601
+ x,
2602
+ y,
2603
+ width: right - x,
2604
+ height: bottom - y
2605
+ } : box;
2606
+ }
2607
+ function gestureAxis(start, size) {
2608
+ const rawMin = Math.ceil(start);
2609
+ const rawMax = Math.max(rawMin, Math.ceil(start + size) - 1);
2610
+ const inset = rawMax - rawMin >= 4 ? 1 : 0;
2611
+ return {
2612
+ min: rawMin + inset,
2613
+ max: rawMax - inset
2614
+ };
2615
+ }
2616
+ function swipeForDirection(box, direction, viewport) {
2617
+ const visibleBox = gestureBox(box, viewport);
2618
+ const x = gestureAxis(visibleBox.x, visibleBox.width);
2619
+ const y = gestureAxis(visibleBox.y, visibleBox.height);
2620
+ const centerX = Math.round((x.min + x.max) / 2);
2621
+ const centerY = Math.round((y.min + y.max) / 2);
2622
+ const edgeLaneX = Math.round(x.min + (x.max - x.min) * 0.05);
2623
+ const edgeLaneY = Math.round(y.min + (y.max - y.min) * 0.05);
2624
+ const deltaX = Math.max(1, Math.round((x.max - x.min) * 0.3));
2625
+ const deltaY = Math.max(1, Math.round((y.max - y.min) * 0.3));
2626
+ switch(direction){
2627
+ case 'down':
2628
+ return {
2629
+ from: {
2630
+ x: edgeLaneX,
2631
+ y: centerY + deltaY
2632
+ },
2633
+ to: {
2634
+ x: edgeLaneX,
2635
+ y: centerY - deltaY
2636
+ }
2637
+ };
2638
+ case 'up':
2639
+ return {
2640
+ from: {
2641
+ x: edgeLaneX,
2642
+ y: centerY - deltaY
2643
+ },
2644
+ to: {
2645
+ x: edgeLaneX,
2646
+ y: centerY + deltaY
2647
+ }
2648
+ };
2649
+ case 'left':
2650
+ return {
2651
+ from: {
2652
+ x: centerX + deltaX,
2653
+ y: edgeLaneY
2654
+ },
2655
+ to: {
2656
+ x: centerX - deltaX,
2657
+ y: edgeLaneY
2658
+ }
2659
+ };
2660
+ case 'right':
2661
+ return {
2662
+ from: {
2663
+ x: centerX - deltaX,
2664
+ y: edgeLaneY
2665
+ },
2666
+ to: {
2667
+ x: centerX + deltaX,
2668
+ y: edgeLaneY
2669
+ }
2670
+ };
2671
+ }
2672
+ }
2673
+ class ActionCore {
2674
+ #snapshots = new Map();
2675
+ #reactLynx = new ReactLynxController();
2676
+ #handlers = new Map();
2677
+ constructor(){
2678
+ this.#register('snapshot', (params, ctx, signal)=>this.#snapshot(params, ctx, signal));
2679
+ this.#register('screenshot', (params, ctx, signal)=>this.#screenshot(params, ctx, signal));
2680
+ this.#register('tap', (params, ctx, signal)=>this.#tap(params, ctx, signal));
2681
+ this.#register('long-press', (params, ctx, signal)=>this.#longPress(params, ctx, signal));
2682
+ this.#register('fill', (params, ctx, signal)=>this.#fill(params, ctx, signal));
2683
+ this.#register('clear', (params, ctx, signal)=>this.#clear(params, ctx, signal));
2684
+ this.#register('scroll', (params, ctx, signal)=>this.#scroll(params, ctx, signal));
2685
+ this.#register('get-text', (params, ctx, signal)=>this.#getText(params, ctx, signal));
2686
+ this.#register('get-style', (params, ctx, signal)=>this.#getStyle(params, ctx, signal));
2687
+ this.#register('wait', (params, ctx, signal)=>this.#wait(params, ctx, signal));
2688
+ this.#register('reactlynx-tree', (params, ctx, signal)=>this.#reactLynxTree(params, ctx, signal));
2689
+ this.#register('reactlynx-find', (params, ctx, signal)=>this.#reactLynxFind(params, ctx, signal));
2690
+ this.#register('reactlynx-component', (params, ctx, signal)=>this.#reactLynxComponent(params, ctx, signal));
2691
+ this.#register('reactlynx-link', (params, ctx, signal)=>this.#reactLynxLink(params, ctx, signal));
2692
+ this.#register('reactlynx-update-prop', (params, ctx, signal)=>this.#reactLynxUpdate('reactlynx-update-prop', 'update-prop', params, ctx, signal));
2693
+ this.#register('reactlynx-update-state', (params, ctx, signal)=>this.#reactLynxUpdate('reactlynx-update-state', 'update-state', params, ctx, signal));
2694
+ this.#register('reactlynx-update-context', (params, ctx, signal)=>this.#reactLynxUpdate('reactlynx-update-context', 'update-context', params, ctx, signal));
2695
+ }
2696
+ has(action) {
2697
+ return this.#handlers.has(action);
2698
+ }
2699
+ hasStream(action) {
2700
+ return 'wait' === action;
2701
+ }
2702
+ actions() {
2703
+ return [
2704
+ ...this.#handlers.keys()
2705
+ ].sort();
2706
+ }
2707
+ streamActions() {
2708
+ return [
2709
+ 'wait'
2710
+ ];
2711
+ }
2712
+ async execute(action, params, ctx, signal) {
2713
+ const registration = this.#handlers.get(action);
2714
+ if (!registration) return result_fail(action, `Unknown command action: ${action}`, {
2715
+ reason: 'unknown-action',
2716
+ nextActions: this.actions().map((name)=>`POST /command/${name}`)
2717
+ });
2718
+ const actionSignal = signal ?? new AbortController().signal;
2719
+ try {
2720
+ actionSignal.throwIfAborted();
2721
+ const target = await resolveSessionTarget(action, params, ctx.connector);
2722
+ if (!target.ok) return target.result;
2723
+ if ([
2724
+ 'tap',
2725
+ 'long-press',
2726
+ 'fill',
2727
+ 'clear',
2728
+ 'scroll'
2729
+ ].includes(action) && invalidBoolean(target.params, 'snapshotAfter')) return result_fail(action, 'snapshotAfter must be a boolean when provided.', {
2730
+ reason: 'bad-params'
2731
+ });
2732
+ return await registration.handler(target.params, ctx, actionSignal);
2733
+ } catch (error) {
2734
+ if (actionSignal.aborted) return result_fail(action, 'Command was aborted.', {
2735
+ cause: actionSignal.reason,
2736
+ reason: 'aborted',
2737
+ recoverable: true
2738
+ });
2739
+ if (error instanceof ReactLynxActionError) return result_fail(action, error.message, {
2740
+ reason: error.reason,
2741
+ recoverable: error.recoverable,
2742
+ nextActions: error.nextActions
2743
+ });
2744
+ return result_fail(action, error instanceof Error ? error.message : String(error), {
2745
+ cause: error,
2746
+ recoverable: true,
2747
+ nextActions: [
2748
+ 'agent-lynx list-clients',
2749
+ 'agent-lynx list-sessions'
2750
+ ]
2751
+ });
2752
+ }
2753
+ }
2754
+ async *stream(action, params, ctx, signal) {
2755
+ if (!this.hasStream(action)) return void (yield result_fail(action, `Unknown stream action: ${action}`, {
2756
+ reason: 'unknown-action',
2757
+ nextActions: this.streamActions().map((name)=>`GET /command/${name}`)
2758
+ }));
2759
+ try {
2760
+ signal.throwIfAborted();
2761
+ const target = await resolveSessionTarget(action, params, ctx.connector);
2762
+ if (!target.ok) return void (yield target.result);
2763
+ yield* this.#waitStream(target.params, ctx, signal, true);
2764
+ } catch (error) {
2765
+ if (signal.aborted) return;
2766
+ yield result_fail(action, error instanceof Error ? error.message : String(error), {
2767
+ cause: error,
2768
+ recoverable: true
2769
+ });
2770
+ }
2771
+ }
2772
+ #register(action, handler) {
2773
+ this.#handlers.set(action, {
2774
+ handler: handler
2775
+ });
2776
+ }
2777
+ #key(clientId, sessionId) {
2778
+ return `${clientId}:${sessionId}`;
2779
+ }
2780
+ getSnapshot(clientId, sessionId) {
2781
+ return this.#snapshots.get(this.#key(clientId, sessionId));
2782
+ }
2783
+ getReactLynxCache(clientId, sessionId) {
2784
+ return this.#reactLynx.getCache(clientId, sessionId);
2785
+ }
2786
+ async #reactLynxTree(params, ctx, signal) {
2787
+ const clientId = core_str(params, 'clientId');
2788
+ const sessionId = num(params, 'sessionId');
2789
+ if (!clientId || void 0 === sessionId) return result_fail('reactlynx-tree', 'clientId and sessionId are required.', {
2790
+ reason: 'bad-params'
2791
+ });
2792
+ if (invalidBoolean(params, 'showShells')) return result_fail('reactlynx-tree', 'showShells must be a boolean when provided.', {
2793
+ reason: 'bad-params'
2794
+ });
2795
+ const depth = num(params, 'depth');
2796
+ if (Object.hasOwn(params, 'depth') && void 0 === depth || void 0 !== depth && (!Number.isInteger(depth) || depth < 1)) return result_fail('reactlynx-tree', 'depth must be a positive integer when provided.', {
2797
+ reason: 'bad-params'
2798
+ });
2799
+ const data = await this.#reactLynx.tree(ctx.connector, {
2800
+ clientId,
2801
+ sessionId
2802
+ }, {
2803
+ ...void 0 === depth ? {} : {
2804
+ depth
2805
+ },
2806
+ showShells: true === bool(params, 'showShells')
2807
+ }, signal);
2808
+ return ok('reactlynx-tree', data);
2809
+ }
2810
+ async #reactLynxFind(params, ctx, signal) {
2811
+ const clientId = core_str(params, 'clientId');
2812
+ const sessionId = num(params, 'sessionId');
2813
+ const pattern = params['pattern'];
2814
+ if (!clientId || void 0 === sessionId || 'string' != typeof pattern) return result_fail('reactlynx-find', 'clientId, sessionId, and a string pattern are required.', {
2815
+ reason: 'bad-params'
2816
+ });
2817
+ for (const key of [
2818
+ 'regex',
2819
+ 'showShells',
2820
+ 'refresh'
2821
+ ])if (invalidBoolean(params, key)) return result_fail('reactlynx-find', `${key} must be a boolean when provided.`, {
2822
+ reason: 'bad-params'
2823
+ });
2824
+ const parsedLimit = num(params, 'limit');
2825
+ if (Object.hasOwn(params, 'limit') && void 0 === parsedLimit) return result_fail('reactlynx-find', 'limit must be a positive integer when provided.', {
2826
+ reason: 'bad-params'
2827
+ });
2828
+ const limit = parsedLimit ?? 50;
2829
+ if (!Number.isInteger(limit) || limit < 1) return result_fail('reactlynx-find', 'limit must be a positive integer when provided.', {
2830
+ reason: 'bad-params'
2831
+ });
2832
+ const data = await this.#reactLynx.find(ctx.connector, {
2833
+ clientId,
2834
+ sessionId
2835
+ }, {
2836
+ pattern,
2837
+ regex: true === bool(params, 'regex'),
2838
+ showShells: true === bool(params, 'showShells'),
2839
+ limit,
2840
+ refresh: true === bool(params, 'refresh')
2841
+ }, signal);
2842
+ return ok('reactlynx-find', data);
2843
+ }
2844
+ async #reactLynxComponent(params, ctx, signal) {
2845
+ const clientId = core_str(params, 'clientId');
2846
+ const sessionId = num(params, 'sessionId');
2847
+ const ref = core_str(params, 'ref')?.trim();
2848
+ if (!clientId || void 0 === sessionId || !ref) return result_fail('reactlynx-component', 'clientId, sessionId, and a non-empty ref are required.', {
2849
+ reason: 'bad-params'
2850
+ });
2851
+ for (const key of [
2852
+ 'showShells',
2853
+ 'refresh'
2854
+ ])if (invalidBoolean(params, key)) return result_fail('reactlynx-component', `${key} must be a boolean when provided.`, {
2855
+ reason: 'bad-params'
2856
+ });
2857
+ const data = await this.#reactLynx.component(ctx.connector, {
2858
+ clientId,
2859
+ sessionId
2860
+ }, {
2861
+ ref,
2862
+ showShells: true === bool(params, 'showShells'),
2863
+ refresh: true === bool(params, 'refresh')
2864
+ }, signal);
2865
+ return ok('reactlynx-component', data);
2866
+ }
2867
+ async #reactLynxLink(params, ctx, signal) {
2868
+ const clientId = core_str(params, 'clientId');
2869
+ const sessionId = num(params, 'sessionId');
2870
+ const rawRef = core_str(params, 'ref')?.trim();
2871
+ if (!clientId || void 0 === sessionId || !rawRef) return result_fail('reactlynx-link', 'clientId, sessionId, and a non-empty ref are required.', {
2872
+ reason: 'bad-params'
2873
+ });
2874
+ for (const key of [
2875
+ 'showShells',
2876
+ 'refresh'
2877
+ ])if (invalidBoolean(params, key)) return result_fail('reactlynx-link', `${key} must be a boolean when provided.`, {
2878
+ reason: 'bad-params'
2879
+ });
2880
+ let ref;
2881
+ try {
2882
+ ref = parseReactLynxLinkRef(rawRef);
2883
+ } catch (error) {
2884
+ return result_fail('reactlynx-link', error instanceof Error ? error.message : String(error), {
2885
+ reason: 'bad-params'
2886
+ });
2887
+ }
2888
+ const target = {
2889
+ clientId,
2890
+ sessionId
2891
+ };
2892
+ const showShells = true === bool(params, 'showShells');
2893
+ const refresh = true === bool(params, 'refresh');
2894
+ if ('element' === ref.kind) {
2895
+ const resolved = this.#resolveRef('reactlynx-link', clientId, sessionId, ref.ref);
2896
+ if ('ok' in resolved) return resolved;
2897
+ const mapping = await this.#reactLynx.componentForElement(ctx.connector, target, {
2898
+ uniqueId: resolved.ref.backendNodeId ?? resolved.ref.nodeId,
2899
+ showShells,
2900
+ refresh
2901
+ }, signal);
2902
+ return ok('reactlynx-link', {
2903
+ ...target,
2904
+ cache: mapping.cache,
2905
+ direction: 'element-to-component',
2906
+ relation: 'nearest-component',
2907
+ element: resolved.ref,
2908
+ component: mapping.component
2909
+ });
2910
+ }
2911
+ const snapshot = this.#snapshots.get(this.#key(clientId, sessionId));
2912
+ if (!snapshot) return result_fail('reactlynx-link', `No snapshot found for ${clientId} session ${sessionId}.`, {
2913
+ reason: 'no-snapshot',
2914
+ recoverable: true,
2915
+ nextActions: [
2916
+ 'agent-lynx snapshot'
2917
+ ]
2918
+ });
2919
+ const componentRef = 'component-label' === ref.kind ? `@c${ref.index}` : String(ref.id);
2920
+ const mapping = await this.#reactLynx.elementForComponent(ctx.connector, target, {
2921
+ ref: componentRef,
2922
+ showShells,
2923
+ refresh
2924
+ }, signal);
2925
+ const element = snapshot.refs.find((candidate)=>(candidate.backendNodeId ?? candidate.nodeId) === mapping.uniqueId);
2926
+ if (!element) return result_fail('reactlynx-link', `No snapshot ref matches host uniqueId ${mapping.uniqueId} for ${componentRef}. The DOM snapshot may be stale, filtered, or the host element may not be surfaced.`, {
2927
+ reason: 'ref-not-found',
2928
+ recoverable: true,
2929
+ nextActions: [
2930
+ 'Run `agent-lynx snapshot`, then retry the link.'
2931
+ ]
2932
+ });
2933
+ return ok('reactlynx-link', {
2934
+ ...target,
2935
+ cache: mapping.cache,
2936
+ direction: 'component-to-element',
2937
+ relation: 'first-host-element',
2938
+ element,
2939
+ component: mapping.component
2940
+ });
2941
+ }
2942
+ async #reactLynxUpdate(action, kind, params, ctx, signal) {
2943
+ const clientId = core_str(params, 'clientId');
2944
+ const sessionId = num(params, 'sessionId');
2945
+ const ref = core_str(params, 'ref')?.trim();
2946
+ const path = core_str(params, 'path');
2947
+ if (!clientId || void 0 === sessionId || !ref || void 0 === path || !Object.hasOwn(params, 'value')) return result_fail(action, 'clientId, sessionId, ref, path, and value are required.', {
2948
+ reason: 'bad-params'
2949
+ });
2950
+ for (const key of [
2951
+ 'showShells',
2952
+ 'refresh'
2953
+ ])if (invalidBoolean(params, key)) return result_fail(action, `${key} must be a boolean when provided.`, {
2954
+ reason: 'bad-params'
2955
+ });
2956
+ const data = await this.#reactLynx.update(ctx.connector, {
2957
+ clientId,
2958
+ sessionId
2959
+ }, {
2960
+ kind,
2961
+ ref,
2962
+ path,
2963
+ value: params['value'],
2964
+ showShells: true === bool(params, 'showShells'),
2965
+ refresh: true === bool(params, 'refresh')
2966
+ }, signal);
2967
+ return ok(action, data);
2968
+ }
2969
+ async #withSnapshotAfter(action, params, ctx, clientId, sessionId, data, signal) {
2970
+ if (invalidBoolean(params, 'snapshotAfter')) return result_fail(action, 'snapshotAfter must be a boolean when provided.', {
2971
+ reason: 'bad-params'
2972
+ });
2973
+ if (true !== bool(params, 'snapshotAfter')) return ok(action, data);
2974
+ try {
2975
+ const { viewport, refs } = await buildSnapshot(ctx.connector, clientId, sessionId, signal);
2976
+ this.#snapshots.set(this.#key(clientId, sessionId), {
2977
+ createdAt: Date.now(),
2978
+ viewport,
2979
+ refs
2980
+ });
2981
+ return ok(action, {
2982
+ ...data,
2983
+ snapshot: {
2984
+ clientId,
2985
+ sessionId,
2986
+ viewport,
2987
+ refs
2988
+ }
2989
+ });
2990
+ } catch (error) {
2991
+ const snapshotError = {
2992
+ message: error instanceof Error ? error.message : String(error),
2993
+ recoverable: true,
2994
+ nextActions: [
2995
+ 'agent-lynx snapshot'
2996
+ ]
2997
+ };
2998
+ if (error instanceof Error && void 0 !== error.cause) snapshotError.cause = String(error.cause);
2999
+ return ok(action, {
3000
+ ...data,
3001
+ snapshotError
3002
+ });
3003
+ }
3004
+ }
3005
+ async #snapshot(params, ctx, signal) {
3006
+ const clientId = core_str(params, 'clientId');
3007
+ const sessionId = num(params, 'sessionId');
3008
+ if (!clientId || void 0 === sessionId) return result_fail('snapshot', 'clientId and sessionId are required.', {
3009
+ reason: 'bad-params'
3010
+ });
3011
+ if (invalidBoolean(params, 'visibleOnly')) return result_fail('snapshot', 'visibleOnly must be a boolean when provided.', {
3012
+ reason: 'bad-params'
3013
+ });
3014
+ const { viewport, refs: allRefs } = await buildSnapshot(ctx.connector, clientId, sessionId, signal);
3015
+ const refs = true === bool(params, 'visibleOnly') ? filterSnapshotRefs(allRefs, (ref)=>ref.flags.visible) : allRefs;
3016
+ this.#snapshots.set(this.#key(clientId, sessionId), {
3017
+ createdAt: Date.now(),
3018
+ viewport,
3019
+ refs
3020
+ });
3021
+ return ok('snapshot', {
3022
+ clientId,
3023
+ sessionId,
3024
+ viewport,
3025
+ refs
3026
+ });
3027
+ }
3028
+ async #screenshot(params, ctx, signal) {
3029
+ const clientId = core_str(params, 'clientId');
3030
+ const sessionId = num(params, 'sessionId');
3031
+ if (!clientId || void 0 === sessionId) return result_fail('screenshot', 'clientId and sessionId are required.', {
3032
+ reason: 'bad-params'
3033
+ });
3034
+ if (invalidBoolean(params, 'fullscreen') || invalidBoolean(params, 'annotate')) return result_fail('screenshot', 'fullscreen and annotate must be booleans when provided.', {
3035
+ reason: 'bad-params'
3036
+ });
3037
+ const fullscreen = true === bool(params, 'fullscreen');
3038
+ const annotate = true === bool(params, 'annotate');
3039
+ if (fullscreen && annotate) return result_fail('screenshot', '--fullscreen cannot be combined with --annotate.', {
3040
+ reason: 'unsupported-option',
3041
+ recoverable: true,
3042
+ nextActions: [
3043
+ 'Remove --fullscreen to annotate the LynxView viewport.',
3044
+ 'Use `agent-lynx take-screenshot --fullscreen` for an unannotated fullscreen image.'
3045
+ ]
3046
+ });
3047
+ try {
3048
+ const capturedFrame = await captureScreenshotFrame(ctx.connector, clientId, sessionId, {
3049
+ fullscreen,
3050
+ quality: annotate ? 100 : 80,
3051
+ signal
3052
+ });
3053
+ const jpegBase64 = capturedFrame.data;
3054
+ let snapshot;
3055
+ let frameBounds;
3056
+ if (annotate) {
3057
+ frameBounds = screencastFrameBounds(capturedFrame.metadata);
3058
+ if (!frameBounds) return result_fail('screenshot', 'The captured frame has no usable logical-size metadata for annotation.', {
3059
+ reason: 'invalid-screenshot',
3060
+ recoverable: true,
3061
+ nextActions: [
3062
+ 'Retry with a Lynx runtime that provides Page.screencastFrame metadata.',
3063
+ 'Use `agent-lynx screenshot` without --annotate for an unannotated image.'
3064
+ ]
3065
+ });
3066
+ const { viewport, refs } = await buildSnapshot(ctx.connector, clientId, sessionId, signal);
3067
+ if (!viewport || viewport.width <= 0 || viewport.height <= 0) return result_fail('screenshot', 'The current snapshot has no usable viewport for screenshot annotation.', {
3068
+ reason: 'unsupported-target',
3069
+ recoverable: true,
3070
+ nextActions: [
3071
+ 'Verify the target page exposes DOM box models, then retry.',
3072
+ 'Use `agent-lynx take-screenshot` for an unannotated image.'
3073
+ ]
3074
+ });
3075
+ snapshot = {
3076
+ clientId,
3077
+ sessionId,
3078
+ viewport,
3079
+ refs
3080
+ };
3081
+ this.#snapshots.set(this.#key(clientId, sessionId), {
3082
+ createdAt: Date.now(),
3083
+ viewport,
3084
+ refs
3085
+ });
3086
+ }
3087
+ let annotated;
3088
+ if (snapshot?.viewport && frameBounds) try {
3089
+ annotated = annotateScreenshot({
3090
+ jpeg: Buffer.from(jpegBase64, 'base64'),
3091
+ refs: snapshot.refs,
3092
+ frame: frameBounds,
3093
+ viewport: snapshot.viewport
3094
+ });
3095
+ } catch (error) {
3096
+ if (!(error instanceof ScreenshotAnnotationError)) throw error;
3097
+ return result_fail('screenshot', error.message, {
3098
+ reason: 'invalid-screenshot',
3099
+ recoverable: true,
3100
+ nextActions: [
3101
+ 'Retry the screenshot after refreshing the target page.'
3102
+ ]
3103
+ });
3104
+ }
3105
+ return ok('screenshot', {
3106
+ clientId,
3107
+ sessionId,
3108
+ jpegBase64: annotated?.jpeg.toString('base64') ?? jpegBase64,
3109
+ ...annotated ? {
3110
+ width: annotated.width,
3111
+ height: annotated.height
3112
+ } : {},
3113
+ ...snapshot ? {
3114
+ snapshot
3115
+ } : {},
3116
+ ...annotated ? {
3117
+ annotations: annotated.annotations
3118
+ } : {}
3119
+ });
3120
+ } catch (error) {
3121
+ if (!(error instanceof ScreenshotTimeoutError)) throw error;
3122
+ return result_fail('screenshot', error.message, {
3123
+ reason: 'timeout',
3124
+ recoverable: true,
3125
+ nextActions: [
3126
+ 'Verify the target app is foregrounded and rendering.',
3127
+ 'Retry `agent-lynx screenshot` after opening or refreshing the page.'
3128
+ ]
3129
+ });
3130
+ }
3131
+ }
3132
+ #resolveRef(action, clientId, sessionId, rawRef) {
3133
+ const refLabel = normalizeRef(rawRef);
3134
+ const snapshot = this.#snapshots.get(this.#key(clientId, sessionId));
3135
+ if (!snapshot) return result_fail(action, `No snapshot found for ${clientId} session ${sessionId}.`, {
3136
+ reason: 'no-snapshot',
3137
+ recoverable: true,
3138
+ nextActions: [
3139
+ 'agent-lynx snapshot'
3140
+ ]
3141
+ });
3142
+ const ref = snapshot.refs.find((candidate)=>candidate.ref === refLabel);
3143
+ if (!ref) return result_fail(action, `Ref ${refLabel} was not found in the latest snapshot.`, {
3144
+ reason: 'ref-not-found',
3145
+ recoverable: true,
3146
+ nextActions: [
3147
+ 'agent-lynx snapshot'
3148
+ ]
3149
+ });
3150
+ return {
3151
+ ref,
3152
+ snapshot
3153
+ };
3154
+ }
3155
+ async #tap(params, ctx, signal) {
3156
+ const clientId = core_str(params, 'clientId');
3157
+ const sessionId = num(params, 'sessionId');
3158
+ const rawRef = core_str(params, 'ref');
3159
+ if (!clientId || void 0 === sessionId || !rawRef) return result_fail('tap', 'clientId, sessionId and ref are required.', {
3160
+ reason: 'bad-params'
3161
+ });
3162
+ const resolved = this.#resolveRef('tap', clientId, sessionId, rawRef);
3163
+ if ('ok' in resolved) return resolved;
3164
+ const validation = await validateRef('tap', ctx.connector, clientId, sessionId, resolved.ref, {}, signal);
3165
+ if (!validation.ok) return validation;
3166
+ await touchTap(ctx.connector, clientId, sessionId, resolved.ref.center, signal);
3167
+ return this.#withSnapshotAfter('tap', params, ctx, clientId, sessionId, {
3168
+ clientId,
3169
+ sessionId,
3170
+ ref: resolved.ref.ref,
3171
+ point: resolved.ref.center
3172
+ }, signal);
3173
+ }
3174
+ async #longPress(params, ctx, signal) {
3175
+ const clientId = core_str(params, 'clientId');
3176
+ const sessionId = num(params, 'sessionId');
3177
+ const rawRef = core_str(params, 'ref');
3178
+ const duration = num(params, 'duration') ?? 600;
3179
+ if (!clientId || void 0 === sessionId || !rawRef) return result_fail('long-press', 'clientId, sessionId and ref are required.', {
3180
+ reason: 'bad-params'
3181
+ });
3182
+ if (invalidNumber(params, 'duration')) return result_fail('long-press', 'duration must be a finite number when provided.', {
3183
+ reason: 'bad-params'
3184
+ });
3185
+ if (duration < 0) return result_fail('long-press', 'duration must be non-negative.', {
3186
+ reason: 'bad-params'
3187
+ });
3188
+ const resolved = this.#resolveRef('long-press', clientId, sessionId, rawRef);
3189
+ if ('ok' in resolved) return resolved;
3190
+ const validation = await validateRef('long-press', ctx.connector, clientId, sessionId, resolved.ref, {}, signal);
3191
+ if (!validation.ok) return validation;
3192
+ await touchLongPress(ctx.connector, clientId, sessionId, resolved.ref.center, duration, signal);
3193
+ return this.#withSnapshotAfter('long-press', params, ctx, clientId, sessionId, {
3194
+ clientId,
3195
+ sessionId,
3196
+ ref: resolved.ref.ref,
3197
+ point: resolved.ref.center,
3198
+ longPress: true
3199
+ }, signal);
3200
+ }
3201
+ async #fillOrClear(action, params, ctx, value, signal) {
3202
+ const clientId = core_str(params, 'clientId');
3203
+ const sessionId = num(params, 'sessionId');
3204
+ const rawRef = core_str(params, 'ref');
3205
+ if (!clientId || void 0 === sessionId || !rawRef) return result_fail(action, 'clientId, sessionId and ref are required.', {
3206
+ reason: 'bad-params'
3207
+ });
3208
+ const resolved = this.#resolveRef(action, clientId, sessionId, rawRef);
3209
+ if ('ok' in resolved) return resolved;
3210
+ const validation = await validateRef(action, ctx.connector, clientId, sessionId, resolved.ref, {
3211
+ requireEditable: true
3212
+ }, signal);
3213
+ if (!validation.ok) return validation;
3214
+ await touchTap(ctx.connector, clientId, sessionId, resolved.ref.center, signal);
3215
+ await setValue(ctx.connector, clientId, sessionId, validation.nodeId, value, signal, resolved.ref.attributes['value']);
3216
+ return this.#withSnapshotAfter(action, params, ctx, clientId, sessionId, {
3217
+ clientId,
3218
+ sessionId,
3219
+ ref: resolved.ref.ref,
3220
+ value
3221
+ }, signal);
3222
+ }
3223
+ async #fill(params, ctx, signal) {
3224
+ const text = core_str(params, 'text');
3225
+ if (void 0 === text) return result_fail('fill', 'text is required.', {
3226
+ reason: 'bad-params'
3227
+ });
3228
+ return this.#fillOrClear('fill', params, ctx, text, signal);
3229
+ }
3230
+ async #clear(params, ctx, signal) {
3231
+ return this.#fillOrClear('clear', params, ctx, '', signal);
3232
+ }
3233
+ async #scroll(params, ctx, signal) {
3234
+ const clientId = core_str(params, 'clientId');
3235
+ const sessionId = num(params, 'sessionId');
3236
+ const rawRef = core_str(params, 'ref');
3237
+ if (!clientId || void 0 === sessionId || !rawRef) return result_fail('scroll', 'clientId, sessionId and ref are required.', {
3238
+ reason: 'bad-params'
3239
+ });
3240
+ const direction = core_str(params, 'direction') ?? 'down';
3241
+ if (![
3242
+ 'up',
3243
+ 'down',
3244
+ 'left',
3245
+ 'right'
3246
+ ].includes(direction)) return result_fail('scroll', `Invalid direction: ${direction}. Use up | down | left | right.`, {
3247
+ reason: 'bad-params'
3248
+ });
3249
+ const resolved = this.#resolveRef('scroll', clientId, sessionId, rawRef);
3250
+ if ('ok' in resolved) return resolved;
3251
+ const validation = await validateRef('scroll', ctx.connector, clientId, sessionId, resolved.ref, {}, signal);
3252
+ if (!validation.ok) return validation;
3253
+ const { from, to } = swipeForDirection(resolved.ref.box, direction, resolved.snapshot.viewport);
3254
+ await touchSwipe(ctx.connector, clientId, sessionId, from, to, signal, 30);
3255
+ return this.#withSnapshotAfter('scroll', params, ctx, clientId, sessionId, {
3256
+ clientId,
3257
+ sessionId,
3258
+ ref: resolved.ref.ref,
3259
+ direction,
3260
+ from,
3261
+ to
3262
+ }, signal);
3263
+ }
3264
+ async #getText(params, ctx, signal) {
3265
+ const clientId = core_str(params, 'clientId');
3266
+ const sessionId = num(params, 'sessionId');
3267
+ const rawRef = core_str(params, 'ref');
3268
+ if (!clientId || void 0 === sessionId || !rawRef) return result_fail('get-text', 'clientId, sessionId and ref are required.', {
3269
+ reason: 'bad-params'
3270
+ });
3271
+ const resolved = this.#resolveRef('get-text', clientId, sessionId, rawRef);
3272
+ if ('ok' in resolved) return resolved;
3273
+ let text = resolved.ref.text;
3274
+ try {
3275
+ const result = await ctx.connector.sendCDPMessage(clientId, sessionId, 'DOM.innerText', {
3276
+ nodeId: resolved.ref.nodeId
3277
+ });
3278
+ signal.throwIfAborted();
3279
+ const liveText = (result.rawTextValues ?? []).map((value)=>value.text).join(' ').trim();
3280
+ if (liveText) text = liveText;
3281
+ } catch (error) {
3282
+ if (!isUnsupportedCdpMethod(error)) throw error;
3283
+ }
3284
+ return ok('get-text', {
3285
+ clientId,
3286
+ sessionId,
3287
+ ref: resolved.ref.ref,
3288
+ text
3289
+ });
3290
+ }
3291
+ async #getStyle(params, ctx, signal) {
3292
+ const clientId = core_str(params, 'clientId');
3293
+ const sessionId = num(params, 'sessionId');
3294
+ const rawRef = core_str(params, 'ref');
3295
+ if (!clientId || void 0 === sessionId || !rawRef) return result_fail('get-style', 'clientId, sessionId and ref are required.', {
3296
+ reason: 'bad-params'
3297
+ });
3298
+ const wanted = strList(params, 'property');
3299
+ const resolved = this.#resolveRef('get-style', clientId, sessionId, rawRef);
3300
+ if ('ok' in resolved) return resolved;
3301
+ const result = await ctx.connector.sendCDPMessage(clientId, sessionId, 'CSS.getComputedStyleForNode', {
3302
+ nodeId: resolved.ref.nodeId
3303
+ });
3304
+ signal.throwIfAborted();
3305
+ const style = {};
3306
+ for (const { name, value } of result.computedStyle ?? [])if (!wanted || wanted.includes(name)) style[name] = value;
3307
+ return ok('get-style', {
3308
+ clientId,
3309
+ sessionId,
3310
+ ref: resolved.ref.ref,
3311
+ style
3312
+ });
3313
+ }
3314
+ async #wait(params, ctx, signal) {
3315
+ for await (const event of this.#waitStream(params, ctx, signal, false))return event;
3316
+ return result_fail('wait', 'Wait ended before producing a result.', {
3317
+ reason: signal.aborted ? 'aborted' : 'empty-stream',
3318
+ recoverable: true
3319
+ });
3320
+ }
3321
+ async *#waitStream(params, ctx, signal, emitProgress) {
3322
+ const clientId = core_str(params, 'clientId');
3323
+ const sessionId = num(params, 'sessionId');
3324
+ if (!clientId || void 0 === sessionId) return void (yield result_fail('wait', 'clientId and sessionId are required.', {
3325
+ reason: 'bad-params'
3326
+ }));
3327
+ const text = core_str(params, 'text');
3328
+ const rawRef = core_str(params, 'ref');
3329
+ if (!text && !rawRef) return void (yield result_fail('wait', 'Provide text or ref to wait for.', {
3330
+ reason: 'bad-params'
3331
+ }));
3332
+ if (invalidNumber(params, 'timeout') || invalidNumber(params, 'interval')) return void (yield result_fail('wait', 'timeout and interval must be finite numbers when provided.', {
3333
+ reason: 'bad-params'
3334
+ }));
3335
+ const timeout = num(params, 'timeout') ?? 10000;
3336
+ const interval = num(params, 'interval') ?? 500;
3337
+ if (timeout < 0 || interval <= 0) return void (yield result_fail('wait', 'timeout must be non-negative and interval must be positive.', {
3338
+ reason: 'bad-params'
3339
+ }));
3340
+ const by = text ? 'text' : 'ref';
3341
+ const query = text ?? normalizeRef(rawRef);
3342
+ const startedAt = Date.now();
3343
+ const deadline = startedAt + timeout;
3344
+ let expectedRef;
3345
+ if ('ref' === by) {
3346
+ const resolved = this.#resolveRef('wait', clientId, sessionId, query);
3347
+ if ('ok' in resolved) return void (yield resolved);
3348
+ expectedRef = resolved.ref;
3349
+ this.#snapshots.delete(this.#key(clientId, sessionId));
3350
+ }
3351
+ const timeoutResult = ()=>result_fail('wait', `Timed out after ${timeout}ms waiting for ${by} "${query}".`, {
3352
+ reason: 'timeout',
3353
+ recoverable: true,
3354
+ nextActions: [
3355
+ 'agent-lynx snapshot'
3356
+ ]
3357
+ });
3358
+ for(;;){
3359
+ signal.throwIfAborted();
3360
+ const snapshot = await runBeforeDeadline(deadline, signal, (operationSignal)=>buildSnapshotStructure(ctx.connector, clientId, sessionId, operationSignal));
3361
+ if (snapshot === WAIT_DEADLINE) return void (yield timeoutResult());
3362
+ const { viewport, refs } = snapshot;
3363
+ const elapsedMs = Date.now() - startedAt;
3364
+ const matched = 'text' === by ? refs.some((ref)=>ref.text.includes(query)) : refs.some((ref)=>sameSnapshotNode(ref, expectedRef));
3365
+ if ('text' === by) this.#snapshots.set(this.#key(clientId, sessionId), {
3366
+ createdAt: Date.now(),
3367
+ viewport,
3368
+ refs
3369
+ });
3370
+ if (matched) {
3371
+ if ('ref' === by) {
3372
+ const enriched = await runBeforeDeadline(deadline, signal, (operationSignal)=>enrichSnapshot(ctx.connector, clientId, sessionId, snapshot, operationSignal));
3373
+ if (enriched !== WAIT_DEADLINE) this.#snapshots.set(this.#key(clientId, sessionId), {
3374
+ createdAt: Date.now(),
3375
+ viewport,
3376
+ refs
3377
+ });
3378
+ }
3379
+ yield ok('wait', {
3380
+ clientId,
3381
+ sessionId,
3382
+ matched: true,
3383
+ by,
3384
+ query,
3385
+ elapsedMs
3386
+ });
3387
+ return;
3388
+ }
3389
+ if (elapsedMs >= timeout) return void (yield timeoutResult());
3390
+ if (emitProgress) yield ok('wait.progress', {
3391
+ clientId,
3392
+ sessionId,
3393
+ matched: false,
3394
+ by,
3395
+ query,
3396
+ elapsedMs,
3397
+ refCount: refs.length
3398
+ });
3399
+ await promises_setTimeout(Math.min(interval, Math.max(0, deadline - Date.now())), void 0, {
3400
+ signal
3401
+ });
3402
+ }
3403
+ }
3404
+ }
3405
+ const STRING_PREFIX = '~lynx-string~';
3406
+ const JSON_PREFIX = '~lynx-json~';
3407
+ function appendCommandQueryParam(query, key, value) {
3408
+ if (void 0 === value) return;
3409
+ if ('string' == typeof value) return void query.append(key, `${STRING_PREFIX}${value}`);
3410
+ const json = JSON.stringify(value);
3411
+ if (void 0 !== json) query.append(key, `${JSON_PREFIX}${json}`);
3412
+ }
3413
+ function decodeCommandQueryValue(value) {
3414
+ if (value.startsWith(STRING_PREFIX)) return value.slice(STRING_PREFIX.length);
3415
+ if (value.startsWith(JSON_PREFIX)) return JSON.parse(value.slice(JSON_PREFIX.length));
3416
+ return value;
3417
+ }
3418
+ function decodeCommandQuery(params) {
3419
+ const result = {};
3420
+ for (const [key, rawValue] of params){
3421
+ const value = decodeCommandQueryValue(rawValue);
3422
+ const previous = result[key];
3423
+ if (void 0 === previous) result[key] = value;
3424
+ else if (Array.isArray(previous)) previous.push(value);
3425
+ else result[key] = [
3426
+ previous,
3427
+ value
3428
+ ];
3429
+ }
3430
+ return result;
3431
+ }
3432
+ export { ActionCore, DevNodeType, ScreenshotAnnotationError, ScreenshotTimeoutError, annotateScreenshot, appendCommandQueryParam, applyOperationV2, applyRootOrder, buildReactLynxUpdatePath, buildRefs, buildRegexMatcher, buildSnapshot, buildSubstringMatcher, captureScreenshot, captureScreenshotFrame, centerOfQuad, createRendererState, decodeCommandQuery, deserializeRendererState, findReactLynxComponents, formatReactLynxTree, normalizeRef, ok, parseReactLynxComponentRef, parseReactLynxLinkRef, result_fail as fail, serializeRendererState, touchTap, typeTag, validateRef };