"""Explicit integration harness, not native browser Worker or network proof."""
import asyncio,json
from офлайн_стенд import ROOT,BROWSER,open_offline as detached
JS=r'''
const __OriginalURL=window.URL; window.URL=class extends __OriginalURL{constructor(s,b){super(s,b==='about:blank'?'https://fixture.invalid/':b)}};
async function __pack(v){if(v instanceof Blob){const a=new Uint8Array(await v.arrayBuffer());let z="";for(let i=0;i<a.length;i+=4096)z+=String.fromCharCode(...a.subarray(i,i+4096));return ["file",v.name||"ИС-файл",v.type,btoa(z),v.lastModified||0];}if(v===null)return ['null'];if(v instanceof ArrayBuffer||ArrayBuffer.isView(v)){const a=v instanceof ArrayBuffer?new Uint8Array(v):new Uint8Array(v.buffer,v.byteOffset,v.byteLength);let s='';for(let i=0;i<a.length;i+=4096)s+=String.fromCharCode(...a.subarray(i,i+4096));return ['bytes',btoa(s)];}if(Array.isArray(v))return ['array',await Promise.all(v.map(__pack))];if(typeof v==='object')return ['object',await Promise.all(Object.entries(v).map(async([k,x])=>[k,await __pack(x)]))];return [typeof v,v];}
function __unpack(p){switch(p[0]){case 'null':return null;case 'string':case 'number':case 'boolean':return p[1];case 'array':return p[1].map(__unpack);case 'object':return Object.fromEntries(p[1].map(([k,v])=>[k,__unpack(v)]));case 'bytes':return Uint8Array.from(atob(p[1]),c=>c.charCodeAt(0)).buffer;default:throw Error('Неизвестный вид тестового транспорта');}}
window.Worker=class{constructor(){this.stopped=false;}postMessage(m){__pack(m).then(x=>window.__bridge(x)).then(msgs=>{if(this.stopped)return;for(const data of msgs){if(this.stopped)break;this.onmessage?.({data:__unpack(data)});}}).catch(error=>{if(!this.stopped)this.onerror?.({message:String(error)});});}terminate(){this.stopped=true;}};
'''
async def open_offline(browser,relative,width=390,before_scripts=None):
 page,errors,requests=await detached(browser,relative,width,JS+'\n'+(before_scripts or ''))
 async def bridge(source,payload):
  proc=await asyncio.create_subprocess_exec('node',str(ROOT/'инструменты/мост-Node-потока-4-11.cjs'),cwd=ROOT,stdin=asyncio.subprocess.PIPE,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)
  try:out,err=await asyncio.wait_for(proc.communicate(json.dumps(payload,ensure_ascii=False).encode()),70)
  except BaseException:
   proc.kill();await proc.wait();raise
  if proc.returncode:raise RuntimeError('Мост Node: '+err.decode(errors='replace')[-2000:])
  return json.loads(out)
 await page.expose_binding('__bridge',bridge)
 # Details opened in the harness; this is not a claim about full keyboard disclosure.
 await page.evaluate("document.querySelectorAll('details').forEach(e=>e.open=true)")
 return page,errors,requests
