lceda-connect 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,9 @@
1
- import { g as CdpError, p as resolveEndpoint, v as clipText, y as coerceText } from "./discover-D4ouuCrn.mjs";
2
- import { a as CdpSession, c as evaluateExpression, i as listTargets, s as apiExpression } from "./targets-DiGwICXT.mjs";
1
+ import { g as CdpError, p as resolveEndpoint, t as DEFAULT_CDP_HOST, v as clipText, y as coerceText } from "./discover-D4ouuCrn.mjs";
2
+ import { t as ToolError } from "./types-D5d7ZRYF.mjs";
3
+ import { a as CdpSession, c as evaluateExpression, d as UI_SHELL_MARKERS, i as listTargets, s as apiExpression } from "./targets-DYfgkrq3.mjs";
3
4
  import path from "node:path";
4
5
  import fs from "node:fs";
6
+ import { z } from "zod";
5
7
  // src/cdp/modalProbe.ts
6
8
  /**
7
9
  * 编辑器状态探针(历史预览态 / 模态框句柄 / 工程与文档信息)的 JS 载荷。
@@ -755,6 +757,653 @@ async function openDocument(board, options) {
755
757
  }
756
758
  return result;
757
759
  }
760
+ // src/cdp/input.ts
761
+ /** 只接受本机回环端点;与 discover/session 的口径一致。 */
762
+ const INPUT_HOST = DEFAULT_CDP_HOST;
763
+ /** 允许的编辑器来源:中文专业版 Web(pro.lceda.cn)和桌面客户端(https://client)。 */
764
+ const INPUT_EDITOR_ORIGINS = ["https://pro.lceda.cn", "https://client"];
765
+ /** 编辑器主页面路径。 */
766
+ const INPUT_EDITOR_PATH = "/editor";
767
+ /** 中文专业版标题:`<工程名> | 嘉立创EDA(专业版) - V4.1.105`(版本号不锁死)。 */
768
+ const INPUT_EDITOR_TITLE_PATTERN = /(?:^| \| )嘉立创EDA\(专业版\) - V\d+(?:\.\d+)+$/;
769
+ /** 文本动作的 UTF-16 长度上限。 */
770
+ const INPUT_MAX_TEXT_LENGTH = 1024;
771
+ /** 坐标是相对主 frame 视口的 CSS 像素,限定在有限的正整数域内。 */
772
+ const INPUT_MAX_COORDINATE = 65535;
773
+ /** 读 `/json/list` 的 HTTP 超时。 */
774
+ const INPUT_HTTP_TIMEOUT_MS = 5e3;
775
+ /** 识别原生、ARIA 和上游常见类名的可见弹层,不要求最小尺寸或文字。 */
776
+ const INPUT_MODAL_SELECTOR = "dialog[open], [role=\"dialog\"], [role=\"alertdialog\"], [aria-modal=\"true\"], [class*=\"lc_modal\"], [class*=\"modal\"], [class*=\"dialog\"]";
777
+ /** 允许发送的按键;`code` 与 `key` 同名,虚拟键码沿用 Windows 口径。 */
778
+ const INPUT_KEY_CODES = {
779
+ Escape: {
780
+ code: "Escape",
781
+ windowsVirtualKeyCode: 27,
782
+ nativeVirtualKeyCode: 27
783
+ },
784
+ Enter: {
785
+ code: "Enter",
786
+ windowsVirtualKeyCode: 13,
787
+ nativeVirtualKeyCode: 13
788
+ },
789
+ Tab: {
790
+ code: "Tab",
791
+ windowsVirtualKeyCode: 9,
792
+ nativeVirtualKeyCode: 9
793
+ },
794
+ ArrowUp: {
795
+ code: "ArrowUp",
796
+ windowsVirtualKeyCode: 38,
797
+ nativeVirtualKeyCode: 38
798
+ },
799
+ ArrowDown: {
800
+ code: "ArrowDown",
801
+ windowsVirtualKeyCode: 40,
802
+ nativeVirtualKeyCode: 40
803
+ },
804
+ ArrowLeft: {
805
+ code: "ArrowLeft",
806
+ windowsVirtualKeyCode: 37,
807
+ nativeVirtualKeyCode: 37
808
+ },
809
+ ArrowRight: {
810
+ code: "ArrowRight",
811
+ windowsVirtualKeyCode: 39,
812
+ nativeVirtualKeyCode: 39
813
+ },
814
+ Backspace: {
815
+ code: "Backspace",
816
+ windowsVirtualKeyCode: 8,
817
+ nativeVirtualKeyCode: 8
818
+ }
819
+ };
820
+ /** 守卫表达式的固定失败码;只用于本地文案映射,不回显页面内容。 */
821
+ const GUARD_MESSAGES = {
822
+ location: "编辑器地址已变化",
823
+ ui: "编辑器界面未通过校验",
824
+ modal: "编辑器上有弹层/对话框打开",
825
+ api: "页面主世界没有可用的编辑器 API",
826
+ document: "活动 PCB 与目标文档不符",
827
+ frame: "编辑画布 iframe 不是唯一的同源目标",
828
+ viewport: "点击坐标不在可见画布范围内",
829
+ hit: "点击坐标未命中编辑画布",
830
+ focus: "键盘焦点不在编辑画布内",
831
+ editable: "焦点控件的可编辑状态不适合该输入",
832
+ transport: "守卫求值没有响应",
833
+ exception: "守卫求值抛异常",
834
+ error: "守卫求值异常",
835
+ unknown: "守卫结果形状不合法"
836
+ };
837
+ const TARGET_ID_PATTERN = /^[0-9A-Fa-f]{32}$/;
838
+ const DOCUMENT_UUID_PATTERN = /^[0-9A-Fa-f]{16,64}$/;
839
+ /** 拒绝 C0/DEL 控制符,只放行制表与换行。 */
840
+ function hasUnsafeControl(value) {
841
+ for (const char of value) {
842
+ const code = char.codePointAt(0) ?? 0;
843
+ if (code < 32 && code !== 9 && code !== 10 || code === 127) return true;
844
+ }
845
+ return false;
846
+ }
847
+ /** 进程内并发闸:同一端口/目标只允许一个 sendCdpInput 在飞。 */
848
+ const ACTIVE_REQUESTS = /* @__PURE__ */ new Set();
849
+ /** 同一 session 对象上不允许两个 dispatchCdpInput 并发。 */
850
+ const ACTIVE_SESSIONS = /* @__PURE__ */ new WeakSet();
851
+ function invalid(message) {
852
+ throw new CdpError("CDP_INPUT_INVALID", message, { exitCode: 2 });
853
+ }
854
+ function targetError(message) {
855
+ throw new CdpError("CDP_INPUT_TARGET", message, { exitCode: 2 });
856
+ }
857
+ function cancelled() {
858
+ return new ToolError("CANCELLED", "CDP 输入已取消");
859
+ }
860
+ function uncertain(request, dispatched, cause) {
861
+ return new CdpError("CDP_INPUT_UNCERTAIN", "输入事件已发出,但无法确认协议完整性或编辑器是否仍为同一文档;结果未知,请勿直接重试。", {
862
+ exitCode: 4,
863
+ details: {
864
+ target: request.target,
865
+ documentUuid: request.documentUuid,
866
+ dispatched
867
+ },
868
+ cause
869
+ });
870
+ }
871
+ function isCancelled(error) {
872
+ return error !== null && typeof error === "object" && error.code === "CANCELLED";
873
+ }
874
+ function guardError(reason) {
875
+ const known = Object.hasOwn(GUARD_MESSAGES, reason);
876
+ const message = known ? GUARD_MESSAGES[reason] ?? "守卫结果形状不合法" : "守卫结果形状不合法";
877
+ return new CdpError("CDP_INPUT_GUARD", `调度前守卫拒绝:${message}`, {
878
+ exitCode: 3,
879
+ details: { reason: known ? reason : "unknown" }
880
+ });
881
+ }
882
+ /**
883
+ * 纯校验;`sendCdpInput` 在联网前调用,`dispatchCdpInput` 在发任何 CDP 方法前也会调用。
884
+ *
885
+ * 顺序固定:结构 → confirm → port → target → documentUuid → action。
886
+ * `confirm` 只接受字面量 `true`,缺省或 false 都在这里拒绝。
887
+ */
888
+ function validateCdpInputRequest(request) {
889
+ if (request === null || typeof request !== "object" || Array.isArray(request)) invalid("输入请求不是对象");
890
+ const candidate = request;
891
+ if (candidate.confirm !== true) throw new CdpError("CDP_INPUT_CONFIRM", "定向输入是写操作,确认影响后以 confirm: true 重新调用。", { exitCode: 3 });
892
+ const port = candidate.port;
893
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) invalid("port 必须是 1..65535 的整数");
894
+ const target = candidate.target;
895
+ if (typeof target !== "string" || !TARGET_ID_PATTERN.test(target)) invalid("target 必须是 32 位十六进制 page id");
896
+ const documentUuid = candidate.documentUuid;
897
+ if (typeof documentUuid !== "string" || !DOCUMENT_UUID_PATTERN.test(documentUuid)) invalid("documentUuid 必须是 16–64 位十六进制文档 id");
898
+ normalizeAction(candidate.action);
899
+ }
900
+ function normalizeInputRequest(request) {
901
+ validateCdpInputRequest(request);
902
+ return normalizeAction(request.action);
903
+ }
904
+ function normalizeAction(raw) {
905
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) invalid("action 不是对象");
906
+ const action = raw;
907
+ switch (action.kind) {
908
+ case "click": {
909
+ const x = action.x;
910
+ const y = action.y;
911
+ if (typeof x !== "number" || !Number.isFinite(x) || x < 0 || x > 65535 || typeof y !== "number" || !Number.isFinite(y) || y < 0 || y > 65535) invalid(`click 的 x/y 必须是 0..${INPUT_MAX_COORDINATE} 的有限数`);
912
+ const button = action.button ?? "left";
913
+ if (button !== "left" && button !== "right") invalid("click 的 button 只能是 left / right");
914
+ const clickCount = action.clickCount ?? 1;
915
+ if (clickCount !== 1 && clickCount !== 2) invalid("click 的 clickCount 只能是 1 / 2");
916
+ return {
917
+ kind: "click",
918
+ x,
919
+ y,
920
+ button,
921
+ clickCount
922
+ };
923
+ }
924
+ case "key": {
925
+ const key = action.key;
926
+ if (typeof key !== "string" || !Object.hasOwn(INPUT_KEY_CODES, key)) invalid(`key 只能是 ${Object.keys(INPUT_KEY_CODES).join(" / ")}`);
927
+ return {
928
+ kind: "key",
929
+ key
930
+ };
931
+ }
932
+ case "text": {
933
+ const text = action.text;
934
+ if (typeof text !== "string" || text.length < 1 || text.length > 1024) invalid(`text 长度必须是 1..${INPUT_MAX_TEXT_LENGTH}`);
935
+ if (hasUnsafeControl(text)) invalid("text 不能包含控制字符(\\t、\\n 除外)");
936
+ return {
937
+ kind: "text",
938
+ text
939
+ };
940
+ }
941
+ default: invalid("action.kind 只能是 click / key / text");
942
+ }
943
+ }
944
+ /**
945
+ * 从 `/json/list` 里挑出精确 target 并返回校验过的 WebSocket 地址。
946
+ *
947
+ * `target` 参数是 page id(不是 URL 子串)。page URL 允许 query/hash(lifecycle 的
948
+ * `#id=<project>,pcb=<pcb>` 就是这样),但拒绝凭据;WebSocket 必须是
949
+ * `ws://127.0.0.1:<同一 port>/devtools/page/<同一个 id>`,无 query/hash/凭据。
950
+ */
951
+ function selectInputTarget(targets, port, target) {
952
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) invalid("port 必须是 1..65535 的整数");
953
+ if (typeof target !== "string" || !TARGET_ID_PATTERN.test(target)) invalid("target 必须是 32 位十六进制 page id");
954
+ if (!Array.isArray(targets)) targetError("CDP 页面列表不是数组");
955
+ const matches = targets.filter((item) => item !== null && typeof item === "object" && item.id === target);
956
+ if (matches.length !== 1) targetError(`指定 target 的命中数=${matches.length}(期望恰好 1)`);
957
+ const page = matches[0];
958
+ if (!page) targetError("指定 target 不存在");
959
+ if (page.type !== "page") targetError("指定 target 不是 page");
960
+ if (typeof page.url !== "string" || page.url === "") targetError("指定 page 没有 URL");
961
+ let url;
962
+ try {
963
+ url = new URL(page.url);
964
+ } catch {
965
+ targetError("指定 page 的 URL 不合法");
966
+ }
967
+ if (url.username || url.password) targetError("指定 page 的 URL 含凭据");
968
+ if (!INPUT_EDITOR_ORIGINS.includes(url.origin)) targetError("指定 page 的来源不是已知的中文编辑器");
969
+ if (url.pathname !== "/editor") targetError("指定 page 的路径不是编辑器主页面");
970
+ if (typeof page.title !== "string" || !INPUT_EDITOR_TITLE_PATTERN.test(page.title)) targetError("指定 page 的标题不是嘉立创EDA(专业版)中文版");
971
+ const raw = page.webSocketDebuggerUrl;
972
+ if (typeof raw !== "string" || raw === "") targetError("指定 page 没有调试 WebSocket");
973
+ let ws;
974
+ try {
975
+ ws = new URL(raw);
976
+ } catch {
977
+ targetError("调试 WebSocket 地址不合法");
978
+ }
979
+ if (ws.protocol !== "ws:" || ws.hostname !== INPUT_HOST || (ws.port ? Number(ws.port) : 80) !== port || ws.pathname !== `/devtools/page/${target}` || ws.search !== "" || ws.hash !== "" || ws.username !== "" || ws.password !== "") targetError("调试 WebSocket 未绑定指定的回环端口和 page target");
980
+ return raw;
981
+ }
982
+ const GUARD_CLICK_BLOCK = String.raw` const x = want.point.x;
983
+ const y = want.point.y;
984
+ const width = globalThis.innerWidth;
985
+ const height = globalThis.innerHeight;
986
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
987
+ return fail('viewport');
988
+ }
989
+ if (!(x >= 0 && y >= 0 && x < width && y < height)) return fail('viewport');
990
+ const rect = frame.getBoundingClientRect();
991
+ if (
992
+ ![rect.left, rect.top, rect.right, rect.bottom].every(Number.isFinite) ||
993
+ !(rect.width > 0 && rect.height > 0)
994
+ ) {
995
+ return fail('frame');
996
+ }
997
+ if (!(x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom)) {
998
+ return fail('viewport');
999
+ }
1000
+ const hit = document.elementFromPoint(x, y);
1001
+ if (!hit || hit !== frame) return fail('hit');
1002
+ const inner = frame.contentDocument;
1003
+ if (!inner) return fail('frame');
1004
+ if (hasVisibleModal(inner)) return fail('modal');
1005
+ const localX = x - rect.left;
1006
+ const localY = y - rect.top;
1007
+ const innerWidth = frame.clientWidth;
1008
+ const innerHeight = frame.clientHeight;
1009
+ if (
1010
+ !Number.isFinite(innerWidth) ||
1011
+ !Number.isFinite(innerHeight) ||
1012
+ innerWidth <= 0 ||
1013
+ innerHeight <= 0
1014
+ ) {
1015
+ return fail('viewport');
1016
+ }
1017
+ if (!(localX >= 0 && localY >= 0 && localX < innerWidth && localY < innerHeight)) {
1018
+ return fail('viewport');
1019
+ }
1020
+ const innerHit = inner.elementFromPoint(localX, localY);
1021
+ if (!innerHit) return fail('hit');
1022
+ const blocked = innerHit.closest?.(
1023
+ 'input, textarea, select, button, a, [contenteditable="true"], [role="dialog"], [class*="lc_modal"]',
1024
+ );
1025
+ if (blocked) return fail('hit');
1026
+ // 只有实际画布才允许定向点击;普通 div 浮层/面板一律视为未命中。
1027
+ if (String(innerHit.tagName || '').toUpperCase() !== 'CANVAS') return fail('hit');
1028
+ return { ok: true };`;
1029
+ const GUARD_KEY_BLOCK = String.raw` if (document.activeElement !== frame) return fail('focus');
1030
+ const inner = frame.contentDocument;
1031
+ if (!inner) return fail('frame');
1032
+ if (hasVisibleModal(inner)) return fail('modal');
1033
+ const active = inner.activeElement;
1034
+ if (!active) return fail('focus');
1035
+ if (active.closest?.('[inert]')) return fail('focus');
1036
+ const tag = String(active.tagName || '').toUpperCase();
1037
+ const editable = tag === 'INPUT' || tag === 'TEXTAREA' || active.isContentEditable === true;
1038
+ if (editable) return fail('editable');
1039
+ if (tag !== 'BODY' && tag !== 'HTML' && tag !== 'CANVAS' && active !== inner.body) {
1040
+ return fail('focus');
1041
+ }
1042
+ return { ok: true };`;
1043
+ const GUARD_TEXT_BLOCK = String.raw` if (document.activeElement !== frame) return fail('focus');
1044
+ const inner = frame.contentDocument;
1045
+ if (!inner) return fail('frame');
1046
+ if (hasVisibleModal(inner)) return fail('modal');
1047
+ const active = inner.activeElement;
1048
+ if (!active) return fail('focus');
1049
+ if (active.hidden === true || active.closest?.('[inert]')) return fail('editable');
1050
+ if (active.getAttribute?.('aria-disabled') === 'true') return fail('editable');
1051
+ const tag = String(active.tagName || '').toUpperCase();
1052
+ if (tag !== 'INPUT' && tag !== 'TEXTAREA' && active.isContentEditable !== true) {
1053
+ return fail('editable');
1054
+ }
1055
+ if (tag === 'INPUT' || tag === 'TEXTAREA') {
1056
+ if (active.disabled === true || active.readOnly === true) return fail('editable');
1057
+ }
1058
+ if (tag === 'INPUT') {
1059
+ const type = String(active.type || 'text').toLowerCase();
1060
+ if (!['text', 'search', 'tel', 'url', 'email', 'number'].includes(type)) {
1061
+ return fail('editable');
1062
+ }
1063
+ }
1064
+ return { ok: true };`;
1065
+ const GUARD_IDENTITY_BLOCK = " return { ok: true };";
1066
+ /** 生成固定的守卫表达式;只嵌入常量与本请求的精确值,不嵌入页面内容。 */
1067
+ function inputGuardExpression(options) {
1068
+ if (!DOCUMENT_UUID_PATTERN.test(options.documentUuid)) invalid("documentUuid 形状不合法");
1069
+ if (options.mode === "click") {
1070
+ if (typeof options.x !== "number" || !Number.isFinite(options.x)) invalid("click 守卫缺少 x");
1071
+ if (typeof options.y !== "number" || !Number.isFinite(options.y)) invalid("click 守卫缺少 y");
1072
+ }
1073
+ const want = JSON.stringify({
1074
+ origins: [...INPUT_EDITOR_ORIGINS],
1075
+ path: INPUT_EDITOR_PATH,
1076
+ documentUuid: options.documentUuid,
1077
+ point: options.mode === "click" ? {
1078
+ x: options.x,
1079
+ y: options.y
1080
+ } : null,
1081
+ pre: options.mode !== "identity",
1082
+ markers: [...UI_SHELL_MARKERS],
1083
+ minMarkers: 2,
1084
+ modalSelector: INPUT_MODAL_SELECTOR
1085
+ });
1086
+ const block = options.mode === "click" ? GUARD_CLICK_BLOCK : options.mode === "key" ? GUARD_KEY_BLOCK : options.mode === "text" ? GUARD_TEXT_BLOCK : GUARD_IDENTITY_BLOCK;
1087
+ return String.raw`(async () => {
1088
+ const want = ${want};
1089
+ const fail = (reason) => ({ ok: false, reason });
1090
+ const hasVisibleModal = (doc) => {
1091
+ if (!doc) return false;
1092
+ const nodes = Array.from(doc.querySelectorAll(want.modalSelector));
1093
+ for (const el of nodes) {
1094
+ // 后台页面不能仅凭 visibilityState 判定弹层不存在。
1095
+ if (el.checkVisibility && !el.checkVisibility({ visibilityProperty: true, opacityProperty: true })) continue;
1096
+ const rect = el.getBoundingClientRect();
1097
+ if (rect.width > 0 && rect.height > 0) return true;
1098
+ }
1099
+ return false;
1100
+ };
1101
+ try {
1102
+ if (!want.origins.includes(location.origin) || location.pathname !== want.path) {
1103
+ return fail('location');
1104
+ }
1105
+ if (document.readyState !== 'complete') return fail('ui');
1106
+ let markers = 0;
1107
+ for (const selector of want.markers) {
1108
+ try { if (document.querySelector(selector)) markers += 1; } catch (error) {}
1109
+ }
1110
+ if (markers < want.minMarkers) return fail('ui');
1111
+ if (want.pre && hasVisibleModal(document)) return fail('modal');
1112
+ const api = globalThis._EXTAPI_ROOT_;
1113
+ if (
1114
+ !api ||
1115
+ typeof api.dmt_Pcb?.getCurrentPcbInfo !== 'function' ||
1116
+ typeof api.dmt_SelectControl?.getCurrentDocumentInfo !== 'function'
1117
+ ) {
1118
+ return fail('api');
1119
+ }
1120
+ const pcb = await api.dmt_Pcb.getCurrentPcbInfo();
1121
+ const documentInfo = await api.dmt_SelectControl.getCurrentDocumentInfo();
1122
+ if (!want.origins.includes(location.origin) || location.pathname !== want.path) {
1123
+ return fail('location');
1124
+ }
1125
+ // await 期间页面可能变化(含弹层弹出而 iframe 焦点仍在),必须重新复查。
1126
+ if (document.readyState !== 'complete') return fail('ui');
1127
+ if (want.pre && hasVisibleModal(document)) return fail('modal');
1128
+ if (!pcb || pcb.uuid !== want.documentUuid) return fail('document');
1129
+ if (
1130
+ !documentInfo ||
1131
+ documentInfo.uuid !== want.documentUuid ||
1132
+ documentInfo.documentType !== 3
1133
+ ) {
1134
+ return fail('document');
1135
+ }
1136
+ if (
1137
+ typeof pcb.parentProjectUuid === 'string' &&
1138
+ typeof documentInfo.parentProjectUuid === 'string' &&
1139
+ pcb.parentProjectUuid !== documentInfo.parentProjectUuid
1140
+ ) {
1141
+ return fail('document');
1142
+ }
1143
+ const frames = Array.from(document.querySelectorAll('iframe.editframe'));
1144
+ if (frames.length !== 1) return fail('frame');
1145
+ const frame = frames[0];
1146
+ if (frame.hasAttribute('srcdoc') || typeof frame.src !== 'string' || !frame.src) return fail('frame');
1147
+ const source = new URL(frame.src, location.href);
1148
+ const current = frame.contentDocument;
1149
+ if (!current || current.readyState !== 'complete') return fail('frame');
1150
+ const loaded = new URL(current.URL);
1151
+ if (source.origin !== location.origin || loaded.origin !== source.origin ||
1152
+ loaded.pathname !== source.pathname || loaded.search !== source.search) return fail('frame');
1153
+ ${block}
1154
+ } catch (error) {
1155
+ return fail('error');
1156
+ }
1157
+ })()`;
1158
+ }
1159
+ /**
1160
+ * 在给定 session 上发一次定向输入。
1161
+ *
1162
+ * 任何 Input 事件之前都会先跑 pre 守卫;事件按数组顺序紧邻发送,不插入等待、不重试。
1163
+ * 双击的第二对事件之前再跑一次 click 守卫。事件一旦尝试发出,后续守卫或传输异常
1164
+ * 一律按 CDP_INPUT_UNCERTAIN 处理,不再做补偿性输入(不重放 press、不补 release)。
1165
+ */
1166
+ async function dispatchCdpInput(session, request, signal) {
1167
+ if (signal?.aborted) throw cancelled();
1168
+ const action = normalizeInputRequest(request);
1169
+ if (signal?.aborted) throw cancelled();
1170
+ if (ACTIVE_SESSIONS.has(session)) throw new CdpError("CDP_INPUT_GUARD", "同一 CDP 会话上已有输入操作在进行,已拒绝并发。", { exitCode: 3 });
1171
+ ACTIVE_SESSIONS.add(session);
1172
+ try {
1173
+ const pre = await runGuard(session, inputGuardExpression({
1174
+ mode: action.kind,
1175
+ documentUuid: request.documentUuid,
1176
+ ...action.kind === "click" ? {
1177
+ x: action.x,
1178
+ y: action.y
1179
+ } : {}
1180
+ }), signal);
1181
+ if (!pre.ok) throw guardError(pre.reason);
1182
+ if (signal?.aborted) throw cancelled();
1183
+ let dispatched = 0;
1184
+ let attempted = false;
1185
+ const send = async (event) => {
1186
+ if (signal?.aborted) throw cancelled();
1187
+ attempted = true;
1188
+ if (signal) await session.call(event.method, event.params, signal);
1189
+ else await session.call(event.method, event.params);
1190
+ dispatched += 1;
1191
+ };
1192
+ const sendAll = async (events) => {
1193
+ for (const event of events) await send(event);
1194
+ };
1195
+ try {
1196
+ if (action.kind === "click") {
1197
+ await sendAll(clickPair(action, 1));
1198
+ if (action.clickCount === 2) {
1199
+ const recheck = await runGuard(session, inputGuardExpression({
1200
+ mode: "click",
1201
+ documentUuid: request.documentUuid,
1202
+ x: action.x,
1203
+ y: action.y
1204
+ }), signal);
1205
+ if (!recheck.ok) throw guardError(recheck.reason);
1206
+ await sendAll(clickPair(action, 2));
1207
+ }
1208
+ } else if (action.kind === "key") await sendAll(keyEvents(action));
1209
+ else await sendAll([textEvent(action)]);
1210
+ } catch (error) {
1211
+ if (!attempted) throw error;
1212
+ throw uncertain(request, dispatched, error);
1213
+ }
1214
+ try {
1215
+ const post = await runGuard(session, inputGuardExpression({
1216
+ mode: "identity",
1217
+ documentUuid: request.documentUuid
1218
+ }), signal);
1219
+ if (!post.ok) throw guardError(post.reason);
1220
+ } catch (error) {
1221
+ throw uncertain(request, dispatched, error);
1222
+ }
1223
+ return {
1224
+ target: request.target,
1225
+ documentUuid: request.documentUuid,
1226
+ dispatched,
1227
+ delivery: "protocol-acknowledged"
1228
+ };
1229
+ } finally {
1230
+ ACTIVE_SESSIONS.delete(session);
1231
+ }
1232
+ }
1233
+ /**
1234
+ * 连接指定回环端点的精确 page target 并发一次定向输入。
1235
+ *
1236
+ * 全部请求校验在 `/json/list` 之前完成;随后重新枚举页面、校验唯一 target 和
1237
+ * WebSocket 绑定,再交给 `dispatchCdpInput`。同一进程内同一 `${port}:${target}`
1238
+ * 不允许并发,避免两次按键/点击互相穿插。
1239
+ */
1240
+ async function sendCdpInput(request, options = {}) {
1241
+ const signal = options.signal;
1242
+ if (signal?.aborted) throw cancelled();
1243
+ normalizeInputRequest(request);
1244
+ if (signal?.aborted) throw cancelled();
1245
+ const key = `${request.port}:${request.target}`;
1246
+ if (ACTIVE_REQUESTS.has(key)) throw new CdpError("CDP_INPUT_GUARD", "同一端口与 target 上已有输入操作在进行,已拒绝并发。", { exitCode: 3 });
1247
+ ACTIVE_REQUESTS.add(key);
1248
+ let session = null;
1249
+ try {
1250
+ const wsUrl = selectInputTarget(await fetchInputTargets(request.port, signal), request.port, request.target);
1251
+ if (signal?.aborted) throw cancelled();
1252
+ session = await CdpSession.connect(wsUrl, { signal });
1253
+ return await dispatchCdpInput(session, request, signal);
1254
+ } finally {
1255
+ ACTIVE_REQUESTS.delete(key);
1256
+ session?.close();
1257
+ }
1258
+ }
1259
+ async function fetchInputTargets(port, signal) {
1260
+ const timeout = AbortSignal.timeout(INPUT_HTTP_TIMEOUT_MS);
1261
+ let response;
1262
+ try {
1263
+ response = await fetch(`http://${INPUT_HOST}:${port}/json/list`, {
1264
+ redirect: "error",
1265
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
1266
+ headers: { accept: "application/json" }
1267
+ });
1268
+ } catch (error) {
1269
+ if (signal?.aborted) throw cancelled();
1270
+ throw new CdpError("CDP_INPUT_TARGET", `无法读取 ${INPUT_HOST}:${port} 的 CDP 页面列表`, {
1271
+ exitCode: 2,
1272
+ cause: error
1273
+ });
1274
+ }
1275
+ if (!response.ok) throw new CdpError("CDP_INPUT_TARGET", `CDP 页面列表返回 HTTP ${response.status}`, { exitCode: 2 });
1276
+ let payload;
1277
+ try {
1278
+ payload = await response.json();
1279
+ } catch (error) {
1280
+ if (signal?.aborted) throw cancelled();
1281
+ throw new CdpError("CDP_INPUT_TARGET", "CDP 页面列表不是 JSON", {
1282
+ exitCode: 2,
1283
+ cause: error
1284
+ });
1285
+ }
1286
+ if (!Array.isArray(payload)) throw targetError("CDP 页面列表不是数组");
1287
+ return payload.filter((item) => item !== null && typeof item === "object" && !Array.isArray(item));
1288
+ }
1289
+ function clickPair(action, clickCount) {
1290
+ const buttons = action.button === "left" ? 1 : 2;
1291
+ return [{
1292
+ method: "Input.dispatchMouseEvent",
1293
+ params: {
1294
+ type: "mousePressed",
1295
+ x: action.x,
1296
+ y: action.y,
1297
+ button: action.button,
1298
+ clickCount,
1299
+ buttons
1300
+ }
1301
+ }, {
1302
+ method: "Input.dispatchMouseEvent",
1303
+ params: {
1304
+ type: "mouseReleased",
1305
+ x: action.x,
1306
+ y: action.y,
1307
+ button: action.button,
1308
+ clickCount,
1309
+ buttons: 0
1310
+ }
1311
+ }];
1312
+ }
1313
+ function keyEvents(action) {
1314
+ const table = INPUT_KEY_CODES[action.key];
1315
+ const base = {
1316
+ key: action.key,
1317
+ code: table.code,
1318
+ windowsVirtualKeyCode: table.windowsVirtualKeyCode,
1319
+ nativeVirtualKeyCode: table.nativeVirtualKeyCode
1320
+ };
1321
+ return [{
1322
+ method: "Input.dispatchKeyEvent",
1323
+ params: {
1324
+ type: "keyDown",
1325
+ ...base
1326
+ }
1327
+ }, {
1328
+ method: "Input.dispatchKeyEvent",
1329
+ params: {
1330
+ type: "keyUp",
1331
+ ...base
1332
+ }
1333
+ }];
1334
+ }
1335
+ function textEvent(action) {
1336
+ return {
1337
+ method: "Input.insertText",
1338
+ params: { text: action.text }
1339
+ };
1340
+ }
1341
+ async function runGuard(session, expression, signal) {
1342
+ let reply;
1343
+ try {
1344
+ reply = signal ? await session.call("Runtime.evaluate", {
1345
+ expression,
1346
+ returnByValue: true,
1347
+ awaitPromise: true
1348
+ }, signal) : await session.call("Runtime.evaluate", {
1349
+ expression,
1350
+ returnByValue: true,
1351
+ awaitPromise: true
1352
+ });
1353
+ } catch (error) {
1354
+ if (isCancelled(error)) throw error;
1355
+ return {
1356
+ ok: false,
1357
+ reason: "transport"
1358
+ };
1359
+ }
1360
+ if (reply?.exceptionDetails !== void 0 && reply.exceptionDetails !== null) return {
1361
+ ok: false,
1362
+ reason: "exception"
1363
+ };
1364
+ const value = reply?.result?.value;
1365
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return {
1366
+ ok: false,
1367
+ reason: "unknown"
1368
+ };
1369
+ const shaped = value;
1370
+ if (shaped.ok === true) return { ok: true };
1371
+ if (shaped.ok === false && typeof shaped.reason === "string" && shaped.reason !== "") return {
1372
+ ok: false,
1373
+ reason: shaped.reason.slice(0, 40)
1374
+ };
1375
+ return {
1376
+ ok: false,
1377
+ reason: "unknown"
1378
+ };
1379
+ }
1380
+ // src/cdp/inputSchema.ts
1381
+ const cdpInputActionSchema = z.discriminatedUnion("kind", [
1382
+ z.strictObject({
1383
+ kind: z.literal("click"),
1384
+ x: z.number().min(0).max(INPUT_MAX_COORDINATE),
1385
+ y: z.number().min(0).max(INPUT_MAX_COORDINATE),
1386
+ button: z.enum(["left", "right"]).optional(),
1387
+ clickCount: z.union([z.literal(1), z.literal(2)]).optional()
1388
+ }),
1389
+ z.strictObject({
1390
+ kind: z.literal("key"),
1391
+ key: z.enum([
1392
+ "Escape",
1393
+ "Enter",
1394
+ "Tab",
1395
+ "ArrowUp",
1396
+ "ArrowDown",
1397
+ "ArrowLeft",
1398
+ "ArrowRight",
1399
+ "Backspace"
1400
+ ])
1401
+ }),
1402
+ z.strictObject({
1403
+ kind: z.literal("text"),
1404
+ text: z.string().min(1).max(INPUT_MAX_TEXT_LENGTH)
1405
+ })
1406
+ ]);
758
1407
  // src/cdp/screenshot.ts
