require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../common/src/webworker/workerFactory.cjs`),t=require(`./workerCDNUrls.cjs`),n=require(`./bridge/serialization.utils.cjs`),r=require(`./bridge/HinkalRNWorker.cjs`);let i=require(`react`),a=require(`react-native`),o=require(`react-native-webview`),s=require(`react/jsx-runtime`);var c=`${new URL(Object.values(t.WORKER_CDN_URLS)[0]).origin}/`;e.WorkerFactory.rnWorkerFactory=e=>new r.HinkalRNWorker(e);var l=`
if (!window.__hinkalPageBoot) (function(){
  window.__hinkalPageBoot = true;
  var URLS = ${JSON.stringify(t.WORKER_CDN_URLS)};
  var BLOBS = {};

  function replacer(_key, value){
    if (typeof value === 'bigint') return { __bigint: value.toString() };
    if (value instanceof Set) return { __set: Array.from(value) };
    if (value instanceof Map) return { __map: Array.from(value.entries()) };
    return value;
  }
  function revive(value){
    if (value === null || typeof value !== 'object') return value;
    var keys = Object.keys(value);
    if (keys.length === 1) {
      if (typeof value.__bigint === 'string') return BigInt(value.__bigint);
      if (Array.isArray(value.__set)) return new Set(value.__set.map(revive));
      if (Array.isArray(value.__map)) return new Map(value.__map.map(function(entry){ return [revive(entry[0]), revive(entry[1])]; }));
    }
    if (Array.isArray(value)) return value.map(revive);
    var out = {}; for (var i = 0; i < keys.length; i++) out[keys[i]] = revive(value[keys[i]]); return out;
  }
  function post(payload){ try { window.ReactNativeWebView.postMessage(JSON.stringify(payload, replacer)); } catch(_){} }
  function describe(error){
    if (!error) return 'worker error';
    if (error.message) return error.message;
    if (error.error && error.error.stack) return error.error.stack;
    try { return JSON.stringify(error); } catch(_){ return String(error); }
  }

  async function blobUrl(url){
    if (BLOBS[url]) return BLOBS[url];
    var response = await fetch(url);
    if (!response.ok) throw new Error('HTTP ' + response.status + ' ' + url);
    var body = await response.text();
    BLOBS[url] = URL.createObjectURL(new Blob([${JSON.stringify(`(function(){
  var post = self.postMessage.bind(self);
  function describe(error){
    if (!error) return 'unknown';
    var parts = [];
    if (error.message) parts.push(error.message);
    if (error.error && error.error.stack) parts.push(error.error.stack);
    if (!parts.length) { try { parts.push(JSON.stringify(error)); } catch(_) { parts.push(String(error)); } }
    return parts.join(' | ');
  }
  self.addEventListener('error', function(event){ try { post({ __hinkalWorkerError: describe(event) }); } catch(_){} });
  self.addEventListener('unhandledrejection', function(event){ try { post({ __hinkalWorkerError: 'unhandledrejection: ' + describe(event && event.reason) }); } catch(_){} });
  try { post({ __hinkalWorkerReady: true }); } catch(_){}
})();`)}, body], { type: 'application/javascript' }));
    return BLOBS[url];
  }

  function spawn(url){
    try { return new Worker(url, { type: 'module' }); } catch(_){ return new Worker(url); }
  }

  window.handleMessage = async function(envelope){
    var requestId = envelope && envelope.requestId;
    var variant = envelope && envelope.variant;
    var message = revive(envelope && envelope.message);
    var url = URLS[variant];
    if (!url) return post({ requestId: requestId, type: 'ERROR', error: 'Unknown variant: ' + variant });

    var worker;
    try { worker = spawn(await blobUrl(url)); }
    catch (error) { return post({ requestId: requestId, type: 'ERROR', error: 'spawn failed: ' + describe(error) }); }

    var done = false, ready = false, pending = message;
    function finish(){ if (done) return; done = true; try { worker.terminate(); } catch(_){} }

    worker.onmessage = function(event){
      var data = event && event.data;
      if (data && typeof data === 'object') {
        if (data.__hinkalWorkerReady) {
          ready = true;
          try { worker.postMessage(pending); pending = null; }
          catch (error) { post({ requestId: requestId, type: 'ERROR', error: 'postMessage failed: ' + describe(error) }); finish(); }
          return;
        }
        if (typeof data.__hinkalWorkerError === 'string') {
          post({ requestId: requestId, type: 'ERROR', error: data.__hinkalWorkerError });
          finish();
          return;
        }
      }
      post({ requestId: requestId, type: 'RESULT', data: data });
      finish();
    };
    worker.onerror = function(event){
      post({ requestId: requestId, type: 'ERROR', error: (ready ? 'worker runtime: ' : 'worker startup: ') + describe(event) });
      finish();
    };
  };

  post({ type: 'READY' });
})();
true;`,u=`<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body><script>${l}<\/script></body></html>`,d=a.StyleSheet.create({hiddenHost:{position:`absolute`,height:1,width:1,left:-9999,top:-9999,opacity:0}}),f=()=>{let e=(0,i.useRef)(null),t=(0,i.useRef)({ready:!1,queue:[]}),r=(0,i.useCallback)((t,r,i)=>{console.log(`inject`,t,r,i);let o;try{o=JSON.stringify({requestId:t,variant:r,message:i},n.bigIntReplacer)}catch(e){a.DeviceEventEmitter.emit(`FROM_WEBVIEW_WORKER`,{requestId:t,type:`ERROR`,error:`serialize failed: ${e?.message??e}`});return}e.current?.injectJavaScript(`window.handleMessage && window.handleMessage(${o}); true;`)},[]);(0,i.useEffect)(()=>{let e=a.DeviceEventEmitter.addListener(`TO_WEBVIEW_WORKER`,e=>{console.log(`TO_WEBVIEW_WORKER`,e);let n={requestId:e?.__requestId??``,variant:e?.variant??``,message:e?.message};t.current.ready?r(n.requestId,n.variant,n.message):t.current.queue.push(n)});return()=>e.remove()},[r]);let f=(0,i.useCallback)(e=>{console.log(`onMessage`,e),console.log(`event.nativeEvent.data`,e.nativeEvent.data);let i;try{i=n.reviveBigInts(JSON.parse(e.nativeEvent.data))}catch(e){a.DeviceEventEmitter.emit(`FROM_WEBVIEW_WORKER`,{type:`ERROR`,error:e?.message??`parse error`});return}if(i?.type===`READY`){t.current.ready=!0;let e=t.current.queue;t.current.queue=[],e.forEach(({requestId:e,variant:t,message:n})=>r(e,t,n));return}a.DeviceEventEmitter.emit(`FROM_WEBVIEW_WORKER`,i)},[r]);return(0,s.jsx)(a.View,{pointerEvents:`none`,style:d.hiddenHost,children:(0,s.jsx)(o.WebView,{ref:e,source:{html:u,baseUrl:c},originWhitelist:[`*`],javaScriptEnabled:!0,domStorageEnabled:!0,androidLayerType:`hardware`,onMessage:f,onLoad:()=>e.current?.injectJavaScript(l)})})};module.exports=f;