VibeCoding / src /apps /workbench /business_bridge.py
dellweb3's picture
Deploy verified conversational workbench and isolated Java application previews
5ca3c16 verified
Raw History Blame Contribute Delete
1.72 kB
"""Fixed child-side bridge injected into a sandboxed generated business page."""
import re
BRIDGE='''<script>
(()=>{let serial=0;const pending=new Map();
const bridge=(method,path)=>new Promise((resolve,reject)=>{
if(!['GET','POST'].includes(method)||typeof path!=='string'||path.length>500){reject(Error('请求格式无效'));return;}
const id='request-'+(++serial);const timer=setTimeout(()=>{pending.delete(id);reject(Error('请求超时,结果未确认'));},30000);
pending.set(id,{resolve,reject,timer});parent.postMessage({type:'zk-business-request',id,method,path},'*');
});
Object.defineProperty(window,'__zkBusinessBridge',{value:bridge,writable:false,configurable:false});
window.zkRequest=bridge;
addEventListener('message',event=>{const data=event.data;if(event.source!==parent||!data||data.type!=='zk-business-response')return;
const entry=pending.get(data.id);if(!entry)return;pending.delete(data.id);clearTimeout(entry.timer);
if(data.ok)entry.resolve(data.body);else entry.reject(Error(data.error||'操作未完成'));
});})();
</script>'''
def inject(page):
result,count=re.subn(r'<html\b[^>]*>',lambda match:match.group(0)+BRIDGE,page,count=1,flags=re.I)
if count!=1:raise ValueError('BUSINESS_PAGE_INVALID')
# Restore the trusted bridge after generated scripts; a model may accidentally
# declare a global function with the same name. Onload handlers run afterward.
restore='<script>window.zkRequest=window.__zkBusinessBridge;</script>'
result,count=re.subn(r'</body\s*>',lambda match:restore+match.group(0),result,count=1,flags=re.I)
if not count:result=re.sub(r'</html\s*>',lambda match:restore+match.group(0),result,count=1,flags=re.I)
return result