page.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. // This script runs in an isolated world without host bindings.
  2. const state = globalThis.__cfbrowserState ||= {
  3. document: `${Date.now()}-${Math.random()}`, snapshot: "", refs: new Map()
  4. };
  5. const clip = (s, n) => String(s || "").slice(0, n);
  6. // A stack of walkers visits open roots without expanding large child arrays.
  7. // The shared node budget includes shadow hosts and non-element nodes.
  8. function walk(root, mask, limit) {
  9. const state={scanned:0,truncated:false};
  10. state[Symbol.iterator]=function* () {
  11. if (!root) return;
  12. const stack=[document.createTreeWalker(root,NodeFilter.SHOW_ALL)];
  13. while(stack.length) {
  14. const node=stack[stack.length-1].nextNode();
  15. if (!node) { stack.pop();continue; }
  16. if (++state.scanned>limit) { state.truncated=true;return; }
  17. if(node.nodeType===Node.ELEMENT_NODE && node.shadowRoot)
  18. stack.push(document.createTreeWalker(node.shadowRoot,NodeFilter.SHOW_ALL));
  19. if((mask & (1 << (node.nodeType-1)))!==0) yield node;
  20. }
  21. };
  22. return state;
  23. }
  24. const textParent = n => n.parentElement || n.getRootNode().host || null;
  25. const text = (e, skipControls=false) => {
  26. if (!e) return "";
  27. let result="";
  28. for(const node of walk(e,NodeFilter.SHOW_TEXT,200)) {
  29. const parent=textParent(node);
  30. if (!parent || parent.closest("script,style,noscript,template")) continue;
  31. if (skipControls && parent.closest("input,select,textarea,button")) continue;
  32. result+=clip(node.data,2048-result.length)+" ";
  33. if(result.length>=2048) break;
  34. }
  35. return result.trim();
  36. };
  37. const visible = e => {
  38. const r = e.getBoundingClientRect(), s = getComputedStyle(e);
  39. return r.width > 0 && r.height > 0 && s.visibility !== "hidden" && s.display !== "none";
  40. };
  41. const name = e => {
  42. const labels=[];
  43. if (e.labels) for (let i=0;i<Math.min(e.labels.length,20);i++) labels.push(text(e.labels[i],true));
  44. const labelled = clip(e.getAttribute("aria-labelledby"),4096).split(/\s+/).slice(0,16)
  45. .filter(Boolean).map(id => text(e.getRootNode().getElementById(id))).join(" ");
  46. return clip(labelled || e.getAttribute("aria-label") ||
  47. labels.join(" ") ||
  48. e.getAttribute("alt") || e.getAttribute("title") ||
  49. (e.tagName === "INPUT" ? e.getAttribute("placeholder") : text(e)), 256).replace(/\s+/g," ").trim();
  50. };
  51. const role = e => e.getAttribute("role") || ({A:"link",BUTTON:"button",SELECT:"combobox",TEXTAREA:"textbox",TABLE:"table"}[e.tagName]) ||
  52. (e.tagName === "INPUT" ? ({checkbox:"checkbox",radio:"radio",submit:"button",button:"button"}[e.type] || "textbox") : "element");
  53. const fingerprint = e => [e.tagName, e.getAttribute("type"), role(e), name(e), e.getAttribute("href")].join("\u001f");
  54. function resolve(a) {
  55. const r = state.refs.get(a.ref);
  56. if (a.snapshotId !== state.snapshot || !r || !r.element.isConnected ||
  57. r.element.ownerDocument !== document || fingerprint(r.element) !== r.fingerprint) {
  58. return {error:"BROWSER_STALE_REF"};
  59. }
  60. return r.element;
  61. }
  62. function run(op, a) {
  63. if (op === "snapshot") {
  64. state.refs.clear(); state.snapshot = a.id;
  65. const elements = [], chunks = [], walker = walk(document.body || document.documentElement, NodeFilter.SHOW_ELEMENT,4000);
  66. let count = 0, chars = 0, truncated = false;
  67. for (const e of walker) {
  68. if (["SCRIPT","STYLE","NOSCRIPT","TEMPLATE"].includes(e.tagName) || !visible(e)) continue;
  69. if (e.matches("a[href],button,input:not([type=hidden]),select,textarea,[role],[tabindex],table")) {
  70. if (elements.length >= a.maxElements) { truncated = true; continue; }
  71. const ref = `e${++count}`;
  72. state.refs.set(ref, {element:e, fingerprint:fingerprint(e)});
  73. elements.push({ref,role:role(e),name:name(e),
  74. value:e.type === "password" || e.type === "file" ? "" : clip(e.value,256),
  75. disabled:!!e.disabled, checked:!!e.checked});
  76. }
  77. if (a.mode !== "interactive" && e.matches("h1,h2,h3,p,li,pre,td,th") && chars < a.textLimit) {
  78. const t = clip(text(e), Math.min(1000, a.textLimit - chars)).trim();
  79. if (t) { chunks.push(t); chars += t.length; }
  80. }
  81. }
  82. return {snapshotId:a.id,documentId:state.document,url:clip(location.href,8192),title:clip(document.title,512),
  83. kind:"dom-semantic",text:chunks.join("\n"),elements,truncated:truncated || walker.truncated,scanned:walker.scanned};
  84. }
  85. if (op === "state") return {url:clip(location.href,8192),ready:document.readyState,documentId:state.document};
  86. if (op === "wait") {
  87. if (a.kind === "url") return location.href.includes(a.value);
  88. if (a.kind === "ready") return document.readyState !== "loading";
  89. if (a.kind === "text" || a.kind === "textGone") {
  90. const walker = walk(document.body || document.documentElement, NodeFilter.SHOW_TEXT,4000);
  91. let s="";
  92. for (const n of walker) {
  93. if(s.length>=100000) break;
  94. if (textParent(n) && !textParent(n).closest("script,style,noscript,input[type=password]")) s += clip(n.textContent, 1000);
  95. }
  96. return a.kind === "text" ? s.includes(a.value) : !s.includes(a.value);
  97. }
  98. return false;
  99. }
  100. let e = a.ref ? resolve(a) : document.body;
  101. if (!e || e.error) return e || {error:"BROWSER_STALE_REF"};
  102. if (op === "read") {
  103. if (e.type === "password" || e.type === "file") return {url:location.href,text:"",rows:[],truncated:false};
  104. if (a.mode === "table") {
  105. let table = e.tagName === "TABLE" ? e : null;
  106. const tables=walk(e,NodeFilter.SHOW_ELEMENT,4000);
  107. if(!table) for(const candidate of tables) if(candidate.tagName==="TABLE") { table=candidate;break; }
  108. const rows=[]; let total=0, truncated=false;
  109. if (table) for (const row of table.rows) {
  110. if (rows.length >= 100 || total >= a.limit) { truncated=true;break; }
  111. const cells=[];
  112. for (let i=0;i<Math.min(row.cells.length,30);i++) {
  113. const cell=row.cells[i];
  114. const v=clip(text(cell),Math.min(512,a.limit-total)); total+=v.length;cells.push(v);
  115. }
  116. rows.push(cells);
  117. }
  118. return {url:clip(location.href,8192),rows,truncated:truncated || tables.truncated};
  119. }
  120. const walker=walk(e,NodeFilter.SHOW_TEXT,4000);let s="",truncated=false;
  121. for (const n of walker) {
  122. if (s.length >= a.limit) { truncated=true;break; }
  123. if (textParent(n) && !textParent(n).closest("script,style,noscript,input[type=password]")) s+=clip(n.textContent,Math.min(1000,a.limit-s.length))+" ";
  124. }
  125. return {url:clip(location.href,8192),text:s.trim(),truncated:truncated || walker.truncated};
  126. }
  127. if (op === "prepare") {
  128. if (!visible(e) || e.disabled) return {error:"BROWSER_TARGET_NOT_ACTIONABLE"};
  129. e.scrollIntoView({block:"center",inline:"center"});
  130. const r=e.getBoundingClientRect(), x=r.left+r.width/2,y=r.top+r.height/2;
  131. let hit=document.elementFromPoint(x,y);
  132. for(let depth=0;hit && hit.shadowRoot && depth<64;depth++) {
  133. const inner=hit.shadowRoot.elementFromPoint(x,y);
  134. if(!inner || inner===hit) break;
  135. hit=inner;
  136. }
  137. let actionable=false;
  138. for(let node=hit,depth=0;node && depth<64;node=node.getRootNode().host,depth++) {
  139. if(node===e || e.contains(node)) { actionable=true;break; }
  140. }
  141. if (!actionable) return {error:"BROWSER_TARGET_NOT_ACTIONABLE"};
  142. e.focus(); return {x,y,value:e.value || "",checked:!!e.checked,tag:e.tagName,type:e.type || "",readOnly:!!e.readOnly};
  143. }
  144. if (op === "mutation") {
  145. if (!visible(e) || e.disabled) return {error:"BROWSER_TARGET_NOT_ACTIONABLE"};
  146. if (a.action === "click") e.click();
  147. else if (a.action === "fill") {
  148. if (!e.matches("input,textarea") || e.type === "file" || e.readOnly) return {error:"BROWSER_TARGET_NOT_ACTIONABLE"};
  149. const proto=e.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
  150. Object.getOwnPropertyDescriptor(proto,"value").set.call(e,a.value);
  151. e.dispatchEvent(new Event("input",{bubbles:true}));e.dispatchEvent(new Event("change",{bubbles:true}));
  152. } else if (a.action === "select") {
  153. let found=false;
  154. if (e.tagName === "SELECT") for (let i=0;i<Math.min(e.options.length,1000);i++) if(e.options[i].value===a.value){found=true;break;}
  155. if (!found) return {error:"BROWSER_INVALID_ARGUMENT"};
  156. e.value=a.value;e.dispatchEvent(new Event("input",{bubbles:true}));e.dispatchEvent(new Event("change",{bubbles:true}));
  157. } else if (a.action === "check" || a.action === "uncheck") {
  158. if (!e.matches("input[type=checkbox],input[type=radio]")) return {error:"BROWSER_INVALID_ARGUMENT"};
  159. const target=a.action === "check"; if (e.checked!==target) e.click();
  160. } else if (a.action === "scroll") {
  161. const delta=a.value === "down" ? 500 : -500;
  162. if (e.scrollHeight>e.clientHeight) e.scrollBy(0,delta);else window.scrollBy(0,delta);
  163. } else return {error:"BROWSER_CAPABILITY_UNSUPPORTED"};
  164. return {value: e.type === "password" ? "" : clip(e.value,256),checked:!!e.checked};
  165. }
  166. return {error:"BROWSER_INVALID_ARGUMENT"};
  167. }