@blueking/bk-weweb 0.0.32 → 0.0.34

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.
package/dist/index.esm.js CHANGED
@@ -1,30 +1,2336 @@
1
- var _e=null;function F(){return _e}function T(r){_e=r}var N=new Map,Fe=`const { ${["Array","ArrayBuffer","Boolean","constructor","DataView","Date","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","Error","escape","eval","EvalError","Float32Array","Float64Array","Function","hasOwnProperty","Infinity","Int16Array","Int32Array","Int8Array","isFinite","isNaN","isPrototypeOf","JSON","Map","Math","NaN","Number","Object","parseFloat","parseInt","Promise","propertyIsEnumerable","Proxy","RangeError","ReferenceError","Reflect","RegExp","Set","String","Symbol","SyntaxError","toLocaleString","toString","TypeError","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray","undefined","unescape","URIError","valueOf","WeakMap","WeakSet"].join(",")} }= this;`,Q=()=>Fe,je=()=>{let r=Object.getOwnPropertyNames(window);for(let e of r)!N.has(e)&&e.match(/^[A-Z]/)&&typeof window[e]=="function"&&window[e].toString().includes("[native code]")&&N.set(e,!0)};je();var I="id";var K=(o=>(o.APP="app",o.CONFIG="config",o.INSTANCE="js",o))(K||{});var Ce=["System","__cjsWrapper",""],j=["__POWERED_BY_BK_WEWEB__","__BK_WEWEB_APP_KEY__","__BK_WEWEB_DATA__"],Me=["window","self","globalThis"],ee=["location","history"],Ye={__bk_pop_manager:!0,__bk_zIndex_manager:!0,i18n:!0},Te=Ye;var D=r=>Promise.resolve().then(r);function x(r){return r.startsWith("//")?`${location.protocol}${r}`:r.startsWith("http")?r:`${location.protocol}//${r}`}function h(r,e){if(!r||/^((((ht|f)tps?)|file):)?\/\//.test(r)||/^(data|blob):/.test(r))return r;let{origin:t,pathname:o}=new URL(x(e));return new URL(r,`${t}${o}`.replace(/\.(\w+)$/,"/")).toString()}function L(){return`inline-${W(16)}`}var Y=window.requestIdleCallback||(r=>{let e=Date.now();return setTimeout(()=>{r({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-e))}})},1)}),St=window.cancelIdleCallback||(r=>{clearTimeout(r)}),W=(r,e="abcdefghijklmnopqrstuvwxyz0123456789")=>{let t="";for(let o=0;o<r;o++)t+=e[Number.parseInt((Math.random()*e.length).toString(),10)];return t},J=r=>{if(!r||r.match(/\.js$/))return!1;let{pathname:e}=new URL(x(r));return!e.match(/\.js$/)};var te=["body","html","head"],oe=(r,e)=>{let t={};function o(d,f){let m=document.createElement("div");m.innerHTML=f;let b=Array.from(m.childNodes),B=e.container;switch(d){case"beforebegin":b.forEach(P=>B.host.parentNode?.insertBefore(P,B.host));break;case"afterbegin":b.reverse().forEach(P=>B.insertBefore(P,B.firstChild));break;case"beforeend":b.forEach(P=>B.appendChild(P));break;case"afterend":b.forEach(P=>B.host.parentNode?.insertBefore(P,B.host.nextSibling));break}}let n=new Proxy({},{get(d,f){if(e.container instanceof ShadowRoot){if(f==="insertAdjacentHTML")return o.bind(e.container);let b=e.container[f];if(typeof b=="function")return b.bind(e.container);if(b!==void 0)return b}let m=Reflect.get(r.body,f);return typeof m=="function"?m.bind(r.body):m},set(d,f,m){return e.container instanceof ShadowRoot?(e.container[f]=m,!0):(Reflect.set(r.body,f,m),!0)}});function i(d,f){let m=r.createElement(d,f);return m.__BK_WEWEB_APP_KEY__=e.appCacheKey,m}function c(d){if(d===n)return e.container instanceof ShadowRoot?e.container:r.body;if(te.includes(d))return e?.container instanceof ShadowRoot?e?.container:r.querySelector.call(this,d);try{return e?.container?.querySelector(d)??null}catch{return null}}function s(d){return te.includes(d)?e?.container instanceof ShadowRoot?e?.container:r.querySelector(d):e?.container?.querySelectorAll(d)??[]}function u(d){return c.call(r,`#${d}`)}function l(d){return s(`.${d}`)}function p(d){return te.includes(d)||!e?.showSourceCode&&d.toLocaleLowerCase()==="script"?r.getElementsByTagName(d):s(d)}function S(d){return s(`[name=${d}]`)}return new Proxy(t,{get(d,f){if(f==="createElement")return i.bind(r);if(f==="querySelector")return c.bind(r);if(f==="querySelectorAll")return s.bind(r);if(f==="getElementById")return u.bind(r);if(f==="getElementsByClassName")return l.bind(r);if(f==="getElementsByTagName")return p.bind(r);if(f==="getElementsByName")return S.bind(r);if(f==="body")return n;let m=Reflect.get(r,f);return typeof m=="function"?m.bind(r):m}})};function xe(){let{addEventListener:r,removeEventListener:e}=window.document,{addEventListener:t,removeEventListener:o}=window.document.body,n=new Map;document.addEventListener=function(c,s,u){let l=F();if(l?.keepAlive){let p=n.get(c)||[];n.set(c,[...p,s])}r.call(l?.container instanceof ShadowRoot?l.container:this,c,s,u)},document.body.addEventListener=document.addEventListener,document.removeEventListener=function(c,s,u){let l=F();if(l?.keepAlive){let p=n.get(c)||[];p.length&&p.some(S=>S===s)&&p.splice(p.indexOf(s),1)}e.call(l?.container instanceof ShadowRoot?l.container:this,c,s,u)},document.body.removeEventListener=document.removeEventListener;function i(){F()?.keepAlive&&n.values()&&Array.from(n.entries()).forEach(([s,u])=>{u?.forEach(l=>{document.removeEventListener.call(document,s,l)})}),document.addEventListener=r,document.body.addEventListener=t,document.removeEventListener=e,document.body.removeEventListener=o,n.clear()}return{resetDocumentAndBodyEvent:i}}var Je=/^class\b/,Ve=/^function\b\s[A-Z].*/,re=new WeakMap;function Ge(r){if(r.prototype?.constructor===r&&Object.getOwnPropertyNames(r.prototype).length>1)return!0;if(re.has(r))return re.get(r);let e=Ve.test(r.toString())||Je.test(r.toString());return re.set(r,e),e}var ne=new WeakMap;function ie(r,e){if(ne.has(e))return ne.get(e);if(typeof e=="function"&&!Ge(e)){let t=Function.prototype.bind.call(e,r);for(let o in e)t[o]=e[o];if(e.hasOwnProperty("prototype")&&!t.hasOwnProperty("prototype")&&Object.defineProperty(t,"prototype",{enumerable:!1,value:e.prototype,writable:!0}),typeof e.toString=="function"){let o=e.hasOwnProperty("toString")&&!t.hasOwnProperty("toString"),n=t.toString===Function.prototype.toString;if(o||n){let i=Object.getOwnPropertyDescriptor(o?e:Function.prototype,"toString");Object.defineProperty(t,"toString",{...i,...i?.get?null:{value:()=>e.toString()}})}}return ne.set(e,t),t}return e}function Le(r){let e=new Map,t=[],o=window,{addEventListener:n,clearInterval:i,removeEventListener:c,setInterval:s}=window;r.addEventListener=(l,p,S)=>{e.set(l,[...e.get(l)||[],p]),n.call(o,l,p,S)},r.removeEventListener=(l,p,S)=>{let d=e.get(l);if(d?.length){let f=d.indexOf(p);f>-1&&d.splice(f,1)}c.call(o,l,p,S)},r.setInterval=(l,p,...S)=>{let d=s.call(o,l,p,...S);return t.push(d),d},r.clearInterval=l=>{let p=t.indexOf(l);p>-1&&t.splice(p,1),i.call(o,l)};function u(){e.size&&(e.forEach((l,p)=>{l.forEach(S=>c.call(o,p,S))}),e.clear()),t.length&&t.forEach(l=>{i.call(o,l)})}return{resetWindowFunction:u}}var R=class{constructor(e){this.app=e;let t=new Set,o=window;this.rawWindow=o,this.rawDocument=oe(document,e);let n=Object.create({});n.__BK_WEWEB_APP_KEY__=e.appCacheKey,n.__POWERED_BY_BK_WEWEB__=!0,n.rawDocument=document,n.rawWindow=o,n.__proto__=Window,this.fakeWindow=n;let{resetWindowFunction:i}=Le(this.fakeWindow);this.resetWindowFunction=i,this.windowSymbolKey=`__${(e.name||e.appCacheKey).replace(/(-|,|:|~|'|")/gim,"_")}_${W(10)}__`,this.proxyWindow=new Proxy(this.fakeWindow,{defineProperty:(c,s,u)=>t.has(s)?Reflect.defineProperty(o,s,u):Reflect.defineProperty(c,s,u),deleteProperty:(c,s)=>Object.hasOwn(c,s)?(this.sameRawWindowKeySet.has(s)&&this.sameRawWindowKeySet.delete(s),this.inRawWindowKeySet.has(s)&&Reflect.deleteProperty(o,s),Reflect.deleteProperty(c,s)):!0,get:(c,s)=>{if(s===Symbol.unscopables||N.has(s))return o[s];if(Te[s])return this.fakeWindow[s];if(Me.includes(s))return this.proxyWindow;if(s==="document")return e.registerRunningApp(),this.rawDocument;if(s==="eval")return e.registerRunningApp(),eval;if(ee.includes(s)&&this.app instanceof A&&this.app.iframe&&this.app.scopeLocation)return this.app.iframe.contentWindow?.[s];if(s==="hasOwnProperty")return l=>Object.hasOwn(this.fakeWindow,l)||Object.hasOwn(o,l);if(s==="top"||s==="parent")return o===o.parent?this.proxyWindow:Reflect.get(o,s);if(s==="getComputedStyle")return(l,p)=>l instanceof Element?o.getComputedStyle(l,p):o.getComputedStyle(document.body,p);if(Reflect.has(c,s)||j.includes(s))return Reflect.get(c,s);let u=Reflect.get(o,s);return ie(o,u)},getOwnPropertyDescriptor:(c,s)=>{if(Object.hasOwn(c,s))return Object.getOwnPropertyDescriptor(c,s);if(Object.hasOwn(o,s)){t.add(s);let u=Object.getOwnPropertyDescriptor(o,s);return u&&!u.configurable&&(u.configurable=!0),u}},has:(c,s)=>N.has(s)||s in c||s in o,ownKeys:c=>Array.from(new Set(Reflect.ownKeys(o).concat(Reflect.ownKeys(c)))),set:(c,s,u)=>{if(this.active){if(ee.includes(s)&&this.app instanceof A&&this.app.iframe&&this.app.scopeLocation)return Reflect.set(this.app.iframe.contentWindow,s,u);if(s==="location")Reflect.set(o,s,u);else if(!Object.hasOwn(c,s)&&Object.hasOwn(o,s)&&!j.includes(s)){let l=Object.getOwnPropertyDescriptor(o,s),{configurable:p,enumerable:S,writable:d}=l;d&&(Object.defineProperty(c,s,{configurable:p,enumerable:S,value:u,writable:d}),this.sameRawWindowKeySet.add(s))}else Reflect.set(c,s,u),this.sameRawWindowKeySet.add(s);Ce.includes(s)&&!Reflect.has(o,s)&&!j.includes(s)&&(Reflect.set(o,s,u),this.inRawWindowKeySet.add(s))}return!0}}),o[this.windowSymbolKey]=this.proxyWindow}active=!1;inRawWindowKeySet=new Set;resetDocumentAndBodyEvent;resetWindowFunction;sameRawWindowKeySet=new Set;fakeWindow;proxyDocument;proxyWindow;rawDocument;rawWindow;windowSymbolKey;activated(e){if(!this.active){this.active=!0,this.rawDocument=oe(document,this.app),this.fakeWindow.__BK_WEWEB_DATA__=e??{};let{resetDocumentAndBodyEvent:t}=xe();this.resetDocumentAndBodyEvent=t}}deactivated(){if(this.active){this.active=!1,this.resetWindowFunction();for(let e of this.inRawWindowKeySet)Reflect.deleteProperty(window,e);this.inRawWindowKeySet.clear(),this.resetDocumentAndBodyEvent?.()}}};var qe=["currentTarget","srcElement","target"];function ve(r,e="custom"){return Object.defineProperties(new CustomEvent(e),qe.reduce((t,o)=>(t[o]={get(){return r}},t),{}))}function _(r){let e=ve(r,"load");if(typeof r.onload=="function"){r.onload(e);return}r.dispatchEvent(e)}function U(r){let e=ve(r,"error");if(typeof r.onerror=="function"){r.onerror(e);return}r.dispatchEvent(e)}var{appendChild:Be}=HTMLBodyElement.prototype;function Pe(r,e,t){if(e instanceof HTMLStyleElement){if(e.hasAttribute("exclude"))return document.createComment("\u3010bk-weweb\u3011style with exclude attribute is ignored");if(e.textContent&&!(t.container instanceof ShadowRoot)&&a.getBaseAppStyle(e.textContent))return document.createComment("\u3010bk-weweb\u3011style is effective in base app");if(!e.hasAttribute("ignore")){let o=new w({code:e.textContent||"",fromHtml:!1,url:""});t.source?.setStyle(L(),o),o.scopedStyleCSS(t,e)}return e}if(e instanceof HTMLLinkElement){let o=t.source?.collectLink(e,r,!0);return o?(o.style&&o.style.scopedLinkCSS(t,e),o.replace!==e?o.replace:e):e}if(e instanceof HTMLScriptElement){let o=t.source.collectScript(e,r,!0);if(!o)return e;if(o.script&&o.script.executeCode(t),o.replace!==e)return o.replace;if(t.scopeJs&&!e.getAttribute("src")&&!e.textContent){let n=new MutationObserver(()=>{if(e.getAttribute("src")){n.disconnect();let i=t.source.collectScript(e,r,!0);if(i?.replace&&Be.call(t.container,i.replace),J(e.getAttribute("src"))){t.container?.append(e);return}i?.script&&i.script.executeCode(t),e.remove()}else if(e.textContent){n.disconnect();let i=new y({async:!1,code:e.textContent,defer:e.type==="module",fromHtml:!1,isModule:e.type==="module"});t.source.scripts.set(L(),i);try{i.executeCode(t)}catch(c){console.error(c)}finally{!i.isModule&&_(e),e.remove()}}});return n.observe(e,{attributeFilter:["src"],childList:!0,subtree:!1}),document.createComment("\u3010bk-weweb\u3011dynamic script or module")}return e}return e}function k(r){return r instanceof HTMLScriptElement||r instanceof HTMLStyleElement||r instanceof HTMLLinkElement}function se(r,e,t){if(e.__BK_WEWEB_APP_KEY__){let o=a.getApp(e.__BK_WEWEB_APP_KEY__);if(o?.container){let n=Pe(r,e,o),i=k(e)&&!!o.keepAlive&&!(o.container instanceof ShadowRoot),c=i?document.head:o?.container;return E(n,o,i),t.call(c,n)}}return t.call(r,e)}function ce(r,e,t,o){if(e.__BK_WEWEB_APP_KEY__){let n=a.getApp(e.__BK_WEWEB_APP_KEY__);if(n?.container){let i=k(e)&&n.keepAlive&&!(n.container instanceof ShadowRoot),c=i?document.head:n?.container,s=Pe(r,e,n);return i&&E(s,n,i),t&&!c.contains(t)?Be.call(c,s):o.call(c,s,t)}}return o.call(r,e,t)}function E(r,e,t){return t&&e&&(r.__KEEP_ALIVE__=e.appCacheKey,r.setAttribute("data-from",e.name),r.setAttribute("data-keep-alive","true")),r.setAttribute?.("powered-by","bk-weweb"),r}function g(r,e={},t){return typeof t?.fetchSource=="function"?t.fetchSource(r,e).catch(()=>""):ae.fetchSource?ae.fetchSource(r,e):window.fetch(r,e).then(o=>o.text())}var w=class{code="";fromHtml;initial;prefetch=!1;preload=!1;scoped;scopedCode="";url;constructor({code:e,fromHtml:t,initial:o,prefetch:n,preload:i,url:c}){this.scoped=!1,this.code=e,this.prefetch=n??!1,this.preload=i??!1,this.url=c,this.fromHtml=t,this.initial=o??!1}commonScoped(e,t){if(t.scopeCss&&!(t.container instanceof ShadowRoot)){let o=new CSSStyleSheet({disabled:!0});o.replaceSync(e.textContent||this.code);let n=Array.from(o?.cssRules??[]),i=`#${t.name}`,c=this.scopeRule(n,i),s=this.resetUrlHost(c,t.url,this.url);e.textContent=s,this.scopedCode=s}else{let o=this.resetUrlHost(e.textContent||this.code||"",t.url,this.url);if(o&&t.container instanceof ShadowRoot){let n="";o.match(/@font-face\s*\{[^}]+\}/g)?.forEach(c=>{n+=`${c}
2
- `});let i=t.sandBox?.rawDocument;if(i&&n){let c=i.createElement("style");c.setAttribute("type","text/css"),c.setAttribute("powered-by","bk-weweb"),c.textContent=n,i?.head?.append(c)}}e.textContent=o}this.scoped=!0}createStyleElement(){let e=document.createElement("style");return e.__BK_WEWEB_APP_KEY__&&(e.__BK_WEWEB_APP_KEY__=void 0),e}async executeCode(e){e.registerRunningApp();let t=this.createStyleElement();t.setAttribute("type","text/css"),t.textContent=this.code;try{this.code||await this.getCode(e),t=this.scopedStyleCSS(e,t),this.scoped=!0}catch(o){console.error("scoped style error",o)}return t}async getCode(e){if(this.code.length||!this.url)return this.code;let t="";return e?.source?.styles?.has(this.url)&&(t=e.source.styles.get(this.url)?.code||""),!t&&a.getCacheStyle(this.url)&&(t=a.getCacheStyle(this.url)?.code||""),t||(t=await g(this.url,{},e).catch(()=>"")),this.code=t,t}linkedBaseStyle(e,t){return!(t.container instanceof ShadowRoot)&&e.textContent&&a.getBaseAppStyle(e.textContent)?(e.textContent="",e.innerHTML="",e.setAttribute("linked-from-base","true"),!0):!1}resetPackRule(e,t,o){let n=this.scopeRule(Array.from(e.cssRules),t);return`@${o} ${e.conditionText} {${n}}`}resetUrlHost(e,t,o){let n=t;return e.replace(/url\(["']?([^)"']+)["']?\)/gm,(i,c)=>{if(/^(data|blob):/.test(c)||/^(https?:)?\/\//.test(c))return i;if(/^((\.\.?\/)|[^/])/.test(c)&&o){let s=o.split("/");s.pop(),n=x(`${s.join("/")}/`)}return`url("${h(c,n)}")`})}scopeRule(e,t){let o="";for(let n of e)switch(n.type){case 1:o+=this.scopeStyleRule(n,t);break;case 4:o+=this.resetPackRule(n,t,"media");break;case 12:o+=this.resetPackRule(n,t,"supports");break;default:o+=n.cssText;break}return o.replace(/^\s+/,"")}scopeStyleRule(e,t){let{cssText:o,selectorText:n}=e;if(/^((html[\s>~,]+body)|(html|body|:root))$/.test(n))return o.replace(/^((html[\s>~,]+body)|(html|body|:root))/,t);if(n==="*")return o.replace("*",`${t} *`);let i=/(^|\s+)((html[\s>~]+body)|(html|body|:root))(?=[\s>~]+|$)/;return o.replace(/^[\s\S]+{/,c=>c.replace(/(^|,)([^,]+)/g,(s,u,l)=>i.test(l)?s.replace(i,t):`${u} ${t} ${l.replace(/^\s*/,"")}`))}scopedLinkCSS(e,t){let o=this.createStyleElement();o.setAttribute("type","text/css");let n=!!e.keepAlive&&!(e.container instanceof ShadowRoot);E(o,e,n);let i=n?document.head:e.container;try{if(this.code)this.commonScoped(o,e),i?.prepend(o),t&&_(t);else if(t.getAttribute("href"))this.url=h(t.getAttribute("href"),e.url),this.getCode(e).then(()=>{this.scopedStyleCSS(e,o),t.remove(),i?.prepend(o),t&&_(t),this.scoped=!0});else{let c=new MutationObserver(()=>{t.href&&(c.disconnect(),this.url=h(t.getAttribute("href"),e.url),this.getCode(e).then(()=>{this.scopedStyleCSS(e,o),t.remove(),i?.prepend(o),t&&_(t),this.scoped=!0}))});c.observe(t,{attributeFilter:["href"],childList:!1,subtree:!1})}}catch{t&&U(t)}return o}scopedStyleCSS(e,t){let o=!!e.keepAlive&&!(e.container instanceof ShadowRoot);if(E(t,e,o),this.code||t.textContent){if(t.textContent&&(t.textContent="",t.innerHTML=""),this.linkedBaseStyle(t,e))return t;this.commonScoped(t,e)}else{let n=new MutationObserver(()=>{(t.textContent||t.sheet?.cssRules?.length)&&(n.disconnect(),this.linkedBaseStyle(t,e)||this.commonScoped(t,e))});n.observe(t,{attributes:!1,characterData:!0,childList:!0,subtree:!0})}return this.url&&t.setAttribute("origin-src",this.url),t}};async function V(r,e){let t=Array.from(r.source.styles.values()),o=[];for(let n of t)o.push(n.executeCode(r));await Promise.all(o).then(n=>{let i=e||r.container;r.keepAlive&&!(i instanceof ShadowRoot)?document.head.append(...n):i?.append(...n)})}var C=class{state="UNSET";appCacheKey;container;data;initSource;isPreLoad=!1;keepAlive;name;sandBox;scopeCss=!0;scopeJs=!1;showSourceCode=!0;source;url;fetchSource;constructor(e){this.name=e.id!==e.url?e.id:W(5),this.appCacheKey=e.id||this.name,this.url=e.url,this.container=e.container??void 0,this.scopeJs=e.scopeJs??!0,this.showSourceCode=e.showSourceCode??!0,this.scopeCss=e.scopeCss??!0,this.keepAlive=e.keepAlive??!1,this.data=e.data??{},this.initSource=e.initSource??[],this.scopeJs&&(this.sandBox=new R(this)),this.fetchSource=e.fetchSource}activated(e,t){if(this.isPreLoad=!1,this.state="ACTIVATED",this.container&&e){e instanceof Element&&e?.setAttribute(I,this.name);let o=document.createDocumentFragment();for(let i of Array.from(this.container.childNodes))o.appendChild(i);e.appendChild(o),this.container=e,this.sandBox?.activated();let n=this.source?.getScript(this.url);t?.(this,n?.exportInstance)}}deactivated(){this.state="DEACTIVATED",this.sandBox?.deactivated()}mount(e,t){this.isPreLoad=!1,this.container=e??this.container,this.state="MOUNTING",this.container instanceof HTMLElement&&this.container?.setAttribute(I,this.name),this.container.innerHTML="";let o=document.createElement("div"),n=`${this.name}-wrapper`;o.setAttribute("id",n),this.source?.styles.size&&V(this,this.container),this.container.appendChild(o),this.sandBox?.activated(),G(this).finally(()=>{this.state="MOUNTED";let i=this.source?.getScript(this.url);typeof i?.exportInstance?.render=="function"&&i.exportInstance.render(o,this.data),t?.(this,i?.exportInstance)})}onError(){this.state="ERROR"}onMount(){this.isPreLoad||(this.state="LOADED",this.mount())}registerRunningApp(){T(this),Promise.resolve().then(()=>T(null))}async start(){(!this.source||["ERROR","UNSET"].includes(this.status))&&(this.source=new v(this.url),await this.source.importEntry(this))}unmount(e){this.state="UNMOUNT",this.sandBox?.deactivated(),e&&a.deleteApp(this.url),this.container.innerHTML="",this.container=void 0}set status(e){this.state=e}get status(){return this.state}};var q,$,z,y=class{async=!1;code="";defer=!1;exportInstance;fromHtml;initial;isModule=!1;scoped;url;constructor({async:e,code:t,defer:o,fromHtml:n,initial:i,isModule:c,url:s}){this.code=t,this.async=e,this.defer=o,this.isModule=c,this.url=s,this.scoped=!1,this.fromHtml=n??!1,this.initial=i??!1}async executeCode(e,t=!1){try{if(this.code||await this.getCode(e),e instanceof C){let n=e.scopeJs&&e.sandBox?.proxyWindow||window;Ze(n)}let o=this.code;if(o=this.transformCode(e),e.showSourceCode||this.isModule){let n=document.createElement("script");if(n.__BK_WEWEB_APP_KEY__&&(n.__BK_WEWEB_APP_KEY__=void 0),e.registerRunningApp(),this.executeSourceScript(n,o),t)return n;let i=!!e.keepAlive&&!(e.container instanceof ShadowRoot),c=i?document.head:e.container;E(n,e,i),c.appendChild(n)}else if(this.executeMemoryScript(e,o),t)return document.createComment("\u3010bk-weweb\u3011dynamic script");if(e instanceof C){let n=e.scopeJs&&e.sandBox?.proxyWindow||window,i=ze(n);i&&(this.exportInstance=n[i],e.scopeJs||delete n[i])}}catch(o){console.error("execute script code error",o)}}executeMemoryScript(e,t){try{let o=e instanceof A&&e.scopeLocation;e.registerRunningApp(),new Function("window","location","history",t)(e.sandBox.proxyWindow,o?e.iframe.contentWindow.location:window.location,o?e.iframe.contentWindow.history:window.history)}catch(o){console.error(o)}}executeSourceScript(e,t){this.isModule?(e.src=`${this.url}?key=${Date.now()}`,e.setAttribute("type","module")):e.textContent=t,this.url&&e.setAttribute("origin-src",this.url)}async getCode(e){if(this.code.length||!this.url)return this.code;let t="";return e?.source?.getScript(this.url)&&(t=e.source.getScript(this.url)?.code||""),!t&&a.getCacheScript(this.url)&&(t=a.getCacheScript(this.url)?.code||""),t||(t=await g(this.url,{},e).catch(o=>(console.error(`fetch script ${this.url} error`,o),""))),t=t.replace(/^"use\sstrict";$/gim,""),this.code=t,t}setCode(e){this.code=e}transformCode(e){let t=this.url?`//# sourceURL=${this.url}
3
- `:"";return e.sandBox?this.isModule?` with(window.${e.sandBox.windowSymbolKey}){
1
+ // src/context/cache.ts
2
+ var currentRunningApp = null;
3
+ function getCurrentRunningApp() {
4
+ return currentRunningApp;
5
+ }
6
+ function setCurrentRunningApp(appInstance) {
7
+ currentRunningApp = appInstance;
8
+ }
9
+ var windowNativeFuncMap = /* @__PURE__ */ new Map();
10
+ var globalContextCode = `const { ${[
11
+ "Array",
12
+ "ArrayBuffer",
13
+ "Boolean",
14
+ "constructor",
15
+ "DataView",
16
+ "Date",
17
+ "decodeURI",
18
+ "decodeURIComponent",
19
+ "encodeURI",
20
+ "encodeURIComponent",
21
+ "Error",
22
+ "escape",
23
+ "eval",
24
+ "EvalError",
25
+ "Float32Array",
26
+ "Float64Array",
27
+ "Function",
28
+ "hasOwnProperty",
29
+ "Infinity",
30
+ "Int16Array",
31
+ "Int32Array",
32
+ "Int8Array",
33
+ "isFinite",
34
+ "isNaN",
35
+ "isPrototypeOf",
36
+ "JSON",
37
+ "Map",
38
+ "Math",
39
+ "NaN",
40
+ "Number",
41
+ "Object",
42
+ "parseFloat",
43
+ "parseInt",
44
+ "Promise",
45
+ "propertyIsEnumerable",
46
+ "Proxy",
47
+ "RangeError",
48
+ "ReferenceError",
49
+ "Reflect",
50
+ "RegExp",
51
+ "Set",
52
+ "String",
53
+ "Symbol",
54
+ "SyntaxError",
55
+ "toLocaleString",
56
+ "toString",
57
+ "TypeError",
58
+ "Uint16Array",
59
+ "Uint32Array",
60
+ "Uint8Array",
61
+ "Uint8ClampedArray",
62
+ "undefined",
63
+ "unescape",
64
+ "URIError",
65
+ "valueOf",
66
+ "WeakMap",
67
+ "WeakSet"
68
+ ].join(",")} }= this;`;
69
+ var getGlobalContextCode = () => {
70
+ return globalContextCode;
71
+ };
72
+ var collectNativeWindowFunc = () => {
73
+ const keyList = Object.getOwnPropertyNames(window);
74
+ for (const key of keyList) {
75
+ if (!windowNativeFuncMap.has(key) && key.match(/^[A-Z]/) && typeof window[key] === "function" && window[key].toString().includes("[native code]")) {
76
+ windowNativeFuncMap.set(key, true);
77
+ }
78
+ }
79
+ };
80
+ collectNativeWindowFunc();
81
+
82
+ // src/typings/source.ts
83
+ var CSS_ATTRIBUTE_KEY = "id";
84
+
85
+ // src/typings/model.ts
86
+ var WewebMode = /* @__PURE__ */ ((WewebMode2) => {
87
+ WewebMode2["APP"] = "app";
88
+ WewebMode2["CONFIG"] = "config";
89
+ WewebMode2["INSTANCE"] = "js";
90
+ return WewebMode2;
91
+ })(WewebMode || {});
92
+
93
+ // src/typings/sandbox.ts
94
+ var WINDOW_WHITE_LIST = [
95
+ "System",
96
+ // SystemJS
97
+ "__cjsWrapper",
98
+ // SystemJS CommonJS wrapper
99
+ false ? "__REACT_DEVTOOLS_GLOBAL_HOOK__" : ""
100
+ ];
101
+ var BK_WEWEB_INJECT_KEY_LIST = [
102
+ "__POWERED_BY_BK_WEWEB__",
103
+ "__BK_WEWEB_APP_KEY__",
104
+ "__BK_WEWEB_DATA__"
105
+ ];
106
+ var WINDOW_ALIAS_LIST = ["window", "self", "globalThis"];
107
+ var BK_WEWEB_LOCATION_KEY_LIST = ["location", "history"];
108
+ var COMMON_MICRO_APP_WINDOE_KEY_MAP = {
109
+ __bk_pop_manager: true,
110
+ __bk_zIndex_manager: true,
111
+ i18n: true
112
+ };
113
+ var DEV_MICRO_APP_WINDOE_KEY_MAP = false ? {
114
+ __DEV__: true,
115
+ __VUE_DEVTOOLS_GLOBAL_HOOK__: true,
116
+ __VUE_DEVTOOLS_HOOK_REPLAY__: true,
117
+ __VUE_DEVTOOLS_PLUGINS__: true,
118
+ __VUE_I18N_FULL_INSTALL__: true,
119
+ __VUE_I18N_LEGACY_API__: true,
120
+ __VUE_OPTIONS_API__: true,
121
+ "__core-js_shared__": true,
122
+ webpackChunkapm: true,
123
+ webpackChunkpc: true,
124
+ webpackChunktrace: true,
125
+ webpackJsonp: true,
126
+ ...COMMON_MICRO_APP_WINDOE_KEY_MAP
127
+ } : COMMON_MICRO_APP_WINDOE_KEY_MAP;
128
+
129
+ // src/utils/common.ts
130
+ var nextTask = (cb) => Promise.resolve().then(cb);
131
+ function addUrlProtocol(url) {
132
+ if (url.startsWith("//")) return `${location.protocol}${url}`;
133
+ if (!url.startsWith("http")) return `${location.protocol}//${url}`;
134
+ return url;
135
+ }
136
+ function fillUpPath(path, baseURI) {
137
+ if (!path || /^((((ht|f)tps?)|file):)?\/\//.test(path) || /^(data|blob):/.test(path)) return path;
138
+ const { origin, pathname } = new URL(addUrlProtocol(baseURI));
139
+ return new URL(path, `${origin}${pathname}`.replace(/\.(\w+)$/, "/")).toString();
140
+ }
141
+ function randomUrl() {
142
+ return `inline-${random(16)}`;
143
+ }
144
+ var requestIdleCallback = window.requestIdleCallback || ((cb) => {
145
+ const start = Date.now();
146
+ return setTimeout(() => {
147
+ cb({
148
+ didTimeout: false,
149
+ timeRemaining() {
150
+ return Math.max(0, 50 - (Date.now() - start));
151
+ }
152
+ });
153
+ }, 1);
154
+ });
155
+ var cancelIdleCallback = window.cancelIdleCallback || ((id) => {
156
+ clearTimeout(id);
157
+ });
158
+ var random = (n, str = "abcdefghijklmnopqrstuvwxyz0123456789") => {
159
+ let result = "";
160
+ for (let i = 0; i < n; i++) {
161
+ result += str[Number.parseInt((Math.random() * str.length).toString(), 10)];
162
+ }
163
+ return result;
164
+ };
165
+ var isJsonpUrl = (url) => {
166
+ if (!url) return false;
167
+ if (url.match(/\.js$/)) return false;
168
+ const { pathname } = new URL(addUrlProtocol(url));
169
+ return !pathname.match(/\.js$/);
170
+ };
171
+
172
+ // src/context/document.ts
173
+ var SPECIAL_ELEMENT_TAG = ["body", "html", "head"];
174
+ var createProxyDocument = (rawDocument, app) => {
175
+ const fakeDocument = {};
176
+ function shadowRootInsertAdjacentHTML(where, domString) {
177
+ const temporaryContainer = document.createElement("div");
178
+ temporaryContainer.innerHTML = domString;
179
+ const elements = Array.from(temporaryContainer.childNodes);
180
+ const shadow = app.container;
181
+ switch (where) {
182
+ case "beforebegin":
183
+ elements.forEach((el) => shadow.host.parentNode?.insertBefore(el, shadow.host));
184
+ break;
185
+ case "afterbegin":
186
+ elements.reverse().forEach((el) => shadow.insertBefore(el, shadow.firstChild));
187
+ break;
188
+ case "beforeend":
189
+ elements.forEach((el) => shadow.appendChild(el));
190
+ break;
191
+ case "afterend":
192
+ elements.forEach((el) => shadow.host.parentNode?.insertBefore(el, shadow.host.nextSibling));
193
+ break;
194
+ }
195
+ }
196
+ const proxyBody = new Proxy(
197
+ {},
198
+ {
199
+ get(_, key) {
200
+ if (app.container instanceof ShadowRoot) {
201
+ if (key === "insertAdjacentHTML") {
202
+ return shadowRootInsertAdjacentHTML.bind(app.container);
203
+ }
204
+ const value2 = app.container[key];
205
+ if (typeof value2 === "function") {
206
+ return value2.bind(app.container);
207
+ }
208
+ if (value2 !== void 0) {
209
+ return value2;
210
+ }
211
+ }
212
+ const value = Reflect.get(rawDocument.body, key);
213
+ return typeof value === "function" ? value.bind(rawDocument.body) : value;
214
+ },
215
+ set(_, key, value) {
216
+ if (app.container instanceof ShadowRoot) {
217
+ app.container[key] = value;
218
+ return true;
219
+ }
220
+ Reflect.set(rawDocument.body, key, value);
221
+ return true;
222
+ }
223
+ }
224
+ );
225
+ function createElement(tagName, options) {
226
+ const element = rawDocument.createElement(tagName, options);
227
+ element.__BK_WEWEB_APP_KEY__ = app.appCacheKey;
228
+ return element;
229
+ }
230
+ function querySelectorNew(selectors) {
231
+ if (selectors === proxyBody) {
232
+ return app.container instanceof ShadowRoot ? app.container : rawDocument.body;
233
+ }
234
+ if (SPECIAL_ELEMENT_TAG.includes(selectors)) {
235
+ if (app?.container instanceof ShadowRoot) {
236
+ return app?.container;
237
+ }
238
+ return rawDocument.querySelector.call(this, selectors);
239
+ }
240
+ try {
241
+ return app?.container?.querySelector(selectors) ?? null;
242
+ } catch {
243
+ return null;
244
+ }
245
+ }
246
+ function querySelectorAllNew(selectors) {
247
+ if (SPECIAL_ELEMENT_TAG.includes(selectors)) {
248
+ if (app?.container instanceof ShadowRoot) {
249
+ return app?.container;
250
+ }
251
+ return rawDocument.querySelector(selectors);
252
+ }
253
+ return app?.container?.querySelectorAll(selectors) ?? [];
254
+ }
255
+ function getElementByIdNew(key) {
256
+ return querySelectorNew.call(rawDocument, `#${key}`);
257
+ }
258
+ function getElementsByClassName(key) {
259
+ return querySelectorAllNew(`.${key}`);
260
+ }
261
+ function getElementsByTagName(key) {
262
+ if (SPECIAL_ELEMENT_TAG.includes(key) || !app?.showSourceCode && key.toLocaleLowerCase() === "script") {
263
+ return rawDocument.getElementsByTagName(key);
264
+ }
265
+ return querySelectorAllNew(key);
266
+ }
267
+ function getElementsByNameNew(key) {
268
+ return querySelectorAllNew(`[name=${key}]`);
269
+ }
270
+ return new Proxy(fakeDocument, {
271
+ get(_, key) {
272
+ if (key === "createElement") {
273
+ return createElement.bind(rawDocument);
274
+ }
275
+ if (key === "querySelector") {
276
+ return querySelectorNew.bind(rawDocument);
277
+ }
278
+ if (key === "querySelectorAll") {
279
+ return querySelectorAllNew.bind(rawDocument);
280
+ }
281
+ if (key === "getElementById") {
282
+ return getElementByIdNew.bind(rawDocument);
283
+ }
284
+ if (key === "getElementsByClassName") {
285
+ return getElementsByClassName.bind(rawDocument);
286
+ }
287
+ if (key === "getElementsByTagName") {
288
+ return getElementsByTagName.bind(rawDocument);
289
+ }
290
+ if (key === "getElementsByName") {
291
+ return getElementsByNameNew.bind(rawDocument);
292
+ }
293
+ if (key === "body") {
294
+ return proxyBody;
295
+ }
296
+ const result = Reflect.get(rawDocument, key);
297
+ if (typeof result === "function") {
298
+ return result.bind(rawDocument);
299
+ }
300
+ return result;
301
+ }
302
+ });
303
+ };
304
+
305
+ // src/context/event.ts
306
+ function rewriteDocumentAndBodyEvent() {
307
+ const { addEventListener, removeEventListener } = window.document;
308
+ const { addEventListener: bodyAddEventListener, removeEventListener: bodyRemoveEventListener } = window.document.body;
309
+ const documentListenerMap = /* @__PURE__ */ new Map();
310
+ document.addEventListener = function(type, listener, options) {
311
+ const app = getCurrentRunningApp();
312
+ if (app?.keepAlive) {
313
+ const listeners = documentListenerMap.get(type) || [];
314
+ documentListenerMap.set(type, [...listeners, listener]);
315
+ }
316
+ addEventListener.call(app?.container instanceof ShadowRoot ? app.container : this, type, listener, options);
317
+ };
318
+ document.body.addEventListener = document.addEventListener;
319
+ document.removeEventListener = function(type, listener, options) {
320
+ const app = getCurrentRunningApp();
321
+ if (app?.keepAlive) {
322
+ const listeners = documentListenerMap.get(type) || [];
323
+ if (listeners.length && listeners.some((l) => l === listener)) {
324
+ listeners.splice(listeners.indexOf(listener), 1);
325
+ }
326
+ }
327
+ removeEventListener.call(app?.container instanceof ShadowRoot ? app.container : this, type, listener, options);
328
+ };
329
+ document.body.removeEventListener = document.removeEventListener;
330
+ function resetDocumentAndBodyEvent() {
331
+ const app = getCurrentRunningApp();
332
+ if (app?.keepAlive && documentListenerMap.values()) {
333
+ Array.from(documentListenerMap.entries()).forEach(([type, listeners]) => {
334
+ listeners?.forEach((listener) => {
335
+ document.removeEventListener.call(document, type, listener);
336
+ });
337
+ });
338
+ }
339
+ document.addEventListener = addEventListener;
340
+ document.body.addEventListener = bodyAddEventListener;
341
+ document.removeEventListener = removeEventListener;
342
+ document.body.removeEventListener = bodyRemoveEventListener;
343
+ documentListenerMap.clear();
344
+ }
345
+ return {
346
+ resetDocumentAndBodyEvent
347
+ };
348
+ }
349
+
350
+ // src/context/function.ts
351
+ var CLASS_REGEX = /^class\b/;
352
+ var COMMON_CONTRUCT_FU_REGEX = /^function\b\s[A-Z].*/;
353
+ var ConstructFunCacheMap = /* @__PURE__ */ new WeakMap();
354
+ function isConstructFun(fn) {
355
+ if (fn.prototype?.constructor === fn && Object.getOwnPropertyNames(fn.prototype).length > 1) {
356
+ return true;
357
+ }
358
+ if (ConstructFunCacheMap.has(fn)) {
359
+ return ConstructFunCacheMap.get(fn);
360
+ }
361
+ const constructable = COMMON_CONTRUCT_FU_REGEX.test(fn.toString()) || CLASS_REGEX.test(fn.toString());
362
+ ConstructFunCacheMap.set(fn, constructable);
363
+ return constructable;
364
+ }
365
+ var functionBoundedValueMap = /* @__PURE__ */ new WeakMap();
366
+ function bindFunctionToRawWindow(rawWindow, value) {
367
+ if (functionBoundedValueMap.has(value)) {
368
+ return functionBoundedValueMap.get(value);
369
+ }
370
+ if (typeof value === "function" && !isConstructFun(value)) {
371
+ const boundValue = Function.prototype.bind.call(value, rawWindow);
372
+ for (const key in value) {
373
+ boundValue[key] = value[key];
374
+ }
375
+ if (value.hasOwnProperty("prototype") && !boundValue.hasOwnProperty("prototype")) {
376
+ Object.defineProperty(boundValue, "prototype", { enumerable: false, value: value.prototype, writable: true });
377
+ }
378
+ if (typeof value.toString === "function") {
379
+ const valueHasInstanceToString = value.hasOwnProperty("toString") && !boundValue.hasOwnProperty("toString");
380
+ const boundValueHasPrototypeToString = boundValue.toString === Function.prototype.toString;
381
+ if (valueHasInstanceToString || boundValueHasPrototypeToString) {
382
+ const originToStringDescriptor = Object.getOwnPropertyDescriptor(
383
+ valueHasInstanceToString ? value : Function.prototype,
384
+ "toString"
385
+ );
386
+ Object.defineProperty(boundValue, "toString", {
387
+ ...originToStringDescriptor,
388
+ ...originToStringDescriptor?.get ? null : { value: () => value.toString() }
389
+ });
390
+ }
391
+ }
392
+ functionBoundedValueMap.set(value, boundValue);
393
+ return boundValue;
394
+ }
395
+ return value;
396
+ }
397
+
398
+ // src/context/window.ts
399
+ function rewriteWindowFunction(fakeWindow) {
400
+ const windowEventLisenerMap = /* @__PURE__ */ new Map();
401
+ const intervalTimerList = [];
402
+ const rawWindow = window;
403
+ const { addEventListener, clearInterval: clearInterval2, removeEventListener, setInterval: setInterval2 } = window;
404
+ fakeWindow.addEventListener = (type, listener, options) => {
405
+ windowEventLisenerMap.set(type, [...windowEventLisenerMap.get(type) || [], listener]);
406
+ addEventListener.call(rawWindow, type, listener, options);
407
+ };
408
+ fakeWindow.removeEventListener = (type, listener, options) => {
409
+ const listenerList = windowEventLisenerMap.get(type);
410
+ if (listenerList?.length) {
411
+ const index = listenerList.indexOf(listener);
412
+ index > -1 && listenerList.splice(index, 1);
413
+ }
414
+ removeEventListener.call(rawWindow, type, listener, options);
415
+ };
416
+ fakeWindow.setInterval = (handler, timeout, ...args) => {
417
+ const timer = setInterval2.call(rawWindow, handler, timeout, ...args);
418
+ intervalTimerList.push(timer);
419
+ return timer;
420
+ };
421
+ fakeWindow.clearInterval = (timer) => {
422
+ const index = intervalTimerList.indexOf(timer);
423
+ index > -1 && intervalTimerList.splice(index, 1);
424
+ clearInterval2.call(rawWindow, timer);
425
+ };
426
+ function resetWindowFunction() {
427
+ if (windowEventLisenerMap.size) {
428
+ windowEventLisenerMap.forEach((listenerList, type) => {
429
+ listenerList.forEach((listener) => removeEventListener.call(rawWindow, type, listener));
430
+ });
431
+ windowEventLisenerMap.clear();
432
+ }
433
+ if (intervalTimerList.length) {
434
+ intervalTimerList.forEach((timer) => {
435
+ clearInterval2.call(rawWindow, timer);
436
+ });
437
+ }
438
+ }
439
+ return {
440
+ resetWindowFunction
441
+ };
442
+ }
443
+
444
+ // src/context/sandbox.ts
445
+ var SandBox = class {
446
+ constructor(app) {
447
+ this.app = app;
448
+ const windowDescriptorSet = /* @__PURE__ */ new Set();
449
+ const rawWindow = window;
450
+ this.rawWindow = rawWindow;
451
+ this.rawDocument = createProxyDocument(document, app);
452
+ const fakeWindow = /* @__PURE__ */ Object.create({});
453
+ fakeWindow.__BK_WEWEB_APP_KEY__ = app.appCacheKey;
454
+ fakeWindow.__POWERED_BY_BK_WEWEB__ = true;
455
+ fakeWindow.rawDocument = document;
456
+ fakeWindow.rawWindow = rawWindow;
457
+ fakeWindow.__proto__ = Window;
458
+ this.fakeWindow = fakeWindow;
459
+ const { resetWindowFunction } = rewriteWindowFunction(this.fakeWindow);
460
+ this.resetWindowFunction = resetWindowFunction;
461
+ this.windowSymbolKey = `__${(app.name || app.appCacheKey).replace(/(-|,|:|~|'|")/gim, "_")}_${random(
462
+ 10
463
+ )}__`;
464
+ this.proxyWindow = new Proxy(this.fakeWindow, {
465
+ // Object.defineProperty(window, key, Descriptor)
466
+ defineProperty: (target, key, value) => {
467
+ if (windowDescriptorSet.has(key)) {
468
+ return Reflect.defineProperty(rawWindow, key, value);
469
+ }
470
+ return Reflect.defineProperty(target, key, value);
471
+ },
472
+ deleteProperty: (target, key) => {
473
+ if (Object.hasOwn(target, key)) {
474
+ this.sameRawWindowKeySet.has(key) && this.sameRawWindowKeySet.delete(key);
475
+ this.inRawWindowKeySet.has(key) && Reflect.deleteProperty(rawWindow, key);
476
+ return Reflect.deleteProperty(target, key);
477
+ }
478
+ return true;
479
+ },
480
+ get: (target, key) => {
481
+ if (key === Symbol.unscopables || windowNativeFuncMap.has(key)) return rawWindow[key];
482
+ if (DEV_MICRO_APP_WINDOE_KEY_MAP[key]) return this.fakeWindow[key];
483
+ if (WINDOW_ALIAS_LIST.includes(key)) return this.proxyWindow;
484
+ if (key === "document") {
485
+ app.registerRunningApp();
486
+ return this.rawDocument;
487
+ }
488
+ if (key === "eval") {
489
+ app.registerRunningApp();
490
+ return eval;
491
+ }
492
+ if (BK_WEWEB_LOCATION_KEY_LIST.includes(key) && this.app instanceof MicroAppModel && this.app.iframe && this.app.scopeLocation) {
493
+ return this.app.iframe.contentWindow?.[key];
494
+ }
495
+ if (key === "hasOwnProperty")
496
+ return (key2) => Object.hasOwn(this.fakeWindow, key2) || Object.hasOwn(rawWindow, key2);
497
+ if (key === "top" || key === "parent") {
498
+ if (rawWindow === rawWindow.parent) {
499
+ return this.proxyWindow;
500
+ }
501
+ return Reflect.get(rawWindow, key);
502
+ }
503
+ if (key === "getComputedStyle") {
504
+ return (element, pseudoElt) => {
505
+ if (element instanceof Element) {
506
+ return rawWindow.getComputedStyle(element, pseudoElt);
507
+ }
508
+ return rawWindow.getComputedStyle(document.body, pseudoElt);
509
+ };
510
+ }
511
+ if (Reflect.has(target, key) || BK_WEWEB_INJECT_KEY_LIST.includes(key)) return Reflect.get(target, key);
512
+ const rawValue = Reflect.get(rawWindow, key);
513
+ return bindFunctionToRawWindow(rawWindow, rawValue);
514
+ },
515
+ getOwnPropertyDescriptor: (target, key) => {
516
+ if (Object.hasOwn(target, key)) {
517
+ return Object.getOwnPropertyDescriptor(target, key);
518
+ }
519
+ if (Object.hasOwn(rawWindow, key)) {
520
+ windowDescriptorSet.add(key);
521
+ const descriptor = Object.getOwnPropertyDescriptor(rawWindow, key);
522
+ if (descriptor && !descriptor.configurable) {
523
+ descriptor.configurable = true;
524
+ }
525
+ return descriptor;
526
+ }
527
+ return void 0;
528
+ },
529
+ has: (target, key) => windowNativeFuncMap.has(key) || key in target || key in rawWindow,
530
+ // Object.getOwnPropertyNames(window)
531
+ ownKeys: (target) => Array.from(new Set(Reflect.ownKeys(rawWindow).concat(Reflect.ownKeys(target)))),
532
+ set: (target, key, value) => {
533
+ if (this.active) {
534
+ if (BK_WEWEB_LOCATION_KEY_LIST.includes(key) && this.app instanceof MicroAppModel && this.app.iframe && this.app.scopeLocation) {
535
+ return Reflect.set(this.app.iframe.contentWindow, key, value);
536
+ }
537
+ if (key === "location") {
538
+ Reflect.set(rawWindow, key, value);
539
+ } else if (!Object.hasOwn(target, key) && Object.hasOwn(rawWindow, key) && !BK_WEWEB_INJECT_KEY_LIST.includes(key)) {
540
+ const descriptor = Object.getOwnPropertyDescriptor(rawWindow, key);
541
+ const { configurable, enumerable, writable } = descriptor;
542
+ if (writable) {
543
+ Object.defineProperty(target, key, {
544
+ configurable,
545
+ enumerable,
546
+ value,
547
+ writable
548
+ });
549
+ this.sameRawWindowKeySet.add(key);
550
+ }
551
+ } else {
552
+ Reflect.set(target, key, value);
553
+ this.sameRawWindowKeySet.add(key);
554
+ }
555
+ if (WINDOW_WHITE_LIST.includes(key) && !Reflect.has(rawWindow, key) && !BK_WEWEB_INJECT_KEY_LIST.includes(key)) {
556
+ Reflect.set(rawWindow, key, value);
557
+ this.inRawWindowKeySet.add(key);
558
+ }
559
+ }
560
+ return true;
561
+ }
562
+ });
563
+ rawWindow[this.windowSymbolKey] = this.proxyWindow;
564
+ }
565
+ active = false;
566
+ inRawWindowKeySet = /* @__PURE__ */ new Set();
567
+ resetDocumentAndBodyEvent;
568
+ resetWindowFunction;
569
+ sameRawWindowKeySet = /* @__PURE__ */ new Set();
570
+ fakeWindow;
571
+ proxyDocument;
572
+ proxyWindow;
573
+ rawDocument;
574
+ rawWindow;
575
+ windowSymbolKey;
576
+ /**
577
+ *
578
+ * @param data data for sandbox
579
+ * @description active hook for sandbox
580
+ */
581
+ activated(data) {
582
+ if (!this.active) {
583
+ this.active = true;
584
+ this.rawDocument = createProxyDocument(document, this.app);
585
+ this.fakeWindow.__BK_WEWEB_DATA__ = data ?? {};
586
+ const { resetDocumentAndBodyEvent } = rewriteDocumentAndBodyEvent();
587
+ this.resetDocumentAndBodyEvent = resetDocumentAndBodyEvent;
588
+ }
589
+ }
590
+ /**
591
+ *
592
+ * @description decativated hook for sandbox
593
+ */
594
+ deactivated() {
595
+ if (!this.active) return;
596
+ this.active = false;
597
+ this.resetWindowFunction();
598
+ for (const key of this.inRawWindowKeySet) {
599
+ Reflect.deleteProperty(window, key);
600
+ }
601
+ this.inRawWindowKeySet.clear();
602
+ this.resetDocumentAndBodyEvent?.();
603
+ }
604
+ };
605
+
606
+ // src/utils/custom.ts
607
+ var ELEMENT_TARGET_NAME = ["currentTarget", "srcElement", "target"];
608
+ function defineEventSourceElement(element, eventName = "custom") {
609
+ return Object.defineProperties(
610
+ new CustomEvent(eventName),
611
+ ELEMENT_TARGET_NAME.reduce((props, name) => {
612
+ props[name] = {
613
+ get() {
614
+ return element;
615
+ }
616
+ };
617
+ return props;
618
+ }, {})
619
+ );
620
+ }
621
+ function dispatchLinkOrScriptLoad(element) {
622
+ const event = defineEventSourceElement(element, "load");
623
+ if (typeof element.onload === "function") {
624
+ element.onload(event);
625
+ return;
626
+ }
627
+ element.dispatchEvent(event);
628
+ }
629
+ function dispatchLinkOrScriptError(element) {
630
+ const event = defineEventSourceElement(element, "error");
631
+ if (typeof element.onerror === "function") {
632
+ element.onerror(event);
633
+ return;
634
+ }
635
+ element.dispatchEvent(event);
636
+ }
637
+
638
+ // src/utils/element.ts
639
+ var { appendChild: bodyAppendChild } = HTMLBodyElement.prototype;
640
+ function resetNewElement(parent, child, app) {
641
+ if (child instanceof HTMLStyleElement) {
642
+ if (child.hasAttribute("exclude")) {
643
+ return document.createComment("\u3010bk-weweb\u3011style with exclude attribute is ignored");
644
+ }
645
+ if (child.textContent) {
646
+ if (!(app.container instanceof ShadowRoot) && appCache.getBaseAppStyle(child.textContent)) {
647
+ return document.createComment("\u3010bk-weweb\u3011style is effective in base app");
648
+ }
649
+ }
650
+ if (!child.hasAttribute("ignore")) {
651
+ const styleInstance = new Style({
652
+ code: child.textContent || "",
653
+ fromHtml: false,
654
+ url: ""
655
+ });
656
+ app.source?.setStyle(randomUrl(), styleInstance);
657
+ styleInstance.scopedStyleCSS(app, child);
658
+ }
659
+ return child;
660
+ }
661
+ if (child instanceof HTMLLinkElement) {
662
+ const result = app.source?.collectLink(child, parent, true);
663
+ if (!result) return child;
664
+ if (result.style) {
665
+ result.style.scopedLinkCSS(app, child);
666
+ }
667
+ if (result.replace !== child) {
668
+ return result.replace;
669
+ }
670
+ return child;
671
+ }
672
+ if (child instanceof HTMLScriptElement) {
673
+ const replaceInfo = app.source.collectScript(child, parent, true);
674
+ if (!replaceInfo) {
675
+ return child;
676
+ }
677
+ if (replaceInfo.script) {
678
+ replaceInfo.script.executeCode(app);
679
+ }
680
+ if (replaceInfo.replace !== child) {
681
+ return replaceInfo.replace;
682
+ }
683
+ if (app.scopeJs && !child.getAttribute("src") && !child.textContent) {
684
+ const observer = new MutationObserver(() => {
685
+ if (child.getAttribute("src")) {
686
+ observer.disconnect();
687
+ const scriptInfo = app.source.collectScript(child, parent, true);
688
+ if (scriptInfo?.replace) {
689
+ bodyAppendChild.call(app.container, scriptInfo.replace);
690
+ }
691
+ if (isJsonpUrl(child.getAttribute("src"))) {
692
+ app.container?.append(child);
693
+ return;
694
+ }
695
+ if (scriptInfo?.script) {
696
+ scriptInfo.script.executeCode(app);
697
+ }
698
+ child.remove();
699
+ } else if (child.textContent) {
700
+ observer.disconnect();
701
+ const scriptInstance = new Script({
702
+ async: false,
703
+ code: child.textContent,
704
+ defer: child.type === "module",
705
+ fromHtml: false,
706
+ isModule: child.type === "module"
707
+ });
708
+ app.source.scripts.set(randomUrl(), scriptInstance);
709
+ try {
710
+ scriptInstance.executeCode(app);
711
+ } catch (e) {
712
+ console.error(e);
713
+ } finally {
714
+ !scriptInstance.isModule && dispatchLinkOrScriptLoad(child);
715
+ child.remove();
716
+ }
717
+ }
718
+ });
719
+ observer.observe(child, { attributeFilter: ["src"], childList: true, subtree: false });
720
+ return document.createComment("\u3010bk-weweb\u3011dynamic script or module");
721
+ }
722
+ return child;
723
+ }
724
+ return child;
725
+ }
726
+ function isSpecialElement(node) {
727
+ return node instanceof HTMLScriptElement || node instanceof HTMLStyleElement || node instanceof HTMLLinkElement;
728
+ }
729
+ function elementAppendHandler(parent, newChild, rawMethod) {
730
+ if (newChild.__BK_WEWEB_APP_KEY__) {
731
+ const app = appCache.getApp(newChild.__BK_WEWEB_APP_KEY__);
732
+ if (app?.container) {
733
+ const targetChild = resetNewElement(parent, newChild, app);
734
+ const needKeepAlive = isSpecialElement(newChild) && !!app.keepAlive && !(app.container instanceof ShadowRoot);
735
+ const container = needKeepAlive ? document.head : app?.container;
736
+ setMarkElement(targetChild, app, needKeepAlive);
737
+ return rawMethod.call(container, targetChild);
738
+ }
739
+ }
740
+ return rawMethod.call(parent, newChild);
741
+ }
742
+ function elementInsertHandler(parent, newChild, passiveChild, rawMethod) {
743
+ if (newChild.__BK_WEWEB_APP_KEY__) {
744
+ const app = appCache.getApp(newChild.__BK_WEWEB_APP_KEY__);
745
+ if (app?.container) {
746
+ const needKeepAlive = isSpecialElement(newChild) && app.keepAlive && !(app.container instanceof ShadowRoot);
747
+ const container = needKeepAlive ? document.head : app?.container;
748
+ const targetChild = resetNewElement(parent, newChild, app);
749
+ if (needKeepAlive) {
750
+ setMarkElement(targetChild, app, needKeepAlive);
751
+ }
752
+ if (passiveChild && !container.contains(passiveChild)) {
753
+ return bodyAppendChild.call(container, targetChild);
754
+ }
755
+ return rawMethod.call(container, targetChild, passiveChild);
756
+ }
757
+ }
758
+ return rawMethod.call(parent, newChild, passiveChild);
759
+ }
760
+ function setMarkElement(element, app, keepAlive) {
761
+ if (keepAlive && app) {
762
+ element.__KEEP_ALIVE__ = app.appCacheKey;
763
+ element.setAttribute("data-from", app.name);
764
+ element.setAttribute("data-keep-alive", "true");
765
+ }
766
+ element.setAttribute?.("powered-by", "bk-weweb");
767
+ return element;
768
+ }
769
+
770
+ // src/utils/fetch.ts
771
+ function fetchSource(url, options = {}, app) {
772
+ if (typeof app?.fetchSource === "function") {
773
+ return app.fetchSource(url, options).catch(() => "");
774
+ }
775
+ if (src_default.fetchSource) {
776
+ return src_default.fetchSource(url, options);
777
+ }
778
+ return window.fetch(url, options).then((res) => res.text());
779
+ }
780
+
781
+ // src/entry/style.ts
782
+ var Style = class {
783
+ code = "";
784
+ fromHtml;
785
+ initial;
786
+ prefetch = false;
787
+ preload = false;
788
+ scoped;
789
+ scopedCode = "";
790
+ url;
791
+ constructor({ code, fromHtml, initial, prefetch, preload, url }) {
792
+ this.scoped = false;
793
+ this.code = code;
794
+ this.prefetch = prefetch ?? false;
795
+ this.preload = preload ?? false;
796
+ this.url = url;
797
+ this.fromHtml = fromHtml;
798
+ this.initial = initial ?? false;
799
+ }
800
+ /**
801
+ * @param styleElement 样式node
802
+ * @param app 应用实例
803
+ */
804
+ commonScoped(styleElement, app) {
805
+ if (app.scopeCss && !(app.container instanceof ShadowRoot)) {
806
+ const cssStyleSheet = new CSSStyleSheet({ disabled: true });
807
+ cssStyleSheet.replaceSync(styleElement.textContent || this.code);
808
+ const rules = Array.from(cssStyleSheet?.cssRules ?? []);
809
+ const cssPrefix = `#${app.name}`;
810
+ const scopedCss = this.scopeRule(rules, cssPrefix);
811
+ const cssText = this.resetUrlHost(scopedCss, app.url, this.url);
812
+ styleElement.textContent = cssText;
813
+ this.scopedCode = cssText;
814
+ } else {
815
+ const cssText = this.resetUrlHost(styleElement.textContent || this.code || "", app.url, this.url);
816
+ if (cssText && app.container instanceof ShadowRoot) {
817
+ let fontContent = "";
818
+ for (const fontFace of cssText.match(/@font-face\s*\{[^}]+\}/g) || []) {
819
+ fontContent += `${fontFace}
820
+ `;
821
+ }
822
+ const rawDocument = app.sandBox?.rawDocument;
823
+ if (rawDocument && fontContent) {
824
+ const fontStyle = rawDocument.createElement("style");
825
+ fontStyle.setAttribute("type", "text/css");
826
+ fontStyle.setAttribute("powered-by", "bk-weweb");
827
+ fontStyle.textContent = fontContent;
828
+ rawDocument?.head?.append(fontStyle);
829
+ }
830
+ }
831
+ styleElement.textContent = cssText.replace(/^\:root$/gm, ":host");
832
+ }
833
+ this.scoped = true;
834
+ }
835
+ createStyleElement() {
836
+ const styleElement = document.createElement("style");
837
+ if (styleElement.__BK_WEWEB_APP_KEY__) {
838
+ styleElement.__BK_WEWEB_APP_KEY__ = void 0;
839
+ }
840
+ return styleElement;
841
+ }
842
+ /**
843
+ * @param app 应用实例
844
+ * @returns 返回执行后的style标签
845
+ */
846
+ async executeCode(app) {
847
+ app.registerRunningApp();
848
+ let styleElement = this.createStyleElement();
849
+ styleElement.setAttribute("type", "text/css");
850
+ styleElement.textContent = this.code;
851
+ try {
852
+ if (!this.code) await this.getCode(app);
853
+ styleElement = this.scopedStyleCSS(app, styleElement);
854
+ this.scoped = true;
855
+ } catch (e) {
856
+ console.error("scoped style error", e);
857
+ }
858
+ return styleElement;
859
+ }
860
+ async getCode(app) {
861
+ if (this.code.length || !this.url) {
862
+ return this.code;
863
+ }
864
+ let code = "";
865
+ if (app?.source?.styles?.has(this.url)) {
866
+ code = app.source.styles.get(this.url)?.code || "";
867
+ }
868
+ if (!code && appCache.getCacheStyle(this.url)) {
869
+ const style = appCache.getCacheStyle(this.url);
870
+ code = style?.code || "";
871
+ }
872
+ if (!code) {
873
+ code = await fetchSource(this.url, {}, app).catch(() => "");
874
+ }
875
+ this.code = code;
876
+ return code;
877
+ }
878
+ // 主应用已生效的样式 不再应用在子应用
879
+ linkedBaseStyle(styleElement, app) {
880
+ if (!(app.container instanceof ShadowRoot) && styleElement.textContent && appCache.getBaseAppStyle(styleElement.textContent)) {
881
+ styleElement.textContent = "";
882
+ styleElement.innerHTML = "";
883
+ styleElement.setAttribute("linked-from-base", "true");
884
+ return true;
885
+ }
886
+ return false;
887
+ }
888
+ resetPackRule(rule, prefix, packName) {
889
+ const result = this.scopeRule(Array.from(rule.cssRules), prefix);
890
+ return `@${packName} ${rule.conditionText} {${result}}`;
891
+ }
892
+ resetUrlHost(cssText, uri, linkPath) {
893
+ let baseURI = uri;
894
+ return cssText.replace(/url\(["']?([^)"']+)["']?\)/gm, (text, $1) => {
895
+ if (/^(data|blob):/.test($1) || /^(https?:)?\/\//.test($1)) {
896
+ return text;
897
+ }
898
+ if (/^((\.\.?\/)|[^/])/.test($1) && linkPath) {
899
+ const pathArr = linkPath.split("/");
900
+ pathArr.pop();
901
+ baseURI = addUrlProtocol(`${pathArr.join("/")}/`);
902
+ }
903
+ return `url("${fillUpPath($1, baseURI)}")`;
904
+ });
905
+ }
906
+ scopeRule(rules, cssPrefix) {
907
+ let result = "";
908
+ for (const rule of rules) {
909
+ switch (rule.type) {
910
+ case 1 /* STYLE_RULE */:
911
+ result += this.scopeStyleRule(rule, cssPrefix);
912
+ break;
913
+ case 4 /* MEDIA_RULE */:
914
+ result += this.resetPackRule(rule, cssPrefix, "media");
915
+ break;
916
+ case 12 /* SUPPORTS_RULE */:
917
+ result += this.resetPackRule(rule, cssPrefix, "supports");
918
+ break;
919
+ default:
920
+ result += rule.cssText;
921
+ break;
922
+ }
923
+ }
924
+ return result.replace(/^\s+/, "");
925
+ }
926
+ scopeStyleRule(rule, prefix) {
927
+ const { cssText, selectorText } = rule;
928
+ if (/^((html[\s>~,]+body)|(html|body|:root))$/.test(selectorText)) {
929
+ return cssText.replace(/^((html[\s>~,]+body)|(html|body|:root))/, prefix);
930
+ }
931
+ if (selectorText === "*") {
932
+ return cssText.replace("*", `${prefix} *`);
933
+ }
934
+ const builtInRootSelectorRE = /(^|\s+)((html[\s>~]+body)|(html|body|:root))(?=[\s>~]+|$)/;
935
+ return cssText.replace(
936
+ /^[\s\S]+{/,
937
+ (selectors) => selectors.replace(/(^|,)([^,]+)/g, (all, $1, $2) => {
938
+ if (builtInRootSelectorRE.test($2)) {
939
+ return all.replace(builtInRootSelectorRE, prefix);
940
+ }
941
+ return `${$1} ${prefix} ${$2.replace(/^\s*/, "")}`;
942
+ })
943
+ );
944
+ }
945
+ scopedLinkCSS(app, linkElement) {
946
+ const styleElement = this.createStyleElement();
947
+ styleElement.setAttribute("type", "text/css");
948
+ const needKeepAlive = !!app.keepAlive && !(app.container instanceof ShadowRoot);
949
+ setMarkElement(styleElement, app, needKeepAlive);
950
+ const container = needKeepAlive ? document.head : app.container;
951
+ try {
952
+ if (this.code) {
953
+ this.commonScoped(styleElement, app);
954
+ container?.prepend(styleElement);
955
+ linkElement && dispatchLinkOrScriptLoad(linkElement);
956
+ } else if (linkElement.getAttribute("href")) {
957
+ this.url = fillUpPath(linkElement.getAttribute("href"), app.url);
958
+ this.getCode(app).then(() => {
959
+ this.scopedStyleCSS(app, styleElement);
960
+ linkElement.remove();
961
+ container?.prepend(styleElement);
962
+ linkElement && dispatchLinkOrScriptLoad(linkElement);
963
+ this.scoped = true;
964
+ });
965
+ } else {
966
+ const observer = new MutationObserver(() => {
967
+ if (!linkElement.href) return;
968
+ observer.disconnect();
969
+ this.url = fillUpPath(linkElement.getAttribute("href"), app.url);
970
+ this.getCode(app).then(() => {
971
+ this.scopedStyleCSS(app, styleElement);
972
+ linkElement.remove();
973
+ container?.prepend(styleElement);
974
+ linkElement && dispatchLinkOrScriptLoad(linkElement);
975
+ this.scoped = true;
976
+ });
977
+ });
978
+ observer.observe(linkElement, { attributeFilter: ["href"], childList: false, subtree: false });
979
+ }
980
+ } catch {
981
+ linkElement && dispatchLinkOrScriptError(linkElement);
982
+ }
983
+ return styleElement;
984
+ }
985
+ scopedStyleCSS(app, styleElement) {
986
+ const needKeepAlive = !!app.keepAlive && !(app.container instanceof ShadowRoot);
987
+ setMarkElement(styleElement, app, needKeepAlive);
988
+ if (this.code || styleElement.textContent) {
989
+ if (styleElement.textContent) {
990
+ styleElement.textContent = "";
991
+ styleElement.innerHTML = "";
992
+ }
993
+ if (this.linkedBaseStyle(styleElement, app)) return styleElement;
994
+ this.commonScoped(styleElement, app);
995
+ } else {
996
+ const observer = new MutationObserver(() => {
997
+ if (!(styleElement.textContent || styleElement.sheet?.cssRules?.length)) return;
998
+ observer.disconnect();
999
+ if (!this.linkedBaseStyle(styleElement, app)) {
1000
+ this.commonScoped(styleElement, app);
1001
+ }
1002
+ });
1003
+ observer.observe(styleElement, { attributes: false, characterData: true, childList: true, subtree: true });
1004
+ }
1005
+ this.url && styleElement.setAttribute("origin-src", this.url);
1006
+ return styleElement;
1007
+ }
1008
+ };
1009
+ async function executeAppStyles(app, container) {
1010
+ const styleList = Array.from(app.source.styles.values());
1011
+ const promiseList = [];
1012
+ for (const style of styleList) {
1013
+ promiseList.push(style.executeCode(app));
1014
+ }
1015
+ await Promise.all(promiseList).then((styleElementList) => {
1016
+ const parentElement = container || app.container;
1017
+ if (app.keepAlive && !(parentElement instanceof ShadowRoot)) {
1018
+ document.head.append(...styleElementList);
1019
+ } else {
1020
+ parentElement?.append(...styleElementList);
1021
+ }
1022
+ });
1023
+ }
1024
+
1025
+ // src/mode/instance.ts
1026
+ var MicroInstanceModel = class {
1027
+ state = "UNSET" /* UNSET */;
1028
+ // 当前实例状态
1029
+ appCacheKey;
1030
+ // 缓存key
1031
+ container;
1032
+ // 容器
1033
+ data;
1034
+ // 数据
1035
+ initSource;
1036
+ // 初始资源
1037
+ isPreLoad = false;
1038
+ // 是否预加载
1039
+ keepAlive;
1040
+ // 是否缓存
1041
+ name;
1042
+ // 名称
1043
+ sandBox;
1044
+ // 沙箱
1045
+ scopeCss = true;
1046
+ // 是否隔离样式
1047
+ scopeJs = false;
1048
+ // 是否隔离js
1049
+ showSourceCode = true;
1050
+ // 是否显示源码
1051
+ source;
1052
+ // 入口资源
1053
+ url;
1054
+ // url
1055
+ fetchSource;
1056
+ constructor(props) {
1057
+ this.name = props.id !== props.url ? props.id : random(5);
1058
+ this.appCacheKey = props.id || this.name;
1059
+ this.url = props.url;
1060
+ this.container = props.container ?? void 0;
1061
+ this.scopeJs = props.scopeJs ?? true;
1062
+ this.showSourceCode = props.showSourceCode ?? true;
1063
+ this.scopeCss = props.scopeCss ?? true;
1064
+ this.keepAlive = props.keepAlive ?? false;
1065
+ this.data = props.data ?? {};
1066
+ this.initSource = props.initSource ?? [];
1067
+ if (this.scopeJs) {
1068
+ this.sandBox = new SandBox(this);
1069
+ }
1070
+ this.fetchSource = props.fetchSource;
1071
+ }
1072
+ activated(container, callback) {
1073
+ this.isPreLoad = false;
1074
+ this.state = "ACTIVATED" /* ACTIVATED */;
1075
+ if (this.container && container) {
1076
+ if (container instanceof Element) container?.setAttribute(CSS_ATTRIBUTE_KEY, this.name);
1077
+ const fragment = document.createDocumentFragment();
1078
+ for (const node of Array.from(this.container.childNodes)) {
1079
+ fragment.appendChild(node);
1080
+ }
1081
+ container.appendChild(fragment);
1082
+ this.container = container;
1083
+ this.sandBox?.activated();
1084
+ const scriptInfo = this.source?.getScript(this.url);
1085
+ callback?.(this, scriptInfo?.exportInstance);
1086
+ }
1087
+ }
1088
+ deactivated() {
1089
+ this.state = "DEACTIVATED" /* DEACTIVATED */;
1090
+ this.sandBox?.deactivated();
1091
+ }
1092
+ mount(container, callback) {
1093
+ this.isPreLoad = false;
1094
+ this.container = container ?? this.container;
1095
+ this.state = "MOUNTING" /* MOUNTING */;
1096
+ if (this.container instanceof HTMLElement) {
1097
+ this.container?.setAttribute(CSS_ATTRIBUTE_KEY, this.name);
1098
+ }
1099
+ this.container.innerHTML = "";
1100
+ const instanceWrap = document.createElement("div");
1101
+ const wrapId = `${this.name}-wrapper`;
1102
+ instanceWrap.setAttribute("id", wrapId);
1103
+ if (this.source?.styles.size) {
1104
+ executeAppStyles(this, this.container);
1105
+ }
1106
+ this.container.appendChild(instanceWrap);
1107
+ this.sandBox?.activated();
1108
+ execAppScripts(this).finally(() => {
1109
+ this.state = "MOUNTED" /* MOUNTED */;
1110
+ const scriptInfo = this.source?.getScript(this.url);
1111
+ if (typeof scriptInfo?.exportInstance?.render === "function") {
1112
+ scriptInfo.exportInstance.render(instanceWrap, this.data);
1113
+ }
1114
+ callback?.(this, scriptInfo?.exportInstance);
1115
+ });
1116
+ }
1117
+ onError() {
1118
+ this.state = "ERROR" /* ERROR */;
1119
+ }
1120
+ onMount() {
1121
+ if (this.isPreLoad) return;
1122
+ this.state = "LOADED" /* LOADED */;
1123
+ this.mount();
1124
+ }
1125
+ registerRunningApp() {
1126
+ setCurrentRunningApp(this);
1127
+ Promise.resolve().then(() => setCurrentRunningApp(null));
1128
+ }
1129
+ async start() {
1130
+ if (!this.source || ["ERROR" /* ERROR */, "UNSET" /* UNSET */].includes(this.status)) {
1131
+ this.source = new EntrySource(this.url);
1132
+ await this.source.importEntry(this);
1133
+ }
1134
+ }
1135
+ unmount(needDestroy) {
1136
+ this.state = "UNMOUNT" /* UNMOUNT */;
1137
+ this.sandBox?.deactivated();
1138
+ needDestroy && appCache.deleteApp(this.url);
1139
+ this.container.innerHTML = "";
1140
+ this.container = void 0;
1141
+ }
1142
+ set status(v) {
1143
+ this.state = v;
1144
+ }
1145
+ get status() {
1146
+ return this.state;
1147
+ }
1148
+ };
1149
+
1150
+ // src/entry/script.ts
1151
+ var firstGlobalProp;
1152
+ var secondGlobalProp;
1153
+ var lastGlobalProp;
1154
+ var Script = class {
1155
+ async = false;
1156
+ code = "";
1157
+ defer = false;
1158
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1159
+ exportInstance;
1160
+ fromHtml;
1161
+ initial;
1162
+ isModule = false;
1163
+ scoped;
1164
+ url;
1165
+ constructor({ async, code, defer, fromHtml, initial, isModule, url }) {
1166
+ this.code = code;
1167
+ this.async = async;
1168
+ this.defer = defer;
1169
+ this.isModule = isModule;
1170
+ this.url = url;
1171
+ this.scoped = false;
1172
+ this.fromHtml = fromHtml ?? false;
1173
+ this.initial = initial ?? false;
1174
+ }
1175
+ /**
1176
+ * @param app 应用
1177
+ * @param needReplaceScriptElement 是否需要替换script标签
1178
+ * @returns 返回执行后的script标签或注释
1179
+ */
1180
+ async executeCode(app, needReplaceScriptElement = false) {
1181
+ try {
1182
+ if (!this.code) await this.getCode(app);
1183
+ if (app instanceof MicroInstanceModel) {
1184
+ const globalWindow = app.scopeJs ? app.sandBox?.proxyWindow || window : window;
1185
+ noteGlobalProps(globalWindow);
1186
+ }
1187
+ let scopedCode = this.code;
1188
+ scopedCode = this.transformCode(app);
1189
+ if (app.showSourceCode || this.isModule) {
1190
+ const scriptElement = document.createElement("script");
1191
+ if (scriptElement.__BK_WEWEB_APP_KEY__) {
1192
+ scriptElement.__BK_WEWEB_APP_KEY__ = void 0;
1193
+ }
1194
+ app.registerRunningApp();
1195
+ this.executeSourceScript(scriptElement, scopedCode);
1196
+ if (needReplaceScriptElement) return scriptElement;
1197
+ const needKeepAlive = !!app.keepAlive && !(app.container instanceof ShadowRoot);
1198
+ const container = needKeepAlive ? document.head : app.container;
1199
+ setMarkElement(scriptElement, app, needKeepAlive);
1200
+ container.appendChild(scriptElement);
1201
+ } else {
1202
+ this.executeMemoryScript(app, scopedCode);
1203
+ if (needReplaceScriptElement) return document.createComment("\u3010bk-weweb\u3011dynamic script");
1204
+ }
1205
+ if (app instanceof MicroInstanceModel) {
1206
+ const globalWindow = app.scopeJs ? app.sandBox?.proxyWindow || window : window;
1207
+ const exportProp = getGlobalProp(globalWindow);
1208
+ if (exportProp) {
1209
+ this.exportInstance = globalWindow[exportProp];
1210
+ if (!app.scopeJs) {
1211
+ delete globalWindow[exportProp];
1212
+ }
1213
+ }
1214
+ }
1215
+ } catch (e) {
1216
+ console.error("execute script code error", e);
1217
+ }
1218
+ return;
1219
+ }
1220
+ // 内存脚本执行
1221
+ executeMemoryScript(app, scopedCode) {
1222
+ try {
1223
+ const isScopedLocation = app instanceof MicroAppModel && app.scopeLocation;
1224
+ app.registerRunningApp();
1225
+ new Function("window", "location", "history", scopedCode)(
1226
+ app.sandBox.proxyWindow,
1227
+ isScopedLocation ? app.iframe.contentWindow.location : window.location,
1228
+ isScopedLocation ? app.iframe.contentWindow.history : window.history
1229
+ );
1230
+ } catch (e) {
1231
+ console.error(e);
1232
+ }
1233
+ }
1234
+ // 脚本标签执行
1235
+ executeSourceScript(scriptElement, scopedCode) {
1236
+ if (this.isModule) {
1237
+ scriptElement.src = `${this.url}?key=${Date.now()}`;
1238
+ scriptElement.setAttribute("type", "module");
1239
+ } else {
1240
+ scriptElement.textContent = scopedCode;
1241
+ }
1242
+ this.url && scriptElement.setAttribute("origin-src", this.url);
1243
+ }
1244
+ // 获取脚本内容
1245
+ async getCode(app) {
1246
+ if (this.code.length || !this.url) {
1247
+ return this.code;
1248
+ }
1249
+ let code = "";
1250
+ if (app?.source?.getScript(this.url)) {
1251
+ code = app.source.getScript(this.url)?.code || "";
1252
+ }
1253
+ if (!code && appCache.getCacheScript(this.url)) {
1254
+ code = appCache.getCacheScript(this.url)?.code || "";
1255
+ }
1256
+ if (!code) {
1257
+ code = await fetchSource(this.url, {}, app).catch((e) => {
1258
+ console.error(`fetch script ${this.url} error`, e);
1259
+ return "";
1260
+ });
1261
+ }
1262
+ code = code.replace(/^"use\sstrict";$/gim, "");
1263
+ this.code = code;
1264
+ return code;
1265
+ }
1266
+ setCode(code) {
1267
+ this.code = code;
1268
+ }
1269
+ // 转换脚本内容
1270
+ transformCode(app) {
1271
+ const sourceMapUrl = "";
1272
+ if (app.sandBox) {
1273
+ if (this.isModule) {
1274
+ return ` with(window.${app.sandBox.windowSymbolKey}){
4
1275
  ;${this.code}
5
1276
 
6
- ${t}
7
- }`:e.showSourceCode?`;(function(window, self, globalThis){
1277
+ ${sourceMapUrl}
1278
+ }`;
1279
+ }
1280
+ if (app.showSourceCode) {
1281
+ return `;(function(window, self, globalThis){
8
1282
  with(window){
9
- ${Q()}
1283
+ ${getGlobalContextCode()}
10
1284
 
11
1285
  ${this.code}
12
1286
 
13
- ${t}
1287
+ ${sourceMapUrl}
14
1288
  }
15
- }).call(window.${e.sandBox.windowSymbolKey},
16
- window.${e.sandBox.windowSymbolKey}, window.${e.sandBox.windowSymbolKey}, window.${e.sandBox.windowSymbolKey});`:`
1289
+ }).call(window.${app.sandBox.windowSymbolKey},
1290
+ window.${app.sandBox.windowSymbolKey}, window.${app.sandBox.windowSymbolKey}, window.${app.sandBox.windowSymbolKey});`;
1291
+ }
1292
+ return `
17
1293
  with(window) {
18
1294
  try {
19
- ${Q()}
1295
+ ${getGlobalContextCode()}
20
1296
 
21
1297
  ${this.code}
22
1298
 
23
- ${t}
1299
+ ${sourceMapUrl}
24
1300
  }
25
1301
  catch(e) {
26
1302
  console.error(e)
27
1303
  }
28
1304
  }
29
- `:this.code}};function Ie(r,e){return!r.hasOwnProperty(e)||!Number.isNaN(e)&&e<r.length||typeof navigator<"u"&&navigator.userAgent.indexOf("Trident")!==-1&&r[e]&&typeof window<"u"&&r[e].parent===window}function ze(r,e){let t=0,o,n;for(let i in r)if(!Ie(r,i)){if(t===0&&i!==q||t===1&&i!==$)return i;o?(z=i,n=e&&n||i):o=i===z,t+=1}return n}function Ze(r){$=void 0,q=$;for(let e in r)Ie(r,e)||(q?$||($=e):q=e,z=e);return z}async function G(r){let e=Array.from(r.source.scripts.values()).filter(i=>i.fromHtml||i.initial),t=e.filter(i=>!i.async&&!i.defer||i.isModule);await Promise.all(t.map(i=>i.getCode(r))),await Promise.all(t.map(i=>i.executeCode(r)));let o=[],n=[];for(let i of e)(i.defer||i.async)&&(!i.code&&i.defer?o.push(i.executeCode(r)):n.push(i.executeCode(r)));await Promise.all([...n,...o]).catch(i=>{console.error(i)})}var We="about:blank",A=class{state="UNSET";container;data;iframe=null;initSource;isModuleApp=!1;isPreLoad=!1;keepAlive;mode="app";name;sandBox;scopeCss;scopeJs;scopeLocation;showSourceCode;source;url;constructor(e){this.name=e.id!==e.url?e.id:W(5),this.mode=e.mode??"app",this.container=e.container??void 0,this.showSourceCode=e.showSourceCode??!1,this.url=e.url,this.data=e.data||{},this.scopeJs=e.scopeJs??!0,this.scopeCss=e.scopeCss??!0,this.scopeLocation=e.scopeLocation??!1,this.isPreLoad=e.isPreLoad??!1,this.keepAlive=e.keepAlive??!1,this.initSource=e.initSource??[],this.scopeJs&&(this.sandBox=new R(this)),this.container instanceof HTMLElement&&this.container.setAttribute(I,this.name)}activated(e,t){this.isPreLoad=!1,this.state="ACTIVATED";let o=this;if(e&&this.container){e instanceof Element&&e.setAttribute(I,this.name);let n=document.createDocumentFragment(),i=Array.from(this.container.childNodes);for(let c of i)c.__BK_WEWEB_APP_KEY__=this.appCacheKey,Object.defineProperties(c,{ownerDocument:{get(){return o.sandBox?.rawDocument}}}),n.appendChild(c);e.innerHTML="",e.appendChild(n),this.container=e,this.initShadowRootContainer(),this.sandBox?.activated(this.data),t?.(this)}}createIframe(){return new Promise(e=>{let t=document.createElement("iframe"),o=new URL(x(this.url)),n=navigator.userAgent.indexOf("Chrome")>-1;if(t.setAttribute("src",`${n?We:location.origin}${o.pathname||"/"}${o.search}${o.hash}`),t.style.cssText="display: none;",document.body.appendChild(t),n)setTimeout(()=>e(t),0);else{let i=setInterval(()=>{t.contentWindow&&t.contentWindow.location.href!==We&&(t.contentWindow.stop(),t.contentDocument.body.parentElement.innerHTML="<head></head><body></body>",clearInterval(i),e(t))},0)}})}deactivated(){this.state="DEACTIVATED",this.sandBox?.deactivated()}initShadowRootContainer(){this.container instanceof ShadowRoot&&Object.defineProperties(this.container,{getBoundingClientRect:{get(){return this.host.getBoundingClientRect}}})}mount(e,t){this.isPreLoad=!1,this.container=e??this.container,this.initShadowRootContainer(),this.state="MOUNTING";let o=this;if(this.container){this.container instanceof Element&&this.container.setAttribute(I,this.name);let n=this.source.html.cloneNode(!0),i=document.createDocumentFragment();for(let c of Array.from(n.childNodes))c.__BK_WEWEB_APP_KEY__=this.appCacheKey,Object.defineProperties(c,{ownerDocument:{get(){return o.sandBox?.rawDocument}}}),i.appendChild(c);this.container.innerHTML="",this.container.appendChild(i),this.sandBox?.activated(this.data),G(this).finally(()=>{this.state="MOUNTED",t?.(this)})}}onError(){this.state="ERROR"}onMount(){this.isPreLoad||(this.state="LOADED",this.mount())}registerRunningApp(){T(this),Promise.resolve().then(()=>T(null))}async start(){if(!this.source||["ERROR","UNSET"].includes(this.status)){if(this.state="LOADING",this.scopeLocation||this.isModuleApp){let e=await this.createIframe();this.iframe=e}this.source=new v(this.url),await this.source.importEntry(this)}}unmount(e=!1){this.state="UNMOUNT",this.sandBox?.deactivated(),e&&a.deleteApp(this.url),this.container.innerHTML="",this.container=void 0}get appCacheKey(){return this.url}get status(){return this.state}set status(e){this.state=e}};async function le(r){let e=[];if(typeof r=="function"?e=await r():e=r||[],!e.length)return{};let t=new Map,o=new Map;return e.forEach(n=>{try{let i=new URL(n);if(i.pathname.match(/\.js$/)){let c=a.getCacheScript(n);t.set(n,new y({async:!1,code:c?.code||"",defer:!1,fromHtml:!1,initial:!0,isModule:!1,url:n}))}else if(i.pathname.match(/\.css$/)){let c=a.getCacheStyle(n);o.set(n,new w({code:c?.code||"",fromHtml:!0,initial:!0,prefetch:!1,preload:!1,url:n}))}}catch{console.error(`\u3010bk-weweb\u3011: ${n} is invalid URL`)}}),{collectScript:t,collectStyle:o}}async function Re(r){let{collectScript:e,collectStyle:t}=await le(r),o=[];e&&Array.from(e.entries()).forEach(n=>{o.push(n[1].getCode()),a.setBaseAppScript(...n)}),t&&Array.from(t.entries()).forEach(n=>{o.push(n[1].getCode()),a.setBaseAppStyle(...n)}),await Promise.all(o).catch(n=>{throw n})}var Xe=["text/javascript","text/ecmascript","application/javascript","application/ecmascript","module"],v=class{constructor(e){this.url=e;this.scripts=new Map,this.styles=new Map}html=null;rawHtml;scripts;styles;collectLink(e,t,o=!1){if(e.hasAttribute("exclude"))return{replace:document.createComment("\u3010bk-weweb\u3011style with exclude attribute is ignored")};if(e.hasAttribute("ignore"))return{replace:e};let n=e.getAttribute("rel"),i=e.getAttribute("href"),c;if(n==="stylesheet"&&i){i=h(i,this.url),c=document.createComment(`\u3010bk-weweb\u3011style with href=${i}`);let s=this.getStyle(i);return s||(s=new w({code:"",fromHtml:!o,prefetch:!!e.getAttribute("prefetch"),preload:!!e.getAttribute("preload"),url:i}),this.styles.set(i,s)),!o&&t.replaceChild(c,e),{replace:c,style:s}}return n&&["apple-touch-icon","icon","prefetch","preload","prerender"].includes(n)?(c=document.createComment(`\u3010bk-weweb\u3011style with rel=${n}${i?` & href=${i}`:""}`),!o&&t.removeChild(e),{replace:c}):(i&&e.setAttribute("href",h(i,this.url)),{replace:e})}collectScript(e,t,o=!1){if(e.hasAttribute("ignore")||e.type!=="module"&&J(e.getAttribute("src"))||e.hasAttribute("type")&&!Xe.includes(e.type))return;let n=null;if(e.hasAttribute("exclude"))return n=document.createComment("\u3010bk-weweb\u3011script element with exclude attribute is removed"),!o&&t.replaceChild(n,e),{replace:n};let i=e.getAttribute("src");if(i){i=h(i,this.url);let c=this.getScript(i);return c||(c=new y({async:e.hasAttribute("async"),code:"",defer:e.defer||e.type==="module",fromHtml:!o,isModule:e.type==="module",url:i}),this.scripts.set(i,c)),n=document.createComment(`\u3010bk-weweb\u3011script with src='${i}'`),!o&&t.replaceChild(n,e),{replace:n,script:c}}if(e.textContent){let c=L(),s=new y({async:!1,code:e.textContent,defer:e.type==="module",fromHtml:!o,initial:!1,isModule:e.type==="module",url:c});return this.scripts.set(c,s),n=document.createComment("\u3010bk-weweb\u3011script with text content"),!o&&t.replaceChild(n,e),{replace:n,script:s}}return{replace:e}}collectScriptAndStyle(e){let t=Array.from(e.querySelectorAll("link"));for(let s of t||[])this.collectLink(s,s.parentElement);let o=Array.from(e.querySelectorAll("style"));for(let s of o||[])!s.hasAttribute("exclude")&&!s.hasAttribute("ignore")&&(this.styles.set(L(),new w({code:s.textContent||"",fromHtml:!0,url:""})),s.remove());let n=Array.from(e.querySelectorAll("script"));for(let s of n)this.collectScript(s,s.parentElement);let i=Array.from(e.querySelectorAll("meta"));for(let s of i)s.parentElement.removeChild(s);let c=Array.from(e.querySelectorAll("img"));for(let s of c)s.hasAttribute("src")&&s.setAttribute("src",h(s.getAttribute("src"),this.url))}getScript(e){return this.scripts.get(e)}getStyle(e){return this.styles.get(e)||Array.from(this.styles.values()).find(t=>t.code===e)}async importEntry(e){if(e.initSource?.length){let{collectScript:t,collectStyle:o}=await le(e.initSource);t&&(this.scripts=t),o&&(this.styles=o)}e instanceof A?await this.importHtmlEntry(e):e instanceof C&&await this.importInstanceEntry(e)}async importHtmlEntry(e){let t=a.getCacheHtml(this.url);if(!t&&(t=await g(x(this.url),{cache:"no-cache"},e),!t))return console.error("load app entry error, place check"),Promise.reject();this.rawHtml=t;let o=document.createElement("div");o.__BK_WEWEB_APP_KEY__&&(o.__BK_WEWEB_APP_KEY__=void 0),o.innerHTML=t.replace(/<\/?head>/gim,"").replace(/<\/?body>/i,""),this.collectScriptAndStyle(o),await V(e,o),this.html=o}async importInstanceEntry(e){let t=a.getCacheScript(this.url)?.code;if(t||(t=await g(this.url,{cache:"no-cache"},e)),!t)return console.error("load app entry error, place check"),Promise.reject();this.scripts.set(this.url,new y({async:!1,code:t,defer:!1,fromHtml:!0,isModule:!!this.url.match(/\.ts$/),url:this.url}))}setScript(e,t){this.scripts.set(e,t instanceof y?t:new y(t))}setStyle(e,t){this.styles.set(e,t)}};var de=class{baseSource;cache;constructor(){this.cache=new Map,this.baseSource=new v(location.href)}deleteApp(e){this.cache.delete(e)}getApp(e){if(!e)return;let t=this.cache.get(e);return t||Array.from(this.cache.values()).find(o=>o.name===e)}getBaseAppStyle(e){return this.baseSource.getStyle(e)}getCacheHtml(e){let o=Array.from(this.cache.values()).find(n=>n.url===e);return o&&o.source?.rawHtml||""}getCacheScript(e){let t=this.baseSource.getScript(e);return t?void 0:(Array.from(this.cache.values()).some(n=>(t=n.source?.getScript(e),!!t)),t)}getCacheStyle(e){let t=this.baseSource.getStyle(e);return t?void 0:(Array.from(this.cache.values()).some(n=>(t=n.source?.getStyle(e),!!t)),t)}setApp(e){this.cache.set(e.appCacheKey,e)}setBaseAppScript(e,t){this.baseSource.setScript(e,t)}setBaseAppStyle(e,t){this.baseSource.setStyle(e,t)}get hasActiveApp(){return Array.from(this.cache.values()).some(e=>e.status!=="UNMOUNT")}},a=new de;window.__getAppOrInstance__=r=>r?a.getApp(r):a;function Qe(r,e,t){let o=document.createElement("style");return E(o),g(r).then(n=>{e.code=n,a.setBaseAppStyle(r,e),o.textContent=n,_(t)}).catch(n=>{console.error(n),U(t)}),o}function et(r,e,t){let o=document.createElement("script");return E(o),g(r).then(n=>{e.setCode(n);try{o.textContent=n,r.startsWith("inline-")||t.setAttribute("origin-src",r)}catch(i){console.error(i,r)}_(t)}).catch(n=>{console.error(n),U(t)}),o}function Oe(r){if(r instanceof HTMLLinkElement){let e=r.getAttribute("rel"),t=r.getAttribute("href");if(e==="stylesheet"&&t){t=h(t,location.origin);let o=document.createElement("style"),n=new w({code:"",fromHtml:!1,url:t});return Qe(t,n,r),o}}if(r instanceof HTMLScriptElement){let e=r.getAttribute("src");if(e&&r.type!=="module"){e=h(e,location.origin);let t=new y({async:r.hasAttribute("async"),code:"",defer:r.defer||r.type==="module",fromHtml:!1,isModule:!1});return a.setBaseAppScript(e,t),et(e,t,r)||r}}return r}function He(r){return r instanceof HTMLLinkElement||r instanceof HTMLScriptElement}function Ne(r,e,t,o){if(He(e)){let n=Oe(e);return o.call(r,n,t)}return o.call(r,e,t)}function ue(r,e,t){if(He(e)){let o=Oe(e);return t.call(r,o)}return t.call(r,e)}function Ke(){let r=HTMLBodyElement.prototype.appendChild,e=HTMLHeadElement.prototype.appendChild,t=HTMLHeadElement.prototype.appendChild;HTMLBodyElement.prototype.appendChild=function(o){return ue(this,o,r)},HTMLHeadElement.prototype.appendChild=function(o){return ue(this,o,e)},HTMLHeadElement.prototype.insertBefore=function(o,n){return Ne(this,o,n,t)},window.addEventListener("load",()=>{let o=document.head.querySelectorAll("style");for(let n of Array.from(o))n.textContent&&a.setBaseAppStyle(L(),new w({code:n.textContent,fromHtml:!1,url:""}))})}var{setAttribute:pe}=Element.prototype,{append:tt,appendChild:fe,insertBefore:ot,removeChild:me}=HTMLBodyElement.prototype,{appendChild:he,insertBefore:ye,removeChild:rt}=HTMLHeadElement.prototype,De=document.head,Se=!1;function Ue(){Se||(Se=!0,Element.prototype.setAttribute=function(r,e){let t=this.tagName.toLocaleUpperCase();(["src","srcset"].includes(r)&&["IMG","SCRIPT"].includes(t)||r==="href"&&["LINK"].includes(t))&&this.__BK_WEWEB_APP_KEY__&&a.getApp(this.__BK_WEWEB_APP_KEY__||"")?pe.call(this,r,h(e,a.getApp(this.__BK_WEWEB_APP_KEY__).url)):pe.call(this,r,e)},HTMLBodyElement.prototype.appendChild=function(e){return e.__KEEP_ALIVE__&&k(e)?he.call(De,e):se(this,e,fe)},HTMLBodyElement.prototype.append=function(...r){r.forEach(e=>{if(e.__KEEP_ALIVE__&&k(e))return he.call(De,e);se(this,e,fe)})},HTMLHeadElement.prototype.appendChild=HTMLBodyElement.prototype.appendChild,HTMLHeadElement.prototype.insertBefore=function(r,e){return ce(this,r,e,ye)},HTMLBodyElement.prototype.insertBefore=function(r,e){return ce(this,r,e,ye)},HTMLBodyElement.prototype.removeChild=function(e){let t=a.getApp(e.__BK_WEWEB_APP_KEY__);return t?.container?.contains(e)?me.call(t.container,e):this.contains(e)?me.call(this,e):e},HTMLHeadElement.prototype.removeChild=HTMLBodyElement.prototype.removeChild)}function Z(){T(null),Element.prototype.setAttribute=pe,HTMLBodyElement.prototype.appendChild=fe,HTMLBodyElement.prototype.append=tt,HTMLBodyElement.prototype.removeChild=me,HTMLBodyElement.prototype.insertBefore=ot,HTMLHeadElement.prototype.appendChild=he,HTMLHeadElement.prototype.insertBefore=ye,HTMLHeadElement.prototype.removeChild=rt,Se=!1}function M(){Ue()}function we(r,e,t){let o=a.getApp(r);o?.status==="DEACTIVATED"&&o.keepAlive?D(()=>{M(),o.activated(e,t)}):o&&D(()=>{M(),o.mount(e,t)})}function ke(r){let e=a.getApp(r);e&&["ACTIVATED","MOUNTED"].includes(e.status)&&(e.keepAlive?e.deactivated():e.unmount()),a.hasActiveApp||Z()}async function Ae(r){return M(),r.mode==="js"?await ge(r):await Ee(r)}async function Ee(r){M();let e=a.getApp(r.id);return e||(e=new A(r),a.setApp(e)),await e.start(),e}function ge(r){return M(),new Promise(e=>{let t=a.getApp(r.id);if(!t)t=new C(r),a.setApp(t),t.start().then(()=>e(t));else if(["MOUNTING","UNSET"].includes(t.status)){let o=setInterval(()=>{["ERROR","MOUNTED"].includes(t.status)&&(e(t),clearInterval(o))},300)}else e(t)})}function $e(r){let e=a.getApp(r);e&&e.status!=="UNMOUNT"&&e.unmount(),a.hasActiveApp||Z()}var H=class extends HTMLElement{appUrl="";connected=!1;static get observedAttributes(){return["url"]}getBooleanAttr(e){return this.hasAttribute(e)||this.hasAttribute(e.replace(/([A-Z])/g,"-$1").toLocaleLowerCase())?this.getAttribute(e)!=="false":void 0}async handleAttributeChanged(){if(!this.appKey)return;this.getBooleanAttr("setShodowDom")&&this.attachShadow({mode:"open"});let e=a.getApp(this.appKey);if(e&&e.url===this.appUrl&&(e.isPreLoad||e.status==="UNMOUNT")){we(this.appKey,this.shadowRoot??this);return}await Ae(this.appProps)}attributeChangedCallback(e,t,o){if(e!=="url"||this[e]===o||!this.connected)return;this.appUrl=o;let n=a.getApp(this.appKey);(this.connected||n)&&this.handleAttributeChanged()}async connectedCallback(){this.getBooleanAttr("setShodowDom")&&!this.shadowRoot&&this.attachShadow({delegatesFocus:!1,mode:"open"}),await Ae(this.appProps),we(this.appKey,this.shadowRoot??this),this.connected=!0}disconnectedCallback(){this.connected=!1,this.appProps.keepAlive?ke(this.appKey):$e(this.appKey)}get appData(){if(this.hasAttribute("data"))try{return JSON.parse(this.getAttribute("data"))}catch{}return{}}get appKey(){return this.getAttribute("id")||this.getAttribute("url")}get appProps(){return this.getAttribute("mode")==="js"?{container:this.shadowRoot??this,data:this.appData,id:this.appKey,keepAlive:this.getBooleanAttr("keepAlive"),mode:"js",scopeCss:this.getBooleanAttr("scopeCss")&&!this.getBooleanAttr("setShodowDom"),scopeJs:this.getBooleanAttr("scopeJs"),showSourceCode:this.getBooleanAttr("showSourceCode"),url:this.getAttribute("url")}:{container:this.shadowRoot??this,data:this.appData,id:this.appKey,keepAlive:this.getBooleanAttr("keepAlive"),mode:"app",scopeCss:!this.getBooleanAttr("setShodowDom"),scopeJs:!this.getBooleanAttr("scopeJs"),scopeLocation:this.getBooleanAttr("scopeLocation"),showSourceCode:this.getBooleanAttr("showSourceCode"),url:this.getAttribute("url")}}};function kr(r,e,t){let o=a.getApp(r);o&&D(()=>{M(),o.mount(e,t)})}function jr(r){a.deleteApp(r)}function qr(r){Y(()=>ge({...r,isPreLoad:!0}))}function zr(r){Y(()=>Ee({...r,isPreLoad:!0}))}function Zr(r){Y(()=>{Re(r)})}var X="bk-weweb",be=class{fetchSource;webcomponentTag=X;constructor(){window.customElements.get(X)||window.customElements.define(X,H)}setWebComponentTag(){window.customElements.get(this.webcomponentTag)||window.customElements.define(this.webcomponentTag,H)}start(e){e?.collectBaseSource&&Ke(),typeof e?.fetchSource=="function"&&(this.fetchSource=e.fetchSource),this.webcomponentTag=e?.webcomponentTag||X,this.setWebComponentTag()}},nt=new be,ae=nt;export{be as WeWeb,K as WewebMode,we as activated,ke as deactivated,ae as default,Ae as load,Ee as loadApp,ge as loadInstance,kr as mount,zr as preLoadApp,qr as preLoadInstance,Zr as preLoadSource,jr as unload,$e as unmount};
1305
+ `;
1306
+ }
1307
+ return this.code;
1308
+ }
1309
+ };
1310
+ function shouldSkipProperty(global, p) {
1311
+ return (
1312
+ // biome-ignore lint/suspicious/noPrototypeBuiltins: <explanation>
1313
+ !global.hasOwnProperty(p) || !Number.isNaN(p) && p < global.length || typeof navigator !== "undefined" && navigator.userAgent.indexOf("Trident") !== -1 && global[p] && typeof window !== "undefined" && global[p].parent === window
1314
+ );
1315
+ }
1316
+ function getGlobalProp(global, useFirstGlobalProp) {
1317
+ let cnt = 0;
1318
+ let foundLastProp;
1319
+ let result;
1320
+ for (const p in global) {
1321
+ if (shouldSkipProperty(global, p)) continue;
1322
+ if (cnt === 0 && p !== firstGlobalProp || cnt === 1 && p !== secondGlobalProp) return p;
1323
+ if (foundLastProp) {
1324
+ lastGlobalProp = p;
1325
+ result = useFirstGlobalProp && result || p;
1326
+ } else {
1327
+ foundLastProp = p === lastGlobalProp;
1328
+ }
1329
+ cnt += 1;
1330
+ }
1331
+ return result;
1332
+ }
1333
+ function noteGlobalProps(global) {
1334
+ secondGlobalProp = void 0;
1335
+ firstGlobalProp = secondGlobalProp;
1336
+ for (const p in global) {
1337
+ if (shouldSkipProperty(global, p)) continue;
1338
+ if (!firstGlobalProp) firstGlobalProp = p;
1339
+ else if (!secondGlobalProp) secondGlobalProp = p;
1340
+ lastGlobalProp = p;
1341
+ }
1342
+ return lastGlobalProp;
1343
+ }
1344
+ async function execAppScripts(app) {
1345
+ const appScriptList = Array.from(app.source.scripts.values()).filter((script) => script.fromHtml || script.initial);
1346
+ const commonList = appScriptList.filter((script) => !script.async && !script.defer || script.isModule);
1347
+ await Promise.all(commonList.map((script) => script.getCode(app)));
1348
+ await Promise.all(commonList.map((script) => script.executeCode(app)));
1349
+ const deferScriptList = [];
1350
+ const asyncScriptList = [];
1351
+ for (const script of appScriptList) {
1352
+ if (script.defer || script.async) {
1353
+ if (!script.code && script.defer) {
1354
+ deferScriptList.push(script.executeCode(app));
1355
+ } else asyncScriptList.push(script.executeCode(app));
1356
+ }
1357
+ }
1358
+ await Promise.all([...asyncScriptList, ...deferScriptList]).catch((e) => {
1359
+ console.error(e);
1360
+ });
1361
+ }
1362
+
1363
+ // src/mode/app.ts
1364
+ var BLANK_ORIGN = "about:blank";
1365
+ var MicroAppModel = class {
1366
+ state = "UNSET" /* UNSET */;
1367
+ // 状态
1368
+ container;
1369
+ // 容器
1370
+ data;
1371
+ // 数据
1372
+ iframe = null;
1373
+ // scoped iframe
1374
+ initSource;
1375
+ // 初始资源
1376
+ isModuleApp = false;
1377
+ // 是否预加载
1378
+ isPreLoad = false;
1379
+ // 是否缓存
1380
+ keepAlive;
1381
+ mode = "app" /* APP */;
1382
+ // 名称
1383
+ name;
1384
+ // 沙箱
1385
+ sandBox;
1386
+ // 是否隔离样式
1387
+ scopeCss;
1388
+ // 是否隔离js
1389
+ scopeJs;
1390
+ // 是否隔离location
1391
+ scopeLocation;
1392
+ // 是否显示源码
1393
+ showSourceCode;
1394
+ // 入口资源
1395
+ source;
1396
+ // url
1397
+ url;
1398
+ // 是否是esm应用
1399
+ constructor(props) {
1400
+ this.name = props.id !== props.url ? props.id : random(5);
1401
+ this.mode = props.mode ?? "app" /* APP */;
1402
+ this.container = props.container ?? void 0;
1403
+ this.showSourceCode = props.showSourceCode ?? false;
1404
+ this.url = props.url;
1405
+ this.data = props.data || {};
1406
+ this.scopeJs = props.scopeJs ?? true;
1407
+ this.scopeCss = props.scopeCss ?? true;
1408
+ this.scopeLocation = props.scopeLocation ?? false;
1409
+ this.isPreLoad = props.isPreLoad ?? false;
1410
+ this.keepAlive = props.keepAlive ?? false;
1411
+ this.initSource = props.initSource ?? [];
1412
+ if (this.scopeJs) {
1413
+ this.sandBox = new SandBox(this);
1414
+ }
1415
+ if (this.container instanceof HTMLElement) {
1416
+ this.container.setAttribute(CSS_ATTRIBUTE_KEY, this.name);
1417
+ }
1418
+ }
1419
+ // 激活
1420
+ activated(container, callback) {
1421
+ this.isPreLoad = false;
1422
+ this.state = "ACTIVATED" /* ACTIVATED */;
1423
+ const app = this;
1424
+ if (container && this.container) {
1425
+ if (container instanceof Element) container.setAttribute(CSS_ATTRIBUTE_KEY, this.name);
1426
+ const fragment = document.createDocumentFragment();
1427
+ const list = Array.from(this.container.childNodes);
1428
+ for (const node of list) {
1429
+ node.__BK_WEWEB_APP_KEY__ = this.appCacheKey;
1430
+ Object.defineProperties(node, {
1431
+ ownerDocument: {
1432
+ get() {
1433
+ return app.sandBox?.rawDocument;
1434
+ }
1435
+ }
1436
+ });
1437
+ fragment.appendChild(node);
1438
+ }
1439
+ container.innerHTML = "";
1440
+ container.appendChild(fragment);
1441
+ this.container = container;
1442
+ this.initShadowRootContainer();
1443
+ this.sandBox?.activated(this.data);
1444
+ callback?.(this);
1445
+ }
1446
+ }
1447
+ // 创建隔离iframe
1448
+ createIframe() {
1449
+ return new Promise((resolve) => {
1450
+ const iframe = document.createElement("iframe");
1451
+ const url = new URL(addUrlProtocol(this.url));
1452
+ const isChrome = navigator.userAgent.indexOf("Chrome") > -1;
1453
+ iframe.setAttribute(
1454
+ "src",
1455
+ `${isChrome ? BLANK_ORIGN : location.origin}${url.pathname || "/"}${url.search}${url.hash}`
1456
+ );
1457
+ iframe.style.cssText = "display: none;";
1458
+ document.body.appendChild(iframe);
1459
+ if (isChrome) {
1460
+ setTimeout(() => resolve(iframe), 0);
1461
+ } else {
1462
+ const interval = setInterval(() => {
1463
+ if (iframe.contentWindow && iframe.contentWindow.location.href !== BLANK_ORIGN) {
1464
+ iframe.contentWindow.stop();
1465
+ iframe.contentDocument.body.parentElement.innerHTML = "<head></head><body></body>";
1466
+ clearInterval(interval);
1467
+ resolve(iframe);
1468
+ }
1469
+ }, 0);
1470
+ }
1471
+ });
1472
+ }
1473
+ deactivated() {
1474
+ this.state = "DEACTIVATED" /* DEACTIVATED */;
1475
+ this.sandBox?.deactivated();
1476
+ }
1477
+ initShadowRootContainer() {
1478
+ if (this.container instanceof ShadowRoot) {
1479
+ Object.defineProperties(this.container, {
1480
+ getBoundingClientRect: {
1481
+ get() {
1482
+ return this.host.getBoundingClientRect;
1483
+ }
1484
+ }
1485
+ });
1486
+ }
1487
+ }
1488
+ mount(container, callback) {
1489
+ this.isPreLoad = false;
1490
+ this.container = container ?? this.container;
1491
+ this.initShadowRootContainer();
1492
+ this.state = "MOUNTING" /* MOUNTING */;
1493
+ const app = this;
1494
+ if (this.container) {
1495
+ if (this.container instanceof Element) this.container.setAttribute(CSS_ATTRIBUTE_KEY, this.name);
1496
+ const clonedNode = this.source.html.cloneNode(true);
1497
+ const fragment = document.createDocumentFragment();
1498
+ for (const node of Array.from(clonedNode.childNodes)) {
1499
+ node.__BK_WEWEB_APP_KEY__ = this.appCacheKey;
1500
+ Object.defineProperties(node, {
1501
+ ownerDocument: {
1502
+ get() {
1503
+ return app.sandBox?.rawDocument;
1504
+ }
1505
+ }
1506
+ });
1507
+ fragment.appendChild(node);
1508
+ }
1509
+ this.container.innerHTML = "";
1510
+ this.container.appendChild(fragment);
1511
+ this.sandBox?.activated(this.data);
1512
+ execAppScripts(this).finally(() => {
1513
+ this.state = "MOUNTED" /* MOUNTED */;
1514
+ callback?.(this);
1515
+ });
1516
+ }
1517
+ }
1518
+ onError() {
1519
+ this.state = "ERROR" /* ERROR */;
1520
+ }
1521
+ onMount() {
1522
+ if (this.isPreLoad) return;
1523
+ this.state = "LOADED" /* LOADED */;
1524
+ this.mount();
1525
+ }
1526
+ registerRunningApp() {
1527
+ setCurrentRunningApp(this);
1528
+ Promise.resolve().then(() => setCurrentRunningApp(null));
1529
+ }
1530
+ async start() {
1531
+ if (!this.source || ["ERROR" /* ERROR */, "UNSET" /* UNSET */].includes(this.status)) {
1532
+ this.state = "LOADING" /* LOADING */;
1533
+ if (this.scopeLocation || this.isModuleApp) {
1534
+ const iframe = await this.createIframe();
1535
+ this.iframe = iframe;
1536
+ }
1537
+ this.source = new EntrySource(this.url);
1538
+ await this.source.importEntry(this);
1539
+ }
1540
+ }
1541
+ unmount(needDestroy = false) {
1542
+ this.state = "UNMOUNT" /* UNMOUNT */;
1543
+ this.sandBox?.deactivated();
1544
+ needDestroy && appCache.deleteApp(this.url);
1545
+ this.container.innerHTML = "";
1546
+ this.container = void 0;
1547
+ }
1548
+ get appCacheKey() {
1549
+ return this.url;
1550
+ }
1551
+ get status() {
1552
+ return this.state;
1553
+ }
1554
+ set status(v) {
1555
+ this.state = v;
1556
+ }
1557
+ };
1558
+
1559
+ // src/utils/load-source.ts
1560
+ async function collectSource(soruceList) {
1561
+ let source = [];
1562
+ if (typeof soruceList === "function") {
1563
+ source = await soruceList();
1564
+ } else {
1565
+ source = soruceList || [];
1566
+ }
1567
+ if (!source.length) return {};
1568
+ const collectScript = /* @__PURE__ */ new Map();
1569
+ const collectStyle = /* @__PURE__ */ new Map();
1570
+ source.forEach((str) => {
1571
+ try {
1572
+ const url = new URL(str);
1573
+ if (url.pathname.match(/\.js$/)) {
1574
+ const script = appCache.getCacheScript(str);
1575
+ collectScript.set(
1576
+ str,
1577
+ new Script({
1578
+ async: false,
1579
+ code: script?.code || "",
1580
+ defer: false,
1581
+ fromHtml: false,
1582
+ initial: true,
1583
+ isModule: false,
1584
+ url: str
1585
+ })
1586
+ );
1587
+ } else if (url.pathname.match(/\.css$/)) {
1588
+ const style = appCache.getCacheStyle(str);
1589
+ collectStyle.set(
1590
+ str,
1591
+ new Style({
1592
+ code: style?.code || "",
1593
+ fromHtml: true,
1594
+ initial: true,
1595
+ prefetch: false,
1596
+ preload: false,
1597
+ url: str
1598
+ })
1599
+ );
1600
+ }
1601
+ } catch {
1602
+ console.error(`\u3010bk-weweb\u3011: ${str} is invalid URL`);
1603
+ }
1604
+ });
1605
+ return {
1606
+ collectScript,
1607
+ collectStyle
1608
+ };
1609
+ }
1610
+ async function loadGlobalSource(soruceList) {
1611
+ const { collectScript, collectStyle } = await collectSource(soruceList);
1612
+ const promiseList = [];
1613
+ collectScript && Array.from(collectScript.entries()).forEach((item) => {
1614
+ promiseList.push(item[1].getCode());
1615
+ appCache.setBaseAppScript(...item);
1616
+ });
1617
+ collectStyle && Array.from(collectStyle.entries()).forEach((item) => {
1618
+ promiseList.push(item[1].getCode());
1619
+ appCache.setBaseAppStyle(...item);
1620
+ });
1621
+ await Promise.all(promiseList).catch((e) => {
1622
+ throw e;
1623
+ });
1624
+ }
1625
+
1626
+ // src/entry/entry.ts
1627
+ var SCRIPT_TYPE_NAMES = [
1628
+ "text/javascript",
1629
+ "text/ecmascript",
1630
+ "application/javascript",
1631
+ "application/ecmascript",
1632
+ "module"
1633
+ ];
1634
+ var EntrySource = class {
1635
+ constructor(url) {
1636
+ this.url = url;
1637
+ this.scripts = /* @__PURE__ */ new Map();
1638
+ this.styles = /* @__PURE__ */ new Map();
1639
+ }
1640
+ html = null;
1641
+ rawHtml;
1642
+ scripts;
1643
+ styles;
1644
+ collectLink(link, parent, needReplaceELement = false) {
1645
+ if (link.hasAttribute("exclude")) {
1646
+ return { replace: document.createComment("\u3010bk-weweb\u3011style with exclude attribute is ignored") };
1647
+ }
1648
+ if (link.hasAttribute("ignore")) {
1649
+ return { replace: link };
1650
+ }
1651
+ const rel = link.getAttribute("rel");
1652
+ let href = link.getAttribute("href");
1653
+ let replaceElement;
1654
+ if (rel === "stylesheet" && href) {
1655
+ href = fillUpPath(href, this.url);
1656
+ replaceElement = document.createComment(`\u3010bk-weweb\u3011style with href=${href}`);
1657
+ let styleInstance = this.getStyle(href);
1658
+ if (!styleInstance) {
1659
+ styleInstance = new Style({
1660
+ code: "",
1661
+ fromHtml: !needReplaceELement,
1662
+ prefetch: !!link.getAttribute("prefetch"),
1663
+ preload: !!link.getAttribute("preload"),
1664
+ url: href
1665
+ });
1666
+ this.styles.set(href, styleInstance);
1667
+ }
1668
+ !needReplaceELement && parent.replaceChild(replaceElement, link);
1669
+ return { replace: replaceElement, style: styleInstance };
1670
+ }
1671
+ if (rel && ["apple-touch-icon", "icon", "prefetch", "preload", "prerender"].includes(rel)) {
1672
+ replaceElement = document.createComment(`\u3010bk-weweb\u3011style with rel=${rel}${href ? ` & href=${href}` : ""}`);
1673
+ !needReplaceELement && parent.removeChild(link);
1674
+ return { replace: replaceElement };
1675
+ }
1676
+ if (href) {
1677
+ link.setAttribute("href", fillUpPath(href, this.url));
1678
+ }
1679
+ return { replace: link };
1680
+ }
1681
+ collectScript(script, parent, needReplaceELement = false) {
1682
+ if (script.hasAttribute("ignore") || script.type !== "module" && isJsonpUrl(script.getAttribute("src")) || script.hasAttribute("type") && !SCRIPT_TYPE_NAMES.includes(script.type)) {
1683
+ return;
1684
+ }
1685
+ let replaceElement = null;
1686
+ if (script.hasAttribute("exclude")) {
1687
+ replaceElement = document.createComment("\u3010bk-weweb\u3011script element with exclude attribute is removed");
1688
+ !needReplaceELement && parent.replaceChild(replaceElement, script);
1689
+ return { replace: replaceElement };
1690
+ }
1691
+ let src = script.getAttribute("src");
1692
+ if (src) {
1693
+ src = fillUpPath(src, this.url);
1694
+ let scriptInstance = this.getScript(src);
1695
+ if (!scriptInstance) {
1696
+ scriptInstance = new Script({
1697
+ async: script.hasAttribute("async"),
1698
+ code: "",
1699
+ defer: script.defer || script.type === "module",
1700
+ fromHtml: !needReplaceELement,
1701
+ isModule: script.type === "module",
1702
+ url: src
1703
+ });
1704
+ this.scripts.set(src, scriptInstance);
1705
+ }
1706
+ replaceElement = document.createComment(`\u3010bk-weweb\u3011script with src='${src}'`);
1707
+ !needReplaceELement && parent.replaceChild(replaceElement, script);
1708
+ return { replace: replaceElement, script: scriptInstance };
1709
+ }
1710
+ if (script.textContent) {
1711
+ const nonceStr = randomUrl();
1712
+ const scriptInstance = new Script({
1713
+ async: false,
1714
+ // code: script.textContent.replace(/var\s+(\w+)=/gm, `window.$1 = `),
1715
+ code: script.textContent,
1716
+ defer: script.type === "module",
1717
+ fromHtml: !needReplaceELement,
1718
+ initial: false,
1719
+ isModule: script.type === "module",
1720
+ url: nonceStr
1721
+ });
1722
+ this.scripts.set(nonceStr, scriptInstance);
1723
+ replaceElement = document.createComment("\u3010bk-weweb\u3011script with text content");
1724
+ !needReplaceELement && parent.replaceChild(replaceElement, script);
1725
+ return {
1726
+ replace: replaceElement,
1727
+ script: scriptInstance
1728
+ };
1729
+ }
1730
+ return { replace: script };
1731
+ }
1732
+ collectScriptAndStyle(parent) {
1733
+ const links = Array.from(parent.querySelectorAll("link"));
1734
+ for (const link of links || []) {
1735
+ this.collectLink(link, link.parentElement);
1736
+ }
1737
+ const styles = Array.from(parent.querySelectorAll("style"));
1738
+ for (const style of styles || []) {
1739
+ if (!style.hasAttribute("exclude") && !style.hasAttribute("ignore")) {
1740
+ this.styles.set(
1741
+ randomUrl(),
1742
+ new Style({
1743
+ code: style.textContent || "",
1744
+ fromHtml: true,
1745
+ url: ""
1746
+ })
1747
+ );
1748
+ style.remove();
1749
+ }
1750
+ }
1751
+ const scripts = Array.from(parent.querySelectorAll("script"));
1752
+ for (const script of scripts) {
1753
+ this.collectScript(script, script.parentElement);
1754
+ }
1755
+ const metas = Array.from(parent.querySelectorAll("meta"));
1756
+ for (const meta of metas) {
1757
+ meta.parentElement.removeChild(meta);
1758
+ }
1759
+ const imgs = Array.from(parent.querySelectorAll("img"));
1760
+ for (const img of imgs) {
1761
+ if (img.hasAttribute("src")) {
1762
+ img.setAttribute("src", fillUpPath(img.getAttribute("src"), this.url));
1763
+ }
1764
+ }
1765
+ }
1766
+ getScript(url) {
1767
+ return this.scripts.get(url);
1768
+ }
1769
+ getStyle(urlOrCode) {
1770
+ return this.styles.get(urlOrCode) || Array.from(this.styles.values()).find((style) => style.code === urlOrCode);
1771
+ }
1772
+ async importEntry(app) {
1773
+ if (app.initSource?.length) {
1774
+ const { collectScript, collectStyle } = await collectSource(app.initSource);
1775
+ if (collectScript) {
1776
+ this.scripts = collectScript;
1777
+ }
1778
+ if (collectStyle) {
1779
+ this.styles = collectStyle;
1780
+ }
1781
+ }
1782
+ if (app instanceof MicroAppModel) await this.importHtmlEntry(app);
1783
+ else if (app instanceof MicroInstanceModel) await this.importInstanceEntry(app);
1784
+ }
1785
+ async importHtmlEntry(app) {
1786
+ let htmlStr = appCache.getCacheHtml(this.url);
1787
+ if (!htmlStr) {
1788
+ htmlStr = await fetchSource(addUrlProtocol(this.url), { cache: "no-cache" }, app);
1789
+ if (!htmlStr) {
1790
+ console.error("load app entry error, place check");
1791
+ return Promise.reject();
1792
+ }
1793
+ }
1794
+ this.rawHtml = htmlStr;
1795
+ const wrapElement = document.createElement("div");
1796
+ if (wrapElement.__BK_WEWEB_APP_KEY__) {
1797
+ wrapElement.__BK_WEWEB_APP_KEY__ = void 0;
1798
+ }
1799
+ wrapElement.innerHTML = htmlStr.replace(/<\/?head>/gim, "").replace(/<\/?body>/i, "");
1800
+ this.collectScriptAndStyle(wrapElement);
1801
+ await executeAppStyles(app, wrapElement);
1802
+ this.html = wrapElement;
1803
+ }
1804
+ async importInstanceEntry(app) {
1805
+ let jsStr = appCache.getCacheScript(this.url)?.code;
1806
+ if (!jsStr) {
1807
+ jsStr = await fetchSource(this.url, { cache: "no-cache" }, app);
1808
+ }
1809
+ if (!jsStr) {
1810
+ console.error("load app entry error, place check");
1811
+ return Promise.reject();
1812
+ }
1813
+ this.scripts.set(
1814
+ this.url,
1815
+ new Script({
1816
+ async: false,
1817
+ code: jsStr,
1818
+ defer: false,
1819
+ fromHtml: true,
1820
+ isModule: !!this.url.match(/\.ts$/),
1821
+ url: this.url
1822
+ })
1823
+ );
1824
+ }
1825
+ setScript(url, script) {
1826
+ this.scripts.set(url, script instanceof Script ? script : new Script(script));
1827
+ }
1828
+ setStyle(url, style) {
1829
+ this.styles.set(url, style);
1830
+ }
1831
+ };
1832
+
1833
+ // src/cache/app-cache.ts
1834
+ var AppCache = class {
1835
+ // todo 主应用共享资源包
1836
+ baseSource;
1837
+ cache;
1838
+ constructor() {
1839
+ this.cache = /* @__PURE__ */ new Map();
1840
+ this.baseSource = new EntrySource(location.href);
1841
+ }
1842
+ // 删除缓存
1843
+ deleteApp(url) {
1844
+ this.cache.delete(url);
1845
+ }
1846
+ // 获取缓存app
1847
+ getApp(name) {
1848
+ if (!name) return void 0;
1849
+ const app = this.cache.get(name);
1850
+ if (app) return app;
1851
+ return Array.from(this.cache.values()).find((item) => item.name === name);
1852
+ }
1853
+ // 获取缓存app
1854
+ getBaseAppStyle(urlOrCode) {
1855
+ return this.baseSource.getStyle(urlOrCode);
1856
+ }
1857
+ getCacheHtml(url) {
1858
+ const list = Array.from(this.cache.values());
1859
+ const app = list.find((item) => item.url === url);
1860
+ if (app) return app.source?.rawHtml || "";
1861
+ return "";
1862
+ }
1863
+ getCacheScript(url) {
1864
+ let script = this.baseSource.getScript(url);
1865
+ if (script) return;
1866
+ const list = Array.from(this.cache.values());
1867
+ list.some((app) => {
1868
+ script = app.source?.getScript(url);
1869
+ return !!script;
1870
+ });
1871
+ return script;
1872
+ }
1873
+ getCacheStyle(url) {
1874
+ let style = this.baseSource.getStyle(url);
1875
+ if (style) return;
1876
+ const list = Array.from(this.cache.values());
1877
+ list.some((app) => {
1878
+ style = app.source?.getStyle(url);
1879
+ return !!style;
1880
+ });
1881
+ return style;
1882
+ }
1883
+ setApp(app) {
1884
+ this.cache.set(app.appCacheKey, app);
1885
+ }
1886
+ setBaseAppScript(url, script) {
1887
+ this.baseSource.setScript(url, script);
1888
+ }
1889
+ setBaseAppStyle(url, style) {
1890
+ this.baseSource.setStyle(url, style);
1891
+ }
1892
+ get hasActiveApp() {
1893
+ return Array.from(this.cache.values()).some((app) => app.status !== "UNMOUNT" /* UNMOUNT */);
1894
+ }
1895
+ };
1896
+ var appCache = new AppCache();
1897
+ window.__getAppOrInstance__ = (id) => {
1898
+ if (!id) return appCache;
1899
+ return appCache.getApp(id);
1900
+ };
1901
+
1902
+ // src/base-app/element.ts
1903
+ function getStyleSource(url, style, originLink) {
1904
+ const replaceStyle = document.createElement("style");
1905
+ setMarkElement(replaceStyle);
1906
+ fetchSource(url).then((data) => {
1907
+ style.code = data;
1908
+ appCache.setBaseAppStyle(url, style);
1909
+ replaceStyle.textContent = data;
1910
+ dispatchLinkOrScriptLoad(originLink);
1911
+ }).catch((err) => {
1912
+ console.error(err);
1913
+ dispatchLinkOrScriptError(originLink);
1914
+ });
1915
+ return replaceStyle;
1916
+ }
1917
+ function getScriptSource(url, script, originScript) {
1918
+ const replaceScript = document.createElement("script");
1919
+ setMarkElement(replaceScript);
1920
+ fetchSource(url).then((code) => {
1921
+ script.setCode(code);
1922
+ try {
1923
+ replaceScript.textContent = code;
1924
+ if (!url.startsWith("inline-")) {
1925
+ originScript.setAttribute("origin-src", url);
1926
+ }
1927
+ } catch (e) {
1928
+ console.error(e, url);
1929
+ }
1930
+ dispatchLinkOrScriptLoad(originScript);
1931
+ }).catch((err) => {
1932
+ console.error(err);
1933
+ dispatchLinkOrScriptError(originScript);
1934
+ });
1935
+ return replaceScript;
1936
+ }
1937
+ function createNewNode(child) {
1938
+ if (child instanceof HTMLLinkElement) {
1939
+ const rel = child.getAttribute("rel");
1940
+ let href = child.getAttribute("href");
1941
+ if (rel === "stylesheet" && href) {
1942
+ href = fillUpPath(href, location.origin);
1943
+ const replaceStyle = document.createElement("style");
1944
+ const styleInstance = new Style({
1945
+ code: "",
1946
+ fromHtml: false,
1947
+ url: href
1948
+ });
1949
+ getStyleSource(href, styleInstance, child);
1950
+ return replaceStyle;
1951
+ }
1952
+ }
1953
+ if (child instanceof HTMLScriptElement) {
1954
+ let src = child.getAttribute("src");
1955
+ if (src && child.type !== "module") {
1956
+ src = fillUpPath(src, location.origin);
1957
+ const script = new Script({
1958
+ async: child.hasAttribute("async"),
1959
+ code: "",
1960
+ defer: child.defer || child.type === "module",
1961
+ fromHtml: false,
1962
+ isModule: false
1963
+ });
1964
+ appCache.setBaseAppScript(src, script);
1965
+ const replaceElement = getScriptSource(src, script, child);
1966
+ return replaceElement || child;
1967
+ }
1968
+ }
1969
+ return child;
1970
+ }
1971
+ function isLinkOrScript(node) {
1972
+ return node instanceof HTMLLinkElement || node instanceof HTMLScriptElement;
1973
+ }
1974
+ function baseElementInertHandle(parent, newChild, passiveChild, rawMethod) {
1975
+ if (isLinkOrScript(newChild)) {
1976
+ const targetChild = createNewNode(newChild);
1977
+ return rawMethod.call(parent, targetChild, passiveChild);
1978
+ }
1979
+ return rawMethod.call(parent, newChild, passiveChild);
1980
+ }
1981
+ function baseElementAppendHandle(parent, newChild, rawMethod) {
1982
+ if (isLinkOrScript(newChild)) {
1983
+ const targetChild = createNewNode(newChild);
1984
+ return rawMethod.call(parent, targetChild);
1985
+ }
1986
+ return rawMethod.call(parent, newChild);
1987
+ }
1988
+
1989
+ // src/base-app/collect-source.ts
1990
+ function collectBaseSource() {
1991
+ const rawBodyAppendChild = HTMLBodyElement.prototype.appendChild;
1992
+ const rawHeadAppendChild = HTMLHeadElement.prototype.appendChild;
1993
+ const rawHeadInsertBefore = HTMLHeadElement.prototype.appendChild;
1994
+ HTMLBodyElement.prototype.appendChild = function(newChild) {
1995
+ return baseElementAppendHandle(this, newChild, rawBodyAppendChild);
1996
+ };
1997
+ HTMLHeadElement.prototype.appendChild = function(newChild) {
1998
+ return baseElementAppendHandle(this, newChild, rawHeadAppendChild);
1999
+ };
2000
+ HTMLHeadElement.prototype.insertBefore = function(newChild, refChild) {
2001
+ return baseElementInertHandle(this, newChild, refChild, rawHeadInsertBefore);
2002
+ };
2003
+ window.addEventListener("load", () => {
2004
+ const nodeList = document.head.querySelectorAll("style");
2005
+ for (const node of Array.from(nodeList)) {
2006
+ node.textContent && appCache.setBaseAppStyle(
2007
+ randomUrl(),
2008
+ new Style({
2009
+ code: node.textContent,
2010
+ fromHtml: false,
2011
+ url: ""
2012
+ })
2013
+ );
2014
+ }
2015
+ });
2016
+ }
2017
+
2018
+ // src/context/element.ts
2019
+ var { setAttribute } = Element.prototype;
2020
+ var {
2021
+ append,
2022
+ appendChild: bodyAppendChild2,
2023
+ insertBefore: bodyInsertBefore,
2024
+ removeChild: bodyRemoveChild
2025
+ } = HTMLBodyElement.prototype;
2026
+ var {
2027
+ appendChild: headAppendChild,
2028
+ insertBefore: headInsertBefore,
2029
+ removeChild: headRemoveChild
2030
+ } = HTMLHeadElement.prototype;
2031
+ var rawHead = document.head;
2032
+ var hasRewrite = false;
2033
+ function rewriteBodyAndHeaderMethods() {
2034
+ if (hasRewrite) return;
2035
+ hasRewrite = true;
2036
+ Element.prototype.setAttribute = function(key, value) {
2037
+ const tagName = this.tagName.toLocaleUpperCase();
2038
+ if ((["src", "srcset"].includes(key) && ["IMG", "SCRIPT"].includes(tagName) || key === "href" && ["LINK"].includes(tagName)) && this.__BK_WEWEB_APP_KEY__ && appCache.getApp(this.__BK_WEWEB_APP_KEY__ || "")) {
2039
+ setAttribute.call(this, key, fillUpPath(value, appCache.getApp(this.__BK_WEWEB_APP_KEY__).url));
2040
+ } else {
2041
+ setAttribute.call(this, key, value);
2042
+ }
2043
+ };
2044
+ HTMLBodyElement.prototype.appendChild = function appendChildNew(newChild) {
2045
+ if (newChild.__KEEP_ALIVE__ && isSpecialElement(newChild)) return headAppendChild.call(rawHead, newChild);
2046
+ return elementAppendHandler(this, newChild, bodyAppendChild2);
2047
+ };
2048
+ HTMLBodyElement.prototype.append = function(...nodes) {
2049
+ nodes.forEach((node) => {
2050
+ if (node.__KEEP_ALIVE__ && isSpecialElement(node)) {
2051
+ return headAppendChild.call(rawHead, node);
2052
+ }
2053
+ elementAppendHandler(this, node, bodyAppendChild2);
2054
+ });
2055
+ };
2056
+ HTMLHeadElement.prototype.appendChild = HTMLBodyElement.prototype.appendChild;
2057
+ HTMLHeadElement.prototype.insertBefore = function(newChild, refChild) {
2058
+ return elementInsertHandler(this, newChild, refChild, headInsertBefore);
2059
+ };
2060
+ HTMLBodyElement.prototype.insertBefore = function(newChild, refChild) {
2061
+ return elementInsertHandler(this, newChild, refChild, headInsertBefore);
2062
+ };
2063
+ HTMLBodyElement.prototype.removeChild = function removeChildNew(oldChild) {
2064
+ const app = appCache.getApp(oldChild.__BK_WEWEB_APP_KEY__);
2065
+ if (app?.container?.contains(oldChild)) {
2066
+ const node = bodyRemoveChild.call(app.container, oldChild);
2067
+ return node;
2068
+ }
2069
+ if (this.contains(oldChild)) {
2070
+ return bodyRemoveChild.call(this, oldChild);
2071
+ }
2072
+ return oldChild;
2073
+ };
2074
+ HTMLHeadElement.prototype.removeChild = HTMLBodyElement.prototype.removeChild;
2075
+ }
2076
+ function resetBodyAndHeaderMethods() {
2077
+ setCurrentRunningApp(null);
2078
+ Element.prototype.setAttribute = setAttribute;
2079
+ HTMLBodyElement.prototype.appendChild = bodyAppendChild2;
2080
+ HTMLBodyElement.prototype.append = append;
2081
+ HTMLBodyElement.prototype.removeChild = bodyRemoveChild;
2082
+ HTMLBodyElement.prototype.insertBefore = bodyInsertBefore;
2083
+ HTMLHeadElement.prototype.appendChild = headAppendChild;
2084
+ HTMLHeadElement.prototype.insertBefore = headInsertBefore;
2085
+ HTMLHeadElement.prototype.removeChild = headRemoveChild;
2086
+ hasRewrite = false;
2087
+ }
2088
+
2089
+ // src/lifecircle/before-load.ts
2090
+ function beforeLoad() {
2091
+ rewriteBodyAndHeaderMethods();
2092
+ }
2093
+
2094
+ // src/lifecircle/activated.ts
2095
+ function activated(appKey, container, callback) {
2096
+ const app = appCache.getApp(appKey);
2097
+ if (app?.status === "DEACTIVATED" /* DEACTIVATED */ && app.keepAlive) {
2098
+ nextTask(() => {
2099
+ beforeLoad();
2100
+ app.activated(container, callback);
2101
+ });
2102
+ } else {
2103
+ app && nextTask(() => {
2104
+ beforeLoad();
2105
+ app.mount(container, callback);
2106
+ });
2107
+ }
2108
+ }
2109
+
2110
+ // src/lifecircle/deactivated.ts
2111
+ function deactivated(appKey) {
2112
+ const app = appCache.getApp(appKey);
2113
+ if (app && ["ACTIVATED" /* ACTIVATED */, "MOUNTED" /* MOUNTED */].includes(app.status)) {
2114
+ app.keepAlive ? app.deactivated() : app.unmount();
2115
+ }
2116
+ if (!appCache.hasActiveApp) {
2117
+ resetBodyAndHeaderMethods();
2118
+ }
2119
+ }
2120
+
2121
+ // src/lifecircle/load.ts
2122
+ async function load(props) {
2123
+ beforeLoad();
2124
+ if (props.mode === "js" /* INSTANCE */) return await loadInstance(props);
2125
+ return await loadApp(props);
2126
+ }
2127
+ async function loadApp(props) {
2128
+ beforeLoad();
2129
+ let instance = appCache.getApp(props.id);
2130
+ if (!instance) {
2131
+ instance = new MicroAppModel(props);
2132
+ appCache.setApp(instance);
2133
+ }
2134
+ await instance.start();
2135
+ return instance;
2136
+ }
2137
+ function loadInstance(props) {
2138
+ beforeLoad();
2139
+ return new Promise((resolve) => {
2140
+ let instance = appCache.getApp(props.id);
2141
+ if (!instance) {
2142
+ instance = new MicroInstanceModel(props);
2143
+ appCache.setApp(instance);
2144
+ instance.start().then(() => resolve(instance));
2145
+ } else if (["MOUNTING" /* MOUNTING */, "UNSET" /* UNSET */].includes(instance.status)) {
2146
+ const timer = setInterval(() => {
2147
+ if (["ERROR" /* ERROR */, "MOUNTED" /* MOUNTED */].includes(instance.status)) {
2148
+ resolve(instance);
2149
+ clearInterval(timer);
2150
+ }
2151
+ }, 300);
2152
+ } else {
2153
+ resolve(instance);
2154
+ }
2155
+ });
2156
+ }
2157
+
2158
+ // src/lifecircle/unmount.ts
2159
+ function unmount(appKey) {
2160
+ const app = appCache.getApp(appKey);
2161
+ if (app && app.status !== "UNMOUNT" /* UNMOUNT */) {
2162
+ app.unmount();
2163
+ }
2164
+ if (!appCache.hasActiveApp) {
2165
+ resetBodyAndHeaderMethods();
2166
+ }
2167
+ }
2168
+
2169
+ // src/component/web-compnent.ts
2170
+ var BkWewebElement = class extends HTMLElement {
2171
+ appUrl = "";
2172
+ connected = false;
2173
+ static get observedAttributes() {
2174
+ return ["url" /* url */];
2175
+ }
2176
+ getBooleanAttr(name) {
2177
+ return this.hasAttribute(name) || this.hasAttribute(name.replace(/([A-Z])/g, "-$1").toLocaleLowerCase()) ? this.getAttribute(name) !== "false" : void 0;
2178
+ }
2179
+ async handleAttributeChanged() {
2180
+ if (!this.appKey) return;
2181
+ if (this.getBooleanAttr("setShodowDom" /* setShodowDom */)) {
2182
+ this.attachShadow({ mode: "open" });
2183
+ }
2184
+ const app = appCache.getApp(this.appKey);
2185
+ if (app && app.url === this.appUrl && (app.isPreLoad || app.status === "UNMOUNT" /* UNMOUNT */)) {
2186
+ activated(this.appKey, this.shadowRoot ?? this);
2187
+ return;
2188
+ }
2189
+ await load(this.appProps);
2190
+ }
2191
+ attributeChangedCallback(attr, _oldVal, newVal) {
2192
+ if (attr !== "url" /* url */ || this[attr] === newVal || !this.connected) return;
2193
+ this.appUrl = newVal;
2194
+ const cacheApp = appCache.getApp(this.appKey);
2195
+ (this.connected || cacheApp) && this.handleAttributeChanged();
2196
+ }
2197
+ async connectedCallback() {
2198
+ if (this.getBooleanAttr("setShodowDom" /* setShodowDom */) && !this.shadowRoot) {
2199
+ this.attachShadow({ delegatesFocus: false, mode: "open" });
2200
+ }
2201
+ await load(this.appProps);
2202
+ activated(this.appKey, this.shadowRoot ?? this);
2203
+ this.connected = true;
2204
+ }
2205
+ disconnectedCallback() {
2206
+ this.connected = false;
2207
+ if (this.appProps.keepAlive) {
2208
+ deactivated(this.appKey);
2209
+ } else unmount(this.appKey);
2210
+ }
2211
+ get appData() {
2212
+ if (this.hasAttribute("data" /* data */)) {
2213
+ try {
2214
+ return JSON.parse(this.getAttribute("data" /* data */));
2215
+ } catch {
2216
+ }
2217
+ }
2218
+ return {};
2219
+ }
2220
+ // 考虑到js模式下 需要js bundle的复用性 需用户设置id属性 如果单实例下则可以不用配置
2221
+ get appKey() {
2222
+ return this.getAttribute("id" /* id */) || this.getAttribute("url" /* url */);
2223
+ }
2224
+ get appProps() {
2225
+ if (this.getAttribute("mode") === "js" /* INSTANCE */) {
2226
+ return {
2227
+ container: this.shadowRoot ?? this,
2228
+ data: this.appData,
2229
+ id: this.appKey,
2230
+ keepAlive: this.getBooleanAttr("keepAlive" /* keepAlive */),
2231
+ mode: "js" /* INSTANCE */,
2232
+ scopeCss: this.getBooleanAttr("scopeCss" /* scopeCss */) && !this.getBooleanAttr("setShodowDom" /* setShodowDom */),
2233
+ scopeJs: this.getBooleanAttr("scopeJs" /* scopeJs */),
2234
+ showSourceCode: this.getBooleanAttr("showSourceCode" /* showSourceCode */),
2235
+ url: this.getAttribute("url" /* url */)
2236
+ };
2237
+ }
2238
+ return {
2239
+ container: this.shadowRoot ?? this,
2240
+ data: this.appData,
2241
+ id: this.appKey,
2242
+ keepAlive: this.getBooleanAttr("keepAlive" /* keepAlive */),
2243
+ mode: "app" /* APP */,
2244
+ scopeCss: !this.getBooleanAttr("setShodowDom" /* setShodowDom */),
2245
+ scopeJs: !this.getBooleanAttr("scopeJs" /* scopeJs */),
2246
+ scopeLocation: this.getBooleanAttr("scopeLocation" /* scopeLocation */),
2247
+ showSourceCode: this.getBooleanAttr("showSourceCode" /* showSourceCode */),
2248
+ url: this.getAttribute("url" /* url */)
2249
+ };
2250
+ }
2251
+ };
2252
+
2253
+ // src/lifecircle/mount.ts
2254
+ function mount(appKey, container, callback) {
2255
+ const app = appCache.getApp(appKey);
2256
+ app && nextTask(() => {
2257
+ beforeLoad();
2258
+ app.mount(container, callback);
2259
+ });
2260
+ }
2261
+
2262
+ // src/lifecircle/unload.ts
2263
+ function unload(url) {
2264
+ appCache.deleteApp(url);
2265
+ }
2266
+
2267
+ // src/preload/preload.ts
2268
+ function preLoadInstance(options) {
2269
+ requestIdleCallback(
2270
+ () => loadInstance({
2271
+ ...options,
2272
+ isPreLoad: true
2273
+ })
2274
+ );
2275
+ }
2276
+ function preLoadApp(options) {
2277
+ requestIdleCallback(
2278
+ () => loadApp({
2279
+ ...options,
2280
+ isPreLoad: true
2281
+ })
2282
+ );
2283
+ }
2284
+ function preLoadSource(sourceList) {
2285
+ requestIdleCallback(() => {
2286
+ loadGlobalSource(sourceList);
2287
+ });
2288
+ }
2289
+
2290
+ // src/index.ts
2291
+ var CUSTOM_ELEMENT_TAG = "bk-weweb";
2292
+ var WeWeb = class {
2293
+ fetchSource;
2294
+ webcomponentTag = CUSTOM_ELEMENT_TAG;
2295
+ constructor() {
2296
+ if (!window.customElements.get(CUSTOM_ELEMENT_TAG)) {
2297
+ window.customElements.define(CUSTOM_ELEMENT_TAG, BkWewebElement);
2298
+ }
2299
+ }
2300
+ // 设置自定义dom标签名
2301
+ setWebComponentTag() {
2302
+ if (!window.customElements.get(this.webcomponentTag)) {
2303
+ window.customElements.define(this.webcomponentTag, BkWewebElement);
2304
+ }
2305
+ }
2306
+ // todo set some global start props
2307
+ start(option) {
2308
+ if (option?.collectBaseSource) {
2309
+ collectBaseSource();
2310
+ }
2311
+ if (typeof option?.fetchSource === "function") {
2312
+ this.fetchSource = option.fetchSource;
2313
+ }
2314
+ this.webcomponentTag = option?.webcomponentTag || CUSTOM_ELEMENT_TAG;
2315
+ this.setWebComponentTag();
2316
+ }
2317
+ };
2318
+ var weWeb = new WeWeb();
2319
+ var src_default = weWeb;
2320
+ export {
2321
+ WeWeb,
2322
+ WewebMode,
2323
+ activated,
2324
+ deactivated,
2325
+ src_default as default,
2326
+ load,
2327
+ loadApp,
2328
+ loadInstance,
2329
+ mount,
2330
+ preLoadApp,
2331
+ preLoadInstance,
2332
+ preLoadSource,
2333
+ unload,
2334
+ unmount
2335
+ };
30
2336
  //# sourceMappingURL=index.esm.js.map