759
1408
  /** 直接返回 base64,不落盘(供需要自己处理数据的调用方)。 */
760
1409
  async function captureScreenshot(session, options = {}) {
@@ -1128,4 +1777,4 @@ function firstSideEffectPattern(expression) {
1128
1777
  for (let index = 0; index < COMPILED.length; index += 1) if (COMPILED[index]?.test(stripped)) return SIDE_EFFECT_PATTERNS[index] ?? null;
1129
1778
  return classifyEval(expression).reasons[0] ?? null;
1130
1779
  }
1131
- export { activeDocument as a, Board as c, pickPage as d, screenshotToFile as i, detectState as l, firstSideEffectPattern as n, listDocuments as o, hasSideEffects as r, openDocument as s, classifyEval as t, normalizeState as u };
1780
+ export { cdpInputActionSchema as a, listDocuments as c, detectState as d, normalizeState as f, screenshotToFile as i, openDocument as l, firstSideEffectPattern as n, sendCdpInput as o, pickPage as p, hasSideEffects as r, activeDocument as s, classifyEval as t, Board as u };
@@ -775,4 +775,4 @@ function formatFrameTree(rows) {
775
775
  }
776
776
  return lines;
777
777
  }
778
- export { CdpSession as a, evaluateExpression as c, redact as d, listTargets as i, evaluateInContext as l, flattenFrameTree as n, EvalUsageError as o, formatFrameTree as r, apiExpression as s, fetchFrameTree as t, planEval as u };
778
+ export { CdpSession as a, evaluateExpression as c, UI_SHELL_MARKERS as d, redact as f, listTargets as i, evaluateInContext as l, flattenFrameTree as n, EvalUsageError as o, formatFrameTree as r, apiExpression as s, fetchFrameTree as t, planEval as u };
@@ -3,7 +3,7 @@ import { o as readAssetJson } from "./assets-D48xh-kr.mjs";
3
3
  import { t as packageVersion } from "./version-B39-elun.mjs";
4
4
  import "./protocol-B4UcGrGa.mjs";
5
5
  import { i as execute, r as discover$1, s as windows, t as BridgeClientError } from "./client-_LVz5Zg0.mjs";
6
- import { a as CdpSession, c as evaluateExpression, i as listTargets } from "./targets-DiGwICXT.mjs";
6
+ import { a as CdpSession, c as evaluateExpression, i as listTargets } from "./targets-DYfgkrq3.mjs";
7
7
  import path from "node:path";
8
8
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
9
  import { createHash } from "node:crypto";