@blueking/bk-weweb 0.0.2 → 0.0.3

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.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).bkIframe={})}(this,(function(e){"use strict";let t=null;function n(){return t}function o(e){t=e}const s=new Map,i=new Map,r="noModule"in document.createElement("script"),c=document.createElement("style");c.setAttribute("id","SCOPED_CSS_STYLE_ID"),document.body.appendChild(c),c.sheet.disabled=!0;const a=c;var l;function h(e){return"function"==typeof e}!function(e){e.UNSET="UNSET",e.LOADING="LOADING",e.LOADED="LOADED",e.ERROR="ERROR",e.MOUNTING="MOUNTING",e.MOUNTED="MOUNTED",e.ACTIVATED="ACTIVATED",e.DEACTIVATED="DEACTIVATED",e.UNMOUNT="UNMOUNT"}(l||(l={}));const u="function"==typeof window.Zone?setTimeout:e=>Promise.resolve().then(e);function p(e){return e.startsWith("//")?`${location.protocol}${e}`:e}function d(e,t){return!e||/^((((ht|f)tps?)|file):)?\/\//.test(e)||/^(data|blob):/.test(e)?e:new URL(e,function(e){const{origin:t,pathname:n}=new URL(e);if(/\.(\w+)$/.test(n)){const e=`${t}${n}`.split("/");return e.pop(),`${e.join("/")}/`}return`${t}${n}/`.replace(/\/\/$/,"/")}(p(t))).toString()}const m="undefined"!=typeof navigator&&-1!==navigator.userAgent.indexOf("Trident");function f(){return`inline-${A(16)}`}const y=window.requestIdleCallback||function(e){const t=Date.now();return setTimeout((()=>{e({didTimeout:!1,handle:()=>Math.max(0,50-(Date.now()-t))})}),1)};function w(e,t){const n=document.createElement(e,t);return n.__BK_WEWEB_APP_KEY__&&delete n.__BK_WEWEB_APP_KEY__,n}function E(e){return/^(body|head|html)$/i.test(e)}const A=(e,t="abcdefghijklmnopqrstuvwxyz0123456789")=>{let n="";for(let o=0;o<e;o++)n+=t[parseInt((Math.random()*t.length).toString(),10)];return n};function _(e,t={}){return Be.fetchSource?Be.fetchSource(e,t):window.fetch(e,t).then((e=>e.text()))}const S="id";var g;!function(e){e[e.STYLE_RULE=1]="STYLE_RULE",e[e.MEDIA_RULE=4]="MEDIA_RULE",e[e.SUPPORTS_RULE=12]="SUPPORTS_RULE"}(g||(g={}));const b=["System","__cjsWrapper","__REACT_ERROR_OVERLAY_GLOBAL_HOOK__"],C=["location"],v=["webpackJsonp","__POWERED_BY_BK_WEWEB__","__BK_WEWEB_APP_KEY__","__BK_WEWEB_DATA__"],L=["location","history"];var T;!function(e){e.TARGET="TARGET",e.WINDOW="WINDOW"}(T||(T={}));const P={undefined:!0,Array:!0,Object:!0,String:!0,Boolean:!0,Math:!0,Reflect:!0,Function:!0,Number:!0,Symbol:!0,parseFloat:!0,parseInt:!0,Float32Array:!0,Set:!0,Infinity:!0,navigator:!0,devicePixelRatio:!0,Promise:!0,HTMLElement:!0,Map:!0,Element:!0,performance:!0,console:!0,isFinite:!0,RegExp:!0,JSON:!0,Date:!0,Proxy:!0,isNaN:!0,WeakMap:!0,WeakSet:!0,Uint8Array:!0},R={__VUE_OPTIONS_API__:!0,__VUE_I18N_LEGACY_API__:!0,__VUE_I18N_FULL_INSTALL__:!0,__VUE_DEVTOOLS_GLOBAL_HOOK__:!0,__VUE_DEVTOOLS_HOOK_REPLAY__:!0,__VUE_DEVTOOLS_PLUGINS__:!0,__DEV__:!0,webpackChunktrace:!0,i18n:!0,"__core-js_shared__":!0},B=new WeakMap;const x=new WeakMap;function M(e,t){if(x.has(t))return x.get(t);if(h(t)&&!function(e){if(B.has(e))return B.get(e);const t=e.toString(),n=e.prototype&&e.prototype.constructor===e&&Object.getOwnPropertyNames(e.prototype).length>1||/^function\s+[A-Z]/.test(t)||/^class\s+/.test(t);return B.set(e,n),n}(t)){const n=t.bind(e);return Object.keys(t).forEach((e=>n[e]=t[e])),t.hasOwnProperty("prototype")&&!n.hasOwnProperty("prototype")&&(n.prototype=t.prototype),x.set(t,n),n}return t}class O{app;resetWindowFunction;resetDocumentAndBodyEvent;injectedKeySet=new Set;escapedKeySet=new Set;active=!1;rawWindow;rawDocument;proxyWindow;fakeWindow={};windowSymbolKey;constructor(e){this.app=e;const t=new Map,o=window,r=window.document;this.fakeWindow.__POWERED_BY_BK_WEWEB__=!0,this.fakeWindow.__BK_WEWEB_APP_KEY__=e.appCacheKey,this.rawWindow=o,this.rawDocument=r,this.fakeWindow.rawWindow=o,this.fakeWindow.rawDocument=r;const{resetWindowFunction:c}=function(e){const t=n(),o=new Map,r=new Map,c=new Map,a=window,l=window.document,{addEventListener:h,removeEventListener:u,setInterval:p,setTimeout:d,clearInterval:m,clearTimeout:f}=window,{removeEventListener:y}=window.document;return e.addEventListener=function(e,t,n){const s=o.get(e);s?s.add(t):o.set(e,new Set([t])),h.call(a,e,t,n)},e.removeEventListener=function(e,t,n){const s=o.get(e);s?.size&&s.has(t)&&s.delete(t),u.call(a,e,t,n)},e.setInterval=function(e,t,...n){const o=p.call(a,e,t,...n);return r.set(o,{handler:e,timeout:t,args:n}),o},e.setTimeout=function(e,t,...n){const o=d.call(a,e,t,...n);return c.set(o,{handler:e,timeout:t,args:n}),o},e.clearInterval=function(e){r.delete(e),m.call(a,e)},e.clearTimeout=function(e){c.delete(e),f.call(a,e)},{resetWindowFunction:()=>{if(o.size&&(o.forEach(((e,t)=>{for(const n of e)u.call(a,t,n)})),o.clear()),r.size&&(r.forEach(((e,t)=>{m.call(a,t)})),r.clear()),c.size&&(c.forEach(((e,t)=>{f.call(a,t)})),c.clear()),t){s.delete(t.appCacheKey);const e=i.get(t.appCacheKey);e&&(e.forEach(((e,t)=>{for(const n of e)y.call(l,t,n)})),e.clear())}}}}(this.fakeWindow);this.resetWindowFunction=c,this.windowSymbolKey=`__${(e.name||e.appCacheKey).replace(/(-|,|:|~|'|")/gim,"_")}_${A(10)}__`,this.proxyWindow=new Proxy(this.fakeWindow,{get:(t,n)=>{if(P[n]||n===Symbol.unscopables)return o[n];if(R[n])return this.fakeWindow[n];if(["window","self","globalThis"].includes(n))return this.proxyWindow;if("document"===n||"eval"===n)return e.registerRunningApp(),"document"===n?r:eval;if(L.includes(n)&&this.app instanceof z&&this.app.iframe&&this.app.scopeLocation)return this.app.iframe.contentWindow?.[n];if("hasOwnProperty"===n)return e=>this.fakeWindow.hasOwnProperty(e)||o.hasOwnProperty(e);if("top"===n||"parent"===n)return o===o.parent?this.proxyWindow:Reflect.get(o,n);if(Reflect.has(t,n)||v.includes(n))return Reflect.get(t,n);const s=Reflect.get(o,n);return M(o,s)},set:(e,t,n)=>{if(this.active){if(L.includes(t)&&this.app instanceof z&&this.app.iframe&&this.app.scopeLocation)return Reflect.set(this.app.iframe.contentWindow,t,n);if(C.includes(t))Reflect.set(o,t,n);else if(e.hasOwnProperty(t)||!o.hasOwnProperty(t)||v.includes(t))Reflect.set(e,t,n),this.injectedKeySet.add(t);else{const s=Object.getOwnPropertyDescriptor(o,t),{writable:i,configurable:r,enumerable:c}=s;i&&(Object.defineProperty(e,t,{configurable:r,enumerable:c,writable:i,value:n}),this.injectedKeySet.add(t))}!b.includes(t)||Reflect.has(o,t)||v.includes(t)||(Reflect.set(o,t,n),this.escapedKeySet.add(t))}return!0},has:(e,t)=>P[t]||t in e||t in o,getOwnPropertyDescriptor:(e,n)=>{if(e.hasOwnProperty(n))return Object.getOwnPropertyDescriptor(e,n);if(o.hasOwnProperty(n)){t.set(n,T.WINDOW);const e=Object.getOwnPropertyDescriptor(o,n);return e&&!e.configurable&&(e.configurable=!0),e}},defineProperty:(e,n,s)=>t.get(n)===T.WINDOW?Reflect.defineProperty(o,n,s):Reflect.defineProperty(e,n,s),ownKeys:e=>{return t=Reflect.ownKeys(o).concat(Reflect.ownKeys(e)),Array.from(new Set(t));var t},deleteProperty:(e,t)=>!e.hasOwnProperty(t)||(this.injectedKeySet.has(t)&&this.injectedKeySet.delete(t),this.escapedKeySet.has(t)&&Reflect.deleteProperty(o,t),Reflect.deleteProperty(e,t))}),e.showSourceCode&&(o[this.windowSymbolKey]=this.proxyWindow)}activeated(e){if(!this.active){this.active=!0,this.fakeWindow.__BK_WEWEB_DATA__=e??{};const{resetDocumentAndBodyEvent:t}=function(){const{addEventListener:e,removeEventListener:t}=window.document,{addEventListener:o,removeEventListener:s}=window.document.body;return document.addEventListener=function(t,o,s){const r=n();if(r){const e=i.get(r.appCacheKey);if(e){const n=e.get(t);n?n.add(o):e.set(t,new Set([o]))}else i.set(r.appCacheKey,new Map([[t,new Set([o])]]))}e.call(r?.container instanceof ShadowRoot?r.container:this,t,o,s)},document.body.addEventListener=document.addEventListener,document.removeEventListener=function(e,o,s){const r=n();if(r){const t=i.get(r.appCacheKey);if(t){const n=t.get(e);n?.size&&n.has(o)&&n.delete(o)}}t.call(r?.container instanceof ShadowRoot?r.container:this,e,o,s)},document.body.removeEventListener=document.removeEventListener,{resetDocumentAndBodyEvent:function(){document.addEventListener=e,document.body.addEventListener=o,document.removeEventListener=t,document.body.removeEventListener=s}}}();this.resetDocumentAndBodyEvent=t}}deactivated(){this.active&&(this.active=!1,this.resetWindowFunction(),this.injectedKeySet.clear(),this.escapedKeySet.forEach((e=>Reflect.deleteProperty(window,e))),this.escapedKeySet.clear(),this.resetDocumentAndBodyEvent?.())}}function D(e,t){Object.defineProperties(e,{currentTarget:{get:()=>t},srcElement:{get:()=>t},target:{get:()=>t}})}function W(e){const t=new CustomEvent("load");D(t,e),h(e.onload)?e.onload(t):e.dispatchEvent(t)}const{appendChild:K}=HTMLBodyElement.prototype;function k(e,t,n){if(t instanceof HTMLStyleElement){if(t.hasAttribute("exclude"))return document.createComment("【bk-weweb】style with exclude attribute is ignored");if(!t.hasAttribute("ignore")){const e=new I({code:t.textContent||"",url:"",fromHtml:!1});n.source?.setStyle(f(),e),e.scopedStyleCSS(n,t)}return t}if(t instanceof HTMLLinkElement){const o=n.source?.collectLink(t,e,!0);return o?(o.style&&o.style.scopedLinkCSS(n,t),o.replace!==t?o.replace:t):t}if(t instanceof HTMLScriptElement){const o=n.source.collectScript(t,e,!0);if(!o)return t;if(o.script&&o.script.excuteCode(n),o.replace!==t)return o.replace;if(n.scopeJs&&!t.getAttribute("src")&&!t.textContent){const o=new MutationObserver((()=>{if(t.getAttribute("src")){o.disconnect();const s=n.source.collectScript(t,e,!0);s?.replace&&K.call(n.container,s.replace),s?.script&&s.script.excuteCode(n),t.remove()}else if(t.textContent){o.disconnect();const e=new F({code:t.textContent,async:!1,defer:"module"===t.type,isModule:"module"===t.type,fromHtml:!1});n.source.scripts.set(f(),e);try{e.excuteCode(n)}catch(e){console.error(e)}finally{!e.isModule&&W(t),t.remove()}}}));return o.observe(t,{attributeFilter:["src"],childList:!0,subtree:!1}),document.createComment("【bk-weweb】dynamic script or module")}return t}return t}function H(e){return e instanceof HTMLScriptElement||e instanceof HTMLStyleElement||e instanceof HTMLLinkElement}function U(e,t,n){if(t.__BK_WEWEB_APP_KEY__){const o=X.getApp(t.__BK_WEWEB_APP_KEY__);if(o?.container){const s=k(e,t,o),i=H(t)&&!!o.keepAlive&&!(o.container instanceof ShadowRoot),r=i?document.head:o?.container;return N(s,o,i),n.call(r,s)}}return n.call(e,t)}function N(e,t,n){return n&&(e.__KEEP_ALIVE__=t.appCacheKey,e.setAttribute("data-from",t.name),e.setAttribute("data-keep-alive","true")),e.setAttribute?.("powered-by","bk-weweb"),e}class I{scopedCode="";code="";prefetch=!1;preload=!1;url;scoped;fromHtml;initial;constructor({code:e,prefetch:t,preload:n,url:o,fromHtml:s,initial:i}){this.scoped=!1,this.code=e,this.prefetch=t??!1,this.preload=n??!1,this.url=o,this.fromHtml=s,this.initial=i??!1}async getCode(e){if(this.code.length||!this.url)return this.code;let t="";if(e?.source?.styles?.has(this.url)&&(t=e.source.styles.get(this.url)?.code||""),!t&&X.getCacheStyle(this.url)){t=X.getCacheStyle(this.url)?.code||""}return t||(t=await _(this.url).catch((()=>""))),this.code=t,t}async excuteCode(e){e.registerRunningApp();let t=w("style");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(e){console.error("scoped style error",e)}return t}scopedStyleCSS(e,t){const n=!(!e.keepAlive||e.container instanceof ShadowRoot);if(N(t,e,n),this.code||t.textContent)t.textContent&&(t.textContent="",t.innerHTML=""),a.textContent=this.code,this.commonScoped(a,t,e),a.textContent="";else{const n=new MutationObserver((()=>{(t.textContent||t.sheet?.cssRules?.length)&&(n.disconnect(),this.commonScoped(t,t,e))}));n.observe(t,{attributes:!1,childList:!0,subtree:!0,characterData:!0})}return this.url&&t.setAttribute("origin-src",this.url),t}scopedLinkCSS(e,t){const n=w("style");n.setAttribute("type","text/css");const o=!(!e.keepAlive||e.container instanceof ShadowRoot);N(n,e,o);const s=o?document.head:e.container;try{if(this.code)a.textContent=n.textContent||this.code,this.commonScoped(a,n,e),s?.prepend(n),t&&W(t),a.textContent="";else if(t.getAttribute("href"))this.url=d(t.getAttribute("href"),e.url),this.getCode(e).then((()=>{this.scopedStyleCSS(e,n),t.remove(),s?.prepend(n),t&&W(t),this.scoped=!0}));else{const o=new MutationObserver((()=>{t.href&&(o.disconnect(),this.url=d(t.getAttribute("href"),e.url),this.getCode(e).then((()=>{this.scopedStyleCSS(e,n),t.remove(),s?.prepend(n),t&&W(t),this.scoped=!0})))}));o.observe(t,{attributeFilter:["href"],subtree:!1,childList:!1})}}catch{t&&function(e){const t=new CustomEvent("error");D(t,e),h(e.onerror)?e.onerror(t):e.dispatchEvent(t)}(t)}return n}commonScoped(e,t,n){if(!n.scopeCss||n.container instanceof ShadowRoot){const o=this.resetUrlHost(t.textContent||e.textContent||"",n.url,this.url);t.textContent=o}else{const o=Array.from(e.sheet?.cssRules??[]),s=`#${n.name}`,i=this.scopeRule(o,s);let r=this.resetUrlHost(i,n.url,this.url);/Safari/.test(navigator.userAgent)&&(r=r.replace(/([;{]\s*content:\s*)([^\s"][^";}]*)/gm,((e,t,n)=>"none"===n||/^(url\()|(counter\()|(attr\()|(open-quote)|(close-quote)/.test(n)?e:`${t}"${n}"`))),t.textContent=r,this.scopedCode=r}this.scoped=!0}scopeRule(e,t){let n="";for(const o of e)switch(o.type){case g.STYLE_RULE:n+=this.scopeStyleRule(o,t);break;case g.MEDIA_RULE:n+=this.resetPackRule(o,t,"media");break;case g.SUPPORTS_RULE:n+=this.resetPackRule(o,t,"supports");break;default:n+=o.cssText}return n.replace(/^\s+/,"")}resetPackRule(e,t,n){const o=this.scopeRule(Array.from(e.cssRules),t);return`@${n} ${e.conditionText} {${o}}`}resetUrlHost(e,t,n){return e.replace(/url\(["']?([^)"']+)["']?\)/gm,((e,o)=>/^(data|blob):/.test(o)||/^(https?:)?\/\//.test(o)?e:(/^((\.\.?\/)|[^/])/.test(o)&&n&&(t=function(e){const t=e.split("/");return t.pop(),p(`${t.join("/")}/`)}(n)),`url("${d(o,t)}")`)))}scopeStyleRule(e,t){const{selectorText:n,cssText:o}=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} *`);const s=/(^|\s+)((html[\s>~]+body)|(html|body|:root))(?=[\s>~]+|$)/;return o.replace(/^[\s\S]+{/,(e=>e.replace(/(^|,)([^,]+)/g,((e,n,o)=>s.test(o)?e.replace(s,t):`${n} ${t} ${o.replace(/^\s*/,"")}`))))}}async function $(e,t){const n=Array.from(e.source.styles.values()),o=[];n.forEach((t=>{o.push(t.excuteCode(e))})),await Promise.all(o).then((n=>{const o=t||e.container;!e.keepAlive||o instanceof ShadowRoot?o?.prepend(...n):document.head.append(...n)}))}class j{state=l.UNSET;isPreLoad=!1;appCacheKey;url;container;scopeJs=!1;source;sandBox;name;showSourceCode=!0;scopeCss=!0;keepAlive;initSource;data;constructor(e){this.name=e.id!==e.url?e.id:A(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 O(this))}get status(){return this.state}set status(e){this.state=e}async start(){this.source&&![l.UNSET,l.ERROR].includes(this.status)||(this.source=new Q(this.url),await this.source.importEntery(this))}onMount(){this.isPreLoad||(this.state=l.LOADED,this.mount())}onError(){this.state=l.ERROR}mount(e,t){this.isPreLoad=!1,this.container=e??this.container,this.state=l.MOUNTING,this.container instanceof HTMLElement&&this.container.setAttribute(S,this.name),this.container.innerHTML="";const n=document.createElement("div"),o=`${this.name}-wrapper`;n.setAttribute("id",o),this.source?.styles.size&&$(this,this.container),this.container.appendChild(n),this.sandBox?.activeated(),q(this).finally((()=>{this.state=l.MOUNTED;const e=this.source?.getScript(this.url);"function"==typeof e?.exportInstance?.render&&e.exportInstance.render(n,this.data),t?.(this,e?.exportInstance)}))}activated(e,t){if(this.isPreLoad=!1,this.state=l.ACTIVATED,this.container&&e){e instanceof Element&&e.setAttribute(S,this.name);const n=document.createDocumentFragment();Array.from(this.container.childNodes).forEach((e=>{n.appendChild(e)})),e.appendChild(n),this.container=e,this.sandBox?.activeated();const o=this.source?.getScript(this.url);t?.(this,o?.exportInstance)}}deactivated(){this.state=l.DEACTIVATED,this.sandBox?.deactivated()}unmount(e){this.state=l.UNMOUNT,this.sandBox?.deactivated(),e&&X.deleteApp(this.url),this.container.innerHTML="",this.container=void 0}registerRunningApp(){o(this),Promise.resolve().then((()=>o(null)))}}let V,Y,J;class F{code="";async=!1;defer=!1;isModule=!1;url;exportInstance;scoped;fromHtml;initial;constructor({code:e,async:t,defer:n,isModule:o,url:s,fromHtml:i,initial:r}){this.code=e,this.async=t,this.defer=n,this.isModule=o,this.url=s,this.scoped=!1,this.fromHtml=i??!1,this.initial=r??!1}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&&X.getCacheScript(this.url)&&(t=X.getCacheScript(this.url)?.code||""),t||(t=await _(this.url).catch((e=>(console.error(`fetch script ${this.url} error`,e),"")))),this.code=t,t}async excuteCode(e,t=!1){try{this.code||await this.getCode(e),e instanceof j&&function(e){Y=void 0,V=Y;for(const t in e)G(e,t)||(V?Y||(Y=t):V=t,J=t)}(e.sandBox?.proxyWindow||window);let n=this.code;if(n=this.transformCode(e),e.showSourceCode||this.isModule){const o=w("script");if(e.registerRunningApp(),this.executeSourceScript(o,n),t)return o;const s=!(!e.keepAlive||e.container instanceof ShadowRoot),i=s?document.head:e.container;N(o,e,s),i.appendChild(o)}else if(this.executeMemoryScript(e,n),t)return document.createComment("【bk-weweb】dynamic script");if(e instanceof j){const t=function(e,t){let n,o,s=0;for(const i in e)if(!G(e,i)){if(0===s&&i!==V||1===s&&i!==Y)return i;n?(J=i,o=t&&o||i):n=i===J,s+=1}return o}(e.sandBox?.proxyWindow||window);t&&(this.exportInstance=(e.sandBox?.proxyWindow||window)[t])}}catch(e){console.error("execute script code error",e)}}transformCode(e){return e.sandBox?e.showSourceCode||this.isModule?`;(function(window, self){\n with(window){\n ;${this.code}\n\n }\n }).call(window.${e.sandBox.windowSymbolKey},\n window.${e.sandBox.windowSymbolKey});`:`\n with(window) {\n try {\n ${this.code}\n }\n catch(e) {\n console.error(e)\n }\n }\n `:this.code}executeSourceScript(e,t){if(this.isModule){const n=new Blob([t],{type:"text/javascript"});e.src=URL.createObjectURL(n),e.setAttribute("type","module")}else e.textContent=t;this.url&&e.setAttribute("origin-src",this.url)}executeMemoryScript(e,t){try{const n=e instanceof z&&e.scopeLocation;e.registerRunningApp(),new Function("window","location","history",t)(e.sandBox.proxyWindow,n?e.iframe?.contentWindow?.location:window.location,n?e.iframe?.contentWindow?.history:window.history)}catch(e){console.error(e)}}}function G(e,t){return!e.hasOwnProperty(t)||!isNaN(t)&&t<e.length||m&&e[t]&&"undefined"!=typeof window&&e[t].parent===window}async function q(e){const t=Array.from(e.source.scripts.values()).filter((e=>e.initial));t.length&&await Promise.all(t.map((t=>t.excuteCode(e))));const n=Array.from(e.source.scripts.values()).filter((e=>e.fromHtml&&!e.initial)),o=n.filter((e=>!e.async&&!e.defer||e.isModule));await Promise.all(o.map((t=>t.excuteCode(e))));const s=[],i=[];n.forEach((t=>{(t.defer||t.async)&&(!t.code&&t.defer?s.push(t.excuteCode(e)):i.push(t.excuteCode(e)))})),await Promise.all([...i,...s]).catch((e=>{console.error(e)}))}class z{state=l.UNSET;isPreLoad=!1;mode="app";name;url;container;showSourceCode;scopeCss;scopeJs;source;sandBox;scopeLocation;keepAlive;initSource;iframe=null;data;constructor(e){this.name=e.id!==e.url?e.id:A(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 O(this)),this.container instanceof HTMLElement&&this.container.setAttribute(S,this.name)}get appCacheKey(){return this.url}get status(){return this.state}set status(e){this.state=e}async start(){if(!this.source||[l.UNSET,l.ERROR].includes(this.status)){if(this.state=l.LOADING,this.scopeLocation){const e=await this.createIframe();this.iframe=e}this.source=new Q(this.url),await this.source.importEntery(this)}}onMount(){this.isPreLoad||(this.state=l.LOADED,this.mount())}onError(){this.state=l.ERROR}mount(e,t){if(this.isPreLoad=!1,this.container=e??this.container,this.state=l.MOUNTING,this.container){this.container instanceof Element&&this.container.setAttribute(S,this.name);const e=this.source.html.cloneNode(!0),n=document.createDocumentFragment();Array.from(e.childNodes).forEach((e=>{n.appendChild(e)})),this.container.innerHTML="",this.container.appendChild(n),this.sandBox?.activeated(this.data),q(this).finally((()=>{this.state=l.MOUNTED,t?.(this)}))}}activated(e,t){if(this.isPreLoad=!1,this.state=l.ACTIVATED,e&&this.container){e instanceof Element&&e.setAttribute(S,this.name);const n=document.createDocumentFragment();Array.from(this.container.childNodes).forEach((e=>{n.appendChild(e)})),e.innerHTML="",e.appendChild(n),this.container=e,this.sandBox?.activeated(this.data),t?.(this)}}deactivated(){this.state=l.DEACTIVATED,this.sandBox?.deactivated()}unmount(e=!1){this.state=l.UNMOUNT,this.sandBox?.deactivated(),e&&X.deleteApp(this.url),this.container.innerHTML="",this.container=void 0}createIframe(){return new Promise((e=>{const t=document.createElement("iframe"),n=new URL(this.url);t.setAttribute("src",`about:blank${n.pathname||"/"}${n.search}${n.hash}`),t.style.cssText="position: fixed; top: -9999px; width: 100%; height: 1px;",document.body.appendChild(t),setTimeout((()=>e(t)),100)}))}registerRunningApp(){o(this),Promise.resolve().then((()=>o(null)))}}async function Z(e){let t=[];if(t="function"==typeof e?await e():e||[],!t.length)return{};const n=new Map,o=new Map;return t.forEach((e=>{try{const t=new URL(e);if(t.pathname.match(/\.js$/)){const t=X.getCacheScript(e);n.set(e,new F({code:t?.code||"",async:!1,defer:!1,url:e,isModule:!1,initial:!0,fromHtml:!1}))}else if(t.pathname.match(/\.css$/)){const t=X.getCacheStyle(e);o.set(e,new I({code:t?.code||"",prefetch:!1,preload:!1,url:e,fromHtml:!0,initial:!0}))}}catch{console.error(`【bk-weweb】: ${e} is invalid URL`)}})),{collectScript:n,collectStyle:o}}class Q{url;scripts;styles;html=null;rawHtml;constructor(e){this.url=e,this.scripts=new Map,this.styles=new Map}async importEntery(e){let t;if(e.initSource?.length){const{collectScript:t,collectStyle:n}=await Z(e.initSource);t&&(this.scripts=t),n&&(this.styles=n)}e instanceof z?t=this.importHtmlEntry(e):e instanceof j&&(t=this.importInstanceEntry()),t&&await t}async importHtmlEntry(e){let t=X.getCacheHtml(this.url);if(!t&&(t=await _(this.url,{cache:"no-cache"}),!t))return console.error("load app entry error, pleace check"),Promise.reject();this.rawHtml=t;const n=w("div");n.innerHTML=t.replace(/<\/?head>/gim,"").replace(/<\/?body>/i,""),this.collectScriptAndStyle(n,e),await $(e,n),this.html=n}async importInstanceEntry(){let e=X.getCacheScript(this.url)?.code;if(e||(e=await _(this.url,{cache:"no-cache"})),!e)return console.error("load app entry error, pleace check"),Promise.reject();this.scripts.set(this.url,new F({code:e,async:!1,defer:!1,url:this.url,isModule:!1,fromHtml:!0}))}collectScriptAndStyle(e,t){const n=Array.from(e.children);n.length&&n.forEach((e=>{this.collectScriptAndStyle(e,t)}));for(const t of n)t instanceof HTMLLinkElement?this.collectLink(t,e):t instanceof HTMLStyleElement?t.hasAttribute("exclude")||t.hasAttribute("ignore")||(this.styles.set(f(),new I({code:t.textContent||"",url:"",fromHtml:!0})),t.remove()):t instanceof HTMLScriptElement?this.collectScript(t,e):t instanceof HTMLMetaElement||t instanceof HTMLTitleElement?e.removeChild(t):t instanceof HTMLImageElement&&t.hasAttribute("src")&&t.setAttribute("src",d(t.getAttribute("src"),this.url))}collectLink(e,t,n=!1){if(e.hasAttribute("exclude"))return{replace:document.createComment("【bk-weweb】style with exclude attribute is ignored")};if(e.hasAttribute("ignore"))return{replace:e};const o=e.getAttribute("rel");let s,i=e.getAttribute("href");if("stylesheet"===o&&i){i=d(i,this.url),s=document.createComment(`【bk-weweb】style with href=${i}`);let o=this.getStyle(i);return o||(o=new I({code:"",url:i,prefetch:!!e.getAttribute("prefetch"),preload:!!e.getAttribute("preload"),fromHtml:!n}),this.styles.set(i,o)),!n&&t.replaceChild(s,e),{replace:s,style:o}}return o&&["prefetch","preload","prerender","icon","apple-touch-icon"].includes(o)?(s=document.createComment(`【bk-weweb】style with rel=${o}${i?` & href=${i}`:""}`),!n&&t.removeChild(e),{replace:s}):(i&&e.setAttribute("href",d(i,this.url)),{replace:e})}collectScript(e,t,n=!1){if(e.hasAttribute("ignore")||e.hasAttribute("type")&&!["text/javascript","text/ecmascript","application/javascript","application/ecmascript","module"].includes(e.type)||!r&&"module"===e.type)return;let o=null;if(e.hasAttribute("exclude"))return o=document.createComment("【bk-weweb】script element with exclude attribute is removed"),!n&&t.replaceChild(o,e),{replace:o};let s=e.getAttribute("src");if(s){s=d(s,this.url);let i=this.getScript(s);return i||(i=new F({code:"",async:e.hasAttribute("async"),defer:e.defer||"module"===e.type,isModule:"module"===e.type,url:s,fromHtml:!n}),this.scripts.set(s,i)),o=document.createComment(`【bk-weweb】script with src='${s}'`),!n&&t.replaceChild(o,e),{replace:o,script:i}}if(e.textContent){const s=f(),i=new F({code:e.textContent,async:!1,defer:"module"===e.type,isModule:"module"===e.type,url:s,fromHtml:!n});return this.scripts.set(s,i),o=document.createComment("【bk-weweb】script with texcontent"),!n&&t.replaceChild(o,e),{replace:o,script:i}}return{replace:e}}setScript(e,t){this.scripts.set(e,new F(t))}getScript(e){return this.scripts.get(e)}setStyle(e,t){this.styles.set(e,t)}getStyle(e){return this.styles.get(e)}}const X=new class{cache;baseSource;constructor(){this.cache=new Map,this.baseSource=new Q(location.href)}get hasActiveApp(){return Array.from(this.cache.values()).some((e=>e.status!==l.UNMOUNT))}setApp(e){this.cache.set(e.appCacheKey,e)}getApp(e){if(!e)return;const t=this.cache.get(e);return t||Array.from(this.cache.values()).find((t=>t.name===e))}getCacheHtml(e){const t=Array.from(this.cache.values()).find((t=>t.url===e));return t&&t.source?.rawHtml||""}getCacheStyle(e){let t=this.baseSource.getStyle(e);if(t)return;return Array.from(this.cache.values()).some((n=>(t=n.source?.getStyle(e),!!t))),t}getCacheScript(e){let t=this.baseSource.getScript(e);if(t)return;return Array.from(this.cache.values()).some((n=>(t=n.source?.getScript(e),!!t))),t}deleteApp(e){this.cache.delete(e)}setBaseAppStyle(e,t){this.baseSource.setStyle(e,t)}setBaseAppScript(e,t){this.baseSource.setScript(e,t)}};window.__getAppOrInstance__=function(e){return e?X.getApp(e):X};const{document:ee}=window,{createElement:te,querySelector:ne,querySelectorAll:oe,getElementById:se,getElementsByClassName:ie,getElementsByTagName:re,getElementsByName:ce}=Document.prototype;function ae(){Document.prototype.createElement=te,Document.prototype.querySelector=ne,Document.prototype.querySelectorAll=oe,Document.prototype.getElementById=se,Document.prototype.getElementsByClassName=ie,Document.prototype.getElementsByTagName=re,Document.prototype.getElementsByName=ce}const{setAttribute:le}=Element.prototype,{appendChild:he,removeChild:ue,append:pe}=HTMLBodyElement.prototype,{appendChild:de,removeChild:me,insertBefore:fe}=HTMLHeadElement.prototype,ye=document.head;function we(){Element.prototype.setAttribute=function(e,t){const n=this.tagName.toLocaleUpperCase();(["src","srcset"].includes(e)&&["SCRIPT","IMG"].includes(n)||"href"===e&&["LINK"].includes(n))&&this.__BK_WEWEB_APP_KEY__&&X.getApp(this.__BK_WEWEB_APP_KEY__||"")?le.call(this,e,d(t,X.getApp(this.__BK_WEWEB_APP_KEY__).url)):le.call(this,e,t)},HTMLBodyElement.prototype.appendChild=function(e){return e.__KEEP_ALIVE__&&H(e)?de.call(ye,e):U(this,e,he)},HTMLBodyElement.prototype.append=function(...e){let t=0;const{length:n}=e;for(;t<n;){if(e[t].__KEEP_ALIVE__&&H(e[t]))return de.call(ye,e[t]);U(this,e[t],he),t+=1}},HTMLHeadElement.prototype.appendChild=HTMLBodyElement.prototype.appendChild,HTMLHeadElement.prototype.insertBefore=function(e,t){return function(e,t,n,o){if(t.__BK_WEWEB_APP_KEY__){const s=X.getApp(t.__BK_WEWEB_APP_KEY__);if(s?.container){const i=H(t)&&s.keepAlive&&!(s.container instanceof ShadowRoot),r=i?document.head:s?.container,c=k(e,t,s);return i&&(c.__KEEP_ALIVE__=s.appCacheKey,c.setAttribute("data-from",s.name),c.setAttribute("data-keep-alive","true")),n&&!r.contains(n)?K.call(r,c):o.call(r,c,n)}}return o.call(e,t,n)}(this,e,t,fe)},HTMLBodyElement.prototype.removeChild=function(e){const t=X.getApp(e.__BK_WEWEB_APP_KEY__);if(t?.container?.contains(e)){return ue.call(t.container,e)}return this.contains(e)?ue.call(this,e):e},HTMLHeadElement.prototype.removeChild=HTMLBodyElement.prototype.removeChild}function Ee(){o(null),Element.prototype.setAttribute=le,HTMLBodyElement.prototype.appendChild=he,HTMLBodyElement.prototype.append=pe,HTMLBodyElement.prototype.removeChild=ue,HTMLHeadElement.prototype.appendChild=de,HTMLHeadElement.prototype.insertBefore=fe,HTMLHeadElement.prototype.removeChild=me}function Ae(){we(),function(){function e(e){const t=n();return t&&e&&!E(e)&&ee===this?t?.container?.querySelector(e)??null:ne.call(this,e)}function t(e){const t=n();return t&&e&&!E(e)&&ee===this?t?.container?.querySelectorAll(e)??[]:oe.call(this,e)}Document.prototype.createElement=function(e,t){const o=te.call(this,e,t),s=n();return s&&(o.__BK_WEWEB_APP_KEY__=s.appCacheKey),o},Document.prototype.querySelector=e,Document.prototype.querySelectorAll=t,Document.prototype.getElementById=function(t){if(!n())return se.call(this,t);try{return e.call(this,`#${t}`)}catch{return se.call(this,t)}},Document.prototype.getElementsByClassName=function(e){if(!n())return ie.call(this,e);try{return t.call(this,`.${e}`)}catch{return ie.call(this,e)}},Document.prototype.getElementsByTagName=function(e){const o=n();if(!o||E(e)||!o?.showSourceCode&&"script"===e.toLocaleLowerCase())return re.call(this,e);try{return t.call(this,e)}catch{return re.call(this,e)}},Document.prototype.getElementsByName=function(e){if(!n())return ce.call(this,e);try{return t.call(this,`[name=${e}]`)}catch{return ce.call(this,e)}}}()}async function _e(e){return"app"===e.mode?await Se(e):"js"===e.mode?await ge(e):await Se(e)}async function Se(e){let t=X.getApp(e.id);return t||(t=new z(e),X.setApp(t)),await t.start(),t}function ge(e){return new Promise((t=>{let n=X.getApp(e.id);if(n)if([l.UNSET,l.MOUNTING].includes(n.status)){const e=setInterval((()=>{[l.ERROR,l.MOUNTED].includes(n.status)&&(t(n),clearInterval(e))}),300)}else t(n);else n=new j(e),X.setApp(n),n.start().then((()=>t(n)))}))}function be(e){const t=X.getApp(e);t?.status!==l.UNMOUNT&&t?.unmount(),X.hasActiveApp||(Ee(),ae())}function Ce(e,t,n){const o=X.getApp(e);o?.status===l.DEACTIVATED&&o.keepAlive?u((()=>o?.activated(t,n))):u((()=>o?.mount(t,n)))}function ve(e){const t=X.getApp(e);t&&[l.ACTIVATED,l.MOUNTED].includes(t.status)&&(t.keepAlive?t.deactivated():t.unmount()),X.hasActiveApp||(Ee(),ae())}var Le;!function(e){e.URL="url",e.showSourceCode="showSourceCode",e.scopeLocation="scopeLocation",e.setShodowDom="setShodowDom",e.mode="mode",e.data="data",e.id="id",e.scopeJs="scopeJs",e.scopeCss="scopeCss",e.keepAlive="keepAlive"}(Le||(Le={}));class Te extends HTMLElement{static get observedAttributes(){return[Le.URL]}connected=!1;appUrl="";get appKey(){return this.getAttribute(Le.id)||this.getAttribute(Le.URL)}get appData(){if(this.hasAttribute(Le.data))try{return JSON.parse(this.getAttribute(Le.data))}catch{}return{}}get appProps(){return"js"===this.getAttribute("mode")?{url:this.getAttribute(Le.URL),mode:"js",id:this.appKey,data:this.appData,container:this.shadowRoot??this,showSourceCode:this.getBooleanAttr(Le.showSourceCode),scopeCss:this.getBooleanAttr(Le.scopeCss)&&!this.getBooleanAttr(Le.setShodowDom),scopeJs:this.getBooleanAttr(Le.scopeJs),keepAlive:this.getBooleanAttr(Le.keepAlive)}:{url:this.getAttribute(Le.URL),mode:"app",id:this.appKey,data:this.appData,container:this.shadowRoot??this,scopeLocation:this.getBooleanAttr(Le.scopeLocation),showSourceCode:this.getBooleanAttr(Le.showSourceCode),scopeCss:!this.getBooleanAttr(Le.setShodowDom),scopeJs:!this.getBooleanAttr(Le.scopeJs),keepAlive:this.getBooleanAttr(Le.keepAlive)}}async connectedCallback(){Ae(),this.getBooleanAttr(Le.setShodowDom)&&!this.shadowRoot&&this.attachShadow({mode:"open",delegatesFocus:!0}),await _e(this.appProps),Ce(this.appKey,this.shadowRoot??this),this.connected=!0}disconnectedCallback(){this.connected=!1,this.appProps.keepAlive?ve(this.appKey):be(this.appKey)}attributeChangedCallback(e,t,n){e===Le.URL&&this[e]!==n&&(this.appUrl=n,(this.connected||X.getApp(this.appKey))&&this.handleAttributeChanged())}async handleAttributeChanged(){if(!this.appKey)return;this.getBooleanAttr(Le.setShodowDom)&&this.attachShadow({mode:"open"});const e=X.getApp(this.appKey);!e||e.url!==this.appUrl||!e.isPreLoad&&e.status!==l.UNMOUNT?await _e(this.appProps):Ce(this.appKey,this.shadowRoot??this)}getBooleanAttr(e){return this.hasAttribute(e)?"false"!==this.getAttribute(e):void 0}}const Pe="bk-weweb";class Re{fetchSource;webcomponentTag=Pe;constructor(){window.customElements.get(Pe)||window.customElements.define(Pe,Te)}start(e){"function"==typeof e?.fetchSource&&(this.fetchSource=e.fetchSource),this.webcomponentTag=e?.webcomponentTag||Pe,this.setWebComponentTag()}setWebComponentTag(){window.customElements.get(this.webcomponentTag)||window.customElements.define(this.webcomponentTag,Te)}}const Be=new Re;e.IframeApp=Re,e.activated=Ce,e.beforeLoad=Ae,e.deactivated=ve,e.default=Be,e.load=_e,e.loadApp=Se,e.loadInstance=ge,e.mount=function(e,t,n){const o=X.getApp(e);u((()=>o?.mount(t,n)))},e.preLoadApp=function(e){y((()=>Se({...e,isPreLoad:!0})))},e.preLoadInstance=function(e){y((()=>ge({...e,isPreLoad:!0})))},e.preLoadSource=function(e){y((()=>{!async function(e){const{collectScript:t,collectStyle:n}=await Z(e),o=[];t&&Array.from(t.entries()).forEach((e=>{o.push(e[1].getCode()),X.setBaseAppScript(...e)})),n&&Array.from(n.entries()).forEach((e=>{o.push(e[1].getCode()),X.setBaseAppStyle(...e)})),await Promise.all(o).catch((e=>{throw e}))}(e)}))},e.unload=function(e){X.deleteApp(e)},e.unmount=be,Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).bkIframe={})}(this,(function(e){"use strict";let t=null;function n(){return t}function o(e){t=e}const s=new Map,i=new Map,r="noModule"in document.createElement("script"),c=document.createElement("style");c.setAttribute("id","SCOPED_CSS_STYLE_ID"),document.body.appendChild(c),c.sheet.disabled=!0;const a=c;var l;function h(e){return"function"==typeof e}!function(e){e.UNSET="UNSET",e.LOADING="LOADING",e.LOADED="LOADED",e.ERROR="ERROR",e.MOUNTING="MOUNTING",e.MOUNTED="MOUNTED",e.ACTIVATED="ACTIVATED",e.DEACTIVATED="DEACTIVATED",e.UNMOUNT="UNMOUNT"}(l||(l={}));const u="function"==typeof window.Zone?setTimeout:e=>Promise.resolve().then(e);function p(e){return e.startsWith("//")?`${location.protocol}${e}`:e}function d(e,t){return!e||/^((((ht|f)tps?)|file):)?\/\//.test(e)||/^(data|blob):/.test(e)?e:new URL(e,function(e){const{origin:t,pathname:n}=new URL(e);if(/\.(\w+)$/.test(n)){const e=`${t}${n}`.split("/");return e.pop(),`${e.join("/")}/`}return`${t}${n}/`.replace(/\/\/$/,"/")}(p(t))).toString()}const m="undefined"!=typeof navigator&&-1!==navigator.userAgent.indexOf("Trident");function f(){return`inline-${A(16)}`}const y=window.requestIdleCallback||function(e){const t=Date.now();return setTimeout((()=>{e({didTimeout:!1,handle:()=>Math.max(0,50-(Date.now()-t))})}),1)};function w(e,t){const n=document.createElement(e,t);return n.__BK_WEWEB_APP_KEY__&&delete n.__BK_WEWEB_APP_KEY__,n}function E(e){return/^(body|head|html)$/i.test(e)}const A=(e,t="abcdefghijklmnopqrstuvwxyz0123456789")=>{let n="";for(let o=0;o<e;o++)n+=t[parseInt((Math.random()*t.length).toString(),10)];return n};function _(e,t={}){return Be.fetchSource?Be.fetchSource(e,t):window.fetch(e,t).then((e=>e.text()))}const S="id";var g;!function(e){e[e.STYLE_RULE=1]="STYLE_RULE",e[e.MEDIA_RULE=4]="MEDIA_RULE",e[e.SUPPORTS_RULE=12]="SUPPORTS_RULE"}(g||(g={}));const b=["System","__cjsWrapper","__REACT_ERROR_OVERLAY_GLOBAL_HOOK__"],C=["location"],v=["webpackJsonp","__POWERED_BY_BK_WEWEB__","__BK_WEWEB_APP_KEY__","__BK_WEWEB_DATA__"],L=["location","history"];var T;!function(e){e.TARGET="TARGET",e.WINDOW="WINDOW"}(T||(T={}));const P={undefined:!0,Array:!0,Object:!0,String:!0,Boolean:!0,Math:!0,Reflect:!0,Function:!0,Number:!0,Symbol:!0,parseFloat:!0,parseInt:!0,Float32Array:!0,Set:!0,Infinity:!0,navigator:!0,devicePixelRatio:!0,Promise:!0,HTMLElement:!0,Map:!0,Element:!0,performance:!0,console:!0,isFinite:!0,RegExp:!0,JSON:!0,Date:!0,Proxy:!0,isNaN:!0,WeakMap:!0,WeakSet:!0,Uint8Array:!0},R={__VUE_OPTIONS_API__:!0,__VUE_I18N_LEGACY_API__:!0,__VUE_I18N_FULL_INSTALL__:!0,__VUE_DEVTOOLS_GLOBAL_HOOK__:!0,__VUE_DEVTOOLS_HOOK_REPLAY__:!0,__VUE_DEVTOOLS_PLUGINS__:!0,__DEV__:!0,webpackChunktrace:!0,webpackChunkpc:!0,webpackChunkapm:!0,i18n:!0,"__core-js_shared__":!0},B=new WeakMap;const x=new WeakMap;function M(e,t){if(x.has(t))return x.get(t);if(h(t)&&!function(e){if(B.has(e))return B.get(e);const t=e.toString(),n=e.prototype&&e.prototype.constructor===e&&Object.getOwnPropertyNames(e.prototype).length>1||/^function\s+[A-Z]/.test(t)||/^class\s+/.test(t);return B.set(e,n),n}(t)){const n=t.bind(e);return Object.keys(t).forEach((e=>n[e]=t[e])),t.hasOwnProperty("prototype")&&!n.hasOwnProperty("prototype")&&(n.prototype=t.prototype),x.set(t,n),n}return t}class O{app;resetWindowFunction;resetDocumentAndBodyEvent;injectedKeySet=new Set;escapedKeySet=new Set;active=!1;rawWindow;rawDocument;proxyWindow;fakeWindow={};windowSymbolKey;constructor(e){this.app=e;const t=new Map,o=window,r=window.document;this.fakeWindow.__POWERED_BY_BK_WEWEB__=!0,this.fakeWindow.__BK_WEWEB_APP_KEY__=e.appCacheKey,this.rawWindow=o,this.rawDocument=r,this.fakeWindow.rawWindow=o,this.fakeWindow.rawDocument=r;const{resetWindowFunction:c}=function(e){const t=n(),o=new Map,r=new Map,c=new Map,a=window,l=window.document,{addEventListener:h,removeEventListener:u,setInterval:p,setTimeout:d,clearInterval:m,clearTimeout:f}=window,{removeEventListener:y}=window.document;return e.addEventListener=function(e,t,n){const s=o.get(e);s?s.add(t):o.set(e,new Set([t])),h.call(a,e,t,n)},e.removeEventListener=function(e,t,n){const s=o.get(e);s?.size&&s.has(t)&&s.delete(t),u.call(a,e,t,n)},e.setInterval=function(e,t,...n){const o=p.call(a,e,t,...n);return r.set(o,{handler:e,timeout:t,args:n}),o},e.setTimeout=function(e,t,...n){const o=d.call(a,e,t,...n);return c.set(o,{handler:e,timeout:t,args:n}),o},e.clearInterval=function(e){r.delete(e),m.call(a,e)},e.clearTimeout=function(e){c.delete(e),f.call(a,e)},{resetWindowFunction:()=>{if(o.size&&(o.forEach(((e,t)=>{for(const n of e)u.call(a,t,n)})),o.clear()),r.size&&(r.forEach(((e,t)=>{m.call(a,t)})),r.clear()),c.size&&(c.forEach(((e,t)=>{f.call(a,t)})),c.clear()),t){s.delete(t.appCacheKey);const e=i.get(t.appCacheKey);e&&(e.forEach(((e,t)=>{for(const n of e)y.call(l,t,n)})),e.clear())}}}}(this.fakeWindow);this.resetWindowFunction=c,this.windowSymbolKey=`__${(e.name||e.appCacheKey).replace(/(-|,|:|~|'|")/gim,"_")}_${A(10)}__`,this.proxyWindow=new Proxy(this.fakeWindow,{get:(t,n)=>{if(P[n]||n===Symbol.unscopables)return o[n];if(R[n])return this.fakeWindow[n];if(["window","self","globalThis"].includes(n))return this.proxyWindow;if("document"===n||"eval"===n)return e.registerRunningApp(),"document"===n?r:eval;if(L.includes(n)&&this.app instanceof z&&this.app.iframe&&this.app.scopeLocation)return this.app.iframe.contentWindow?.[n];if("hasOwnProperty"===n)return e=>this.fakeWindow.hasOwnProperty(e)||o.hasOwnProperty(e);if("top"===n||"parent"===n)return o===o.parent?this.proxyWindow:Reflect.get(o,n);if(Reflect.has(t,n)||v.includes(n))return Reflect.get(t,n);const s=Reflect.get(o,n);return M(o,s)},set:(e,t,n)=>{if(this.active){if(L.includes(t)&&this.app instanceof z&&this.app.iframe&&this.app.scopeLocation)return Reflect.set(this.app.iframe.contentWindow,t,n);if(C.includes(t))Reflect.set(o,t,n);else if(e.hasOwnProperty(t)||!o.hasOwnProperty(t)||v.includes(t))Reflect.set(e,t,n),this.injectedKeySet.add(t);else{const s=Object.getOwnPropertyDescriptor(o,t),{writable:i,configurable:r,enumerable:c}=s;i&&(Object.defineProperty(e,t,{configurable:r,enumerable:c,writable:i,value:n}),this.injectedKeySet.add(t))}!b.includes(t)||Reflect.has(o,t)||v.includes(t)||(Reflect.set(o,t,n),this.escapedKeySet.add(t))}return!0},has:(e,t)=>P[t]||t in e||t in o,getOwnPropertyDescriptor:(e,n)=>{if(e.hasOwnProperty(n))return Object.getOwnPropertyDescriptor(e,n);if(o.hasOwnProperty(n)){t.set(n,T.WINDOW);const e=Object.getOwnPropertyDescriptor(o,n);return e&&!e.configurable&&(e.configurable=!0),e}},defineProperty:(e,n,s)=>t.get(n)===T.WINDOW?Reflect.defineProperty(o,n,s):Reflect.defineProperty(e,n,s),ownKeys:e=>{return t=Reflect.ownKeys(o).concat(Reflect.ownKeys(e)),Array.from(new Set(t));var t},deleteProperty:(e,t)=>!e.hasOwnProperty(t)||(this.injectedKeySet.has(t)&&this.injectedKeySet.delete(t),this.escapedKeySet.has(t)&&Reflect.deleteProperty(o,t),Reflect.deleteProperty(e,t))}),e.showSourceCode&&(o[this.windowSymbolKey]=this.proxyWindow)}activeated(e){if(!this.active){this.active=!0,this.fakeWindow.__BK_WEWEB_DATA__=e??{};const{resetDocumentAndBodyEvent:t}=function(){const{addEventListener:e,removeEventListener:t}=window.document,{addEventListener:o,removeEventListener:s}=window.document.body;return document.addEventListener=function(t,o,s){const r=n();if(r){const e=i.get(r.appCacheKey);if(e){const n=e.get(t);n?n.add(o):e.set(t,new Set([o]))}else i.set(r.appCacheKey,new Map([[t,new Set([o])]]))}e.call(r?.container instanceof ShadowRoot?r.container:this,t,o,s)},document.body.addEventListener=document.addEventListener,document.removeEventListener=function(e,o,s){const r=n();if(r){const t=i.get(r.appCacheKey);if(t){const n=t.get(e);n?.size&&n.has(o)&&n.delete(o)}}t.call(r?.container instanceof ShadowRoot?r.container:this,e,o,s)},document.body.removeEventListener=document.removeEventListener,{resetDocumentAndBodyEvent:function(){document.addEventListener=e,document.body.addEventListener=o,document.removeEventListener=t,document.body.removeEventListener=s}}}();this.resetDocumentAndBodyEvent=t}}deactivated(){this.active&&(this.active=!1,this.resetWindowFunction(),this.injectedKeySet.clear(),this.escapedKeySet.forEach((e=>Reflect.deleteProperty(window,e))),this.escapedKeySet.clear(),this.resetDocumentAndBodyEvent?.())}}function D(e,t){Object.defineProperties(e,{currentTarget:{get:()=>t},srcElement:{get:()=>t},target:{get:()=>t}})}function W(e){const t=new CustomEvent("load");D(t,e),h(e.onload)?e.onload(t):e.dispatchEvent(t)}const{appendChild:K}=HTMLBodyElement.prototype;function k(e,t,n){if(t instanceof HTMLStyleElement){if(t.hasAttribute("exclude"))return document.createComment("【bk-weweb】style with exclude attribute is ignored");if(!t.hasAttribute("ignore")){const e=new I({code:t.textContent||"",url:"",fromHtml:!1});n.source?.setStyle(f(),e),e.scopedStyleCSS(n,t)}return t}if(t instanceof HTMLLinkElement){const o=n.source?.collectLink(t,e,!0);return o?(o.style&&o.style.scopedLinkCSS(n,t),o.replace!==t?o.replace:t):t}if(t instanceof HTMLScriptElement){const o=n.source.collectScript(t,e,!0);if(!o)return t;if(o.script&&o.script.excuteCode(n),o.replace!==t)return o.replace;if(n.scopeJs&&!t.getAttribute("src")&&!t.textContent){const o=new MutationObserver((()=>{if(t.getAttribute("src")){o.disconnect();const s=n.source.collectScript(t,e,!0);s?.replace&&K.call(n.container,s.replace),s?.script&&s.script.excuteCode(n),t.remove()}else if(t.textContent){o.disconnect();const e=new F({code:t.textContent,async:!1,defer:"module"===t.type,isModule:"module"===t.type,fromHtml:!1});n.source.scripts.set(f(),e);try{e.excuteCode(n)}catch(e){console.error(e)}finally{!e.isModule&&W(t),t.remove()}}}));return o.observe(t,{attributeFilter:["src"],childList:!0,subtree:!1}),document.createComment("【bk-weweb】dynamic script or module")}return t}return t}function H(e){return e instanceof HTMLScriptElement||e instanceof HTMLStyleElement||e instanceof HTMLLinkElement}function U(e,t,n){if(t.__BK_WEWEB_APP_KEY__){const o=X.getApp(t.__BK_WEWEB_APP_KEY__);if(o?.container){const s=k(e,t,o),i=H(t)&&!!o.keepAlive&&!(o.container instanceof ShadowRoot),r=i?document.head:o?.container;return N(s,o,i),n.call(r,s)}}return n.call(e,t)}function N(e,t,n){return n&&(e.__KEEP_ALIVE__=t.appCacheKey,e.setAttribute("data-from",t.name),e.setAttribute("data-keep-alive","true")),e.setAttribute?.("powered-by","bk-weweb"),e}class I{scopedCode="";code="";prefetch=!1;preload=!1;url;scoped;fromHtml;initial;constructor({code:e,prefetch:t,preload:n,url:o,fromHtml:s,initial:i}){this.scoped=!1,this.code=e,this.prefetch=t??!1,this.preload=n??!1,this.url=o,this.fromHtml=s,this.initial=i??!1}async getCode(e){if(this.code.length||!this.url)return this.code;let t="";if(e?.source?.styles?.has(this.url)&&(t=e.source.styles.get(this.url)?.code||""),!t&&X.getCacheStyle(this.url)){t=X.getCacheStyle(this.url)?.code||""}return t||(t=await _(this.url).catch((()=>""))),this.code=t,t}async excuteCode(e){e.registerRunningApp();let t=w("style");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(e){console.error("scoped style error",e)}return t}scopedStyleCSS(e,t){const n=!(!e.keepAlive||e.container instanceof ShadowRoot);if(N(t,e,n),this.code||t.textContent)t.textContent&&(t.textContent="",t.innerHTML=""),a.textContent=this.code,this.commonScoped(a,t,e),a.textContent="";else{const n=new MutationObserver((()=>{(t.textContent||t.sheet?.cssRules?.length)&&(n.disconnect(),this.commonScoped(t,t,e))}));n.observe(t,{attributes:!1,childList:!0,subtree:!0,characterData:!0})}return this.url&&t.setAttribute("origin-src",this.url),t}scopedLinkCSS(e,t){const n=w("style");n.setAttribute("type","text/css");const o=!(!e.keepAlive||e.container instanceof ShadowRoot);N(n,e,o);const s=o?document.head:e.container;try{if(this.code)a.textContent=n.textContent||this.code,this.commonScoped(a,n,e),s?.prepend(n),t&&W(t),a.textContent="";else if(t.getAttribute("href"))this.url=d(t.getAttribute("href"),e.url),this.getCode(e).then((()=>{this.scopedStyleCSS(e,n),t.remove(),s?.prepend(n),t&&W(t),this.scoped=!0}));else{const o=new MutationObserver((()=>{t.href&&(o.disconnect(),this.url=d(t.getAttribute("href"),e.url),this.getCode(e).then((()=>{this.scopedStyleCSS(e,n),t.remove(),s?.prepend(n),t&&W(t),this.scoped=!0})))}));o.observe(t,{attributeFilter:["href"],subtree:!1,childList:!1})}}catch{t&&function(e){const t=new CustomEvent("error");D(t,e),h(e.onerror)?e.onerror(t):e.dispatchEvent(t)}(t)}return n}commonScoped(e,t,n){if(!n.scopeCss||n.container instanceof ShadowRoot){const o=this.resetUrlHost(t.textContent||e.textContent||"",n.url,this.url);t.textContent=o}else{const o=Array.from(e.sheet?.cssRules??[]),s=`#${n.name}`,i=this.scopeRule(o,s);let r=this.resetUrlHost(i,n.url,this.url);/Safari/.test(navigator.userAgent)&&(r=r.replace(/([;{]\s*content:\s*)([^\s"][^";}]*)/gm,((e,t,n)=>"none"===n||/^(url\()|(counter\()|(attr\()|(open-quote)|(close-quote)/.test(n)?e:`${t}"${n}"`))),t.textContent=r,this.scopedCode=r}this.scoped=!0}scopeRule(e,t){let n="";for(const o of e)switch(o.type){case g.STYLE_RULE:n+=this.scopeStyleRule(o,t);break;case g.MEDIA_RULE:n+=this.resetPackRule(o,t,"media");break;case g.SUPPORTS_RULE:n+=this.resetPackRule(o,t,"supports");break;default:n+=o.cssText}return n.replace(/^\s+/,"")}resetPackRule(e,t,n){const o=this.scopeRule(Array.from(e.cssRules),t);return`@${n} ${e.conditionText} {${o}}`}resetUrlHost(e,t,n){return e.replace(/url\(["']?([^)"']+)["']?\)/gm,((e,o)=>/^(data|blob):/.test(o)||/^(https?:)?\/\//.test(o)?e:(/^((\.\.?\/)|[^/])/.test(o)&&n&&(t=function(e){const t=e.split("/");return t.pop(),p(`${t.join("/")}/`)}(n)),`url("${d(o,t)}")`)))}scopeStyleRule(e,t){const{selectorText:n,cssText:o}=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} *`);const s=/(^|\s+)((html[\s>~]+body)|(html|body|:root))(?=[\s>~]+|$)/;return o.replace(/^[\s\S]+{/,(e=>e.replace(/(^|,)([^,]+)/g,((e,n,o)=>s.test(o)?e.replace(s,t):`${n} ${t} ${o.replace(/^\s*/,"")}`))))}}async function $(e,t){const n=Array.from(e.source.styles.values()),o=[];n.forEach((t=>{o.push(t.excuteCode(e))})),await Promise.all(o).then((n=>{const o=t||e.container;!e.keepAlive||o instanceof ShadowRoot?o?.prepend(...n):document.head.append(...n)}))}class j{state=l.UNSET;isPreLoad=!1;appCacheKey;url;container;scopeJs=!1;source;sandBox;name;showSourceCode=!0;scopeCss=!0;keepAlive;initSource;data;constructor(e){this.name=e.id!==e.url?e.id:A(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 O(this))}get status(){return this.state}set status(e){this.state=e}async start(){this.source&&![l.UNSET,l.ERROR].includes(this.status)||(this.source=new Q(this.url),await this.source.importEntery(this))}onMount(){this.isPreLoad||(this.state=l.LOADED,this.mount())}onError(){this.state=l.ERROR}mount(e,t){this.isPreLoad=!1,this.container=e??this.container,this.state=l.MOUNTING,this.container instanceof HTMLElement&&this.container.setAttribute(S,this.name),this.container.innerHTML="";const n=document.createElement("div"),o=`${this.name}-wrapper`;n.setAttribute("id",o),this.source?.styles.size&&$(this,this.container),this.container.appendChild(n),this.sandBox?.activeated(),q(this).finally((()=>{this.state=l.MOUNTED;const e=this.source?.getScript(this.url);"function"==typeof e?.exportInstance?.render&&e.exportInstance.render(n,this.data),t?.(this,e?.exportInstance)}))}activated(e,t){if(this.isPreLoad=!1,this.state=l.ACTIVATED,this.container&&e){e instanceof Element&&e.setAttribute(S,this.name);const n=document.createDocumentFragment();Array.from(this.container.childNodes).forEach((e=>{n.appendChild(e)})),e.appendChild(n),this.container=e,this.sandBox?.activeated();const o=this.source?.getScript(this.url);t?.(this,o?.exportInstance)}}deactivated(){this.state=l.DEACTIVATED,this.sandBox?.deactivated()}unmount(e){this.state=l.UNMOUNT,this.sandBox?.deactivated(),e&&X.deleteApp(this.url),this.container.innerHTML="",this.container=void 0}registerRunningApp(){o(this),Promise.resolve().then((()=>o(null)))}}let V,Y,J;class F{code="";async=!1;defer=!1;isModule=!1;url;exportInstance;scoped;fromHtml;initial;constructor({code:e,async:t,defer:n,isModule:o,url:s,fromHtml:i,initial:r}){this.code=e,this.async=t,this.defer=n,this.isModule=o,this.url=s,this.scoped=!1,this.fromHtml=i??!1,this.initial=r??!1}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&&X.getCacheScript(this.url)&&(t=X.getCacheScript(this.url)?.code||""),t||(t=await _(this.url).catch((e=>(console.error(`fetch script ${this.url} error`,e),"")))),this.code=t,t}async excuteCode(e,t=!1){try{this.code||await this.getCode(e),e instanceof j&&function(e){Y=void 0,V=Y;for(const t in e)G(e,t)||(V?Y||(Y=t):V=t,J=t)}(e.sandBox?.proxyWindow||window);let n=this.code;if(n=this.transformCode(e),e.showSourceCode||this.isModule){const o=w("script");if(e.registerRunningApp(),this.executeSourceScript(o,n),t)return o;const s=!(!e.keepAlive||e.container instanceof ShadowRoot),i=s?document.head:e.container;N(o,e,s),i.appendChild(o)}else if(this.executeMemoryScript(e,n),t)return document.createComment("【bk-weweb】dynamic script");if(e instanceof j){const t=function(e,t){let n,o,s=0;for(const i in e)if(!G(e,i)){if(0===s&&i!==V||1===s&&i!==Y)return i;n?(J=i,o=t&&o||i):n=i===J,s+=1}return o}(e.sandBox?.proxyWindow||window);t&&(this.exportInstance=(e.sandBox?.proxyWindow||window)[t])}}catch(e){console.error("execute script code error",e)}}transformCode(e){return e.sandBox?e.showSourceCode||this.isModule?`;(function(window, self){\n with(window){\n ;${this.code}\n\n }\n }).call(window.${e.sandBox.windowSymbolKey},\n window.${e.sandBox.windowSymbolKey});`:`\n with(window) {\n try {\n ${this.code}\n }\n catch(e) {\n console.error(e)\n }\n }\n `:this.code}executeSourceScript(e,t){if(this.isModule){const n=new Blob([t],{type:"text/javascript"});e.src=URL.createObjectURL(n),e.setAttribute("type","module")}else e.textContent=t;this.url&&e.setAttribute("origin-src",this.url)}executeMemoryScript(e,t){try{const n=e instanceof z&&e.scopeLocation;e.registerRunningApp(),new Function("window","location","history",t)(e.sandBox.proxyWindow,n?e.iframe?.contentWindow?.location:window.location,n?e.iframe?.contentWindow?.history:window.history)}catch(e){console.error(e)}}}function G(e,t){return!e.hasOwnProperty(t)||!isNaN(t)&&t<e.length||m&&e[t]&&"undefined"!=typeof window&&e[t].parent===window}async function q(e){const t=Array.from(e.source.scripts.values()).filter((e=>e.initial));t.length&&await Promise.all(t.map((t=>t.excuteCode(e))));const n=Array.from(e.source.scripts.values()).filter((e=>e.fromHtml&&!e.initial)),o=n.filter((e=>!e.async&&!e.defer||e.isModule));await Promise.all(o.map((t=>t.excuteCode(e))));const s=[],i=[];n.forEach((t=>{(t.defer||t.async)&&(!t.code&&t.defer?s.push(t.excuteCode(e)):i.push(t.excuteCode(e)))})),await Promise.all([...i,...s]).catch((e=>{console.error(e)}))}class z{state=l.UNSET;isPreLoad=!1;mode="app";name;url;container;showSourceCode;scopeCss;scopeJs;source;sandBox;scopeLocation;keepAlive;initSource;iframe=null;data;constructor(e){this.name=e.id!==e.url?e.id:A(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 O(this)),this.container instanceof HTMLElement&&this.container.setAttribute(S,this.name)}get appCacheKey(){return this.url}get status(){return this.state}set status(e){this.state=e}async start(){if(!this.source||[l.UNSET,l.ERROR].includes(this.status)){if(this.state=l.LOADING,this.scopeLocation){const e=await this.createIframe();this.iframe=e}this.source=new Q(this.url),await this.source.importEntery(this)}}onMount(){this.isPreLoad||(this.state=l.LOADED,this.mount())}onError(){this.state=l.ERROR}mount(e,t){if(this.isPreLoad=!1,this.container=e??this.container,this.state=l.MOUNTING,this.container){this.container instanceof Element&&this.container.setAttribute(S,this.name);const e=this.source.html.cloneNode(!0),n=document.createDocumentFragment();Array.from(e.childNodes).forEach((e=>{n.appendChild(e)})),this.container.innerHTML="",this.container.appendChild(n),this.sandBox?.activeated(this.data),q(this).finally((()=>{this.state=l.MOUNTED,t?.(this)}))}}activated(e,t){if(this.isPreLoad=!1,this.state=l.ACTIVATED,e&&this.container){e instanceof Element&&e.setAttribute(S,this.name);const n=document.createDocumentFragment();Array.from(this.container.childNodes).forEach((e=>{n.appendChild(e)})),e.innerHTML="",e.appendChild(n),this.container=e,this.sandBox?.activeated(this.data),t?.(this)}}deactivated(){this.state=l.DEACTIVATED,this.sandBox?.deactivated()}unmount(e=!1){this.state=l.UNMOUNT,this.sandBox?.deactivated(),e&&X.deleteApp(this.url),this.container.innerHTML="",this.container=void 0}createIframe(){return new Promise((e=>{const t=document.createElement("iframe"),n=new URL(this.url);t.setAttribute("src",`about:blank${n.pathname||"/"}${n.search}${n.hash}`),t.style.cssText="position: fixed; top: -9999px; width: 100%; height: 1px;",document.body.appendChild(t),setTimeout((()=>e(t)),100)}))}registerRunningApp(){o(this),Promise.resolve().then((()=>o(null)))}}async function Z(e){let t=[];if(t="function"==typeof e?await e():e||[],!t.length)return{};const n=new Map,o=new Map;return t.forEach((e=>{try{const t=new URL(e);if(t.pathname.match(/\.js$/)){const t=X.getCacheScript(e);n.set(e,new F({code:t?.code||"",async:!1,defer:!1,url:e,isModule:!1,initial:!0,fromHtml:!1}))}else if(t.pathname.match(/\.css$/)){const t=X.getCacheStyle(e);o.set(e,new I({code:t?.code||"",prefetch:!1,preload:!1,url:e,fromHtml:!0,initial:!0}))}}catch{console.error(`【bk-weweb】: ${e} is invalid URL`)}})),{collectScript:n,collectStyle:o}}class Q{url;scripts;styles;html=null;rawHtml;constructor(e){this.url=e,this.scripts=new Map,this.styles=new Map}async importEntery(e){let t;if(e.initSource?.length){const{collectScript:t,collectStyle:n}=await Z(e.initSource);t&&(this.scripts=t),n&&(this.styles=n)}e instanceof z?t=this.importHtmlEntry(e):e instanceof j&&(t=this.importInstanceEntry()),t&&await t}async importHtmlEntry(e){let t=X.getCacheHtml(this.url);if(!t&&(t=await _(this.url,{cache:"no-cache"}),!t))return console.error("load app entry error, pleace check"),Promise.reject();this.rawHtml=t;const n=w("div");n.innerHTML=t.replace(/<\/?head>/gim,"").replace(/<\/?body>/i,""),this.collectScriptAndStyle(n,e),await $(e,n),this.html=n}async importInstanceEntry(){let e=X.getCacheScript(this.url)?.code;if(e||(e=await _(this.url,{cache:"no-cache"})),!e)return console.error("load app entry error, pleace check"),Promise.reject();this.scripts.set(this.url,new F({code:e,async:!1,defer:!1,url:this.url,isModule:!1,fromHtml:!0}))}collectScriptAndStyle(e,t){const n=Array.from(e.children);n.length&&n.forEach((e=>{this.collectScriptAndStyle(e,t)}));for(const t of n)t instanceof HTMLLinkElement?this.collectLink(t,e):t instanceof HTMLStyleElement?t.hasAttribute("exclude")||t.hasAttribute("ignore")||(this.styles.set(f(),new I({code:t.textContent||"",url:"",fromHtml:!0})),t.remove()):t instanceof HTMLScriptElement?this.collectScript(t,e):t instanceof HTMLMetaElement||t instanceof HTMLTitleElement?e.removeChild(t):t instanceof HTMLImageElement&&t.hasAttribute("src")&&t.setAttribute("src",d(t.getAttribute("src"),this.url))}collectLink(e,t,n=!1){if(e.hasAttribute("exclude"))return{replace:document.createComment("【bk-weweb】style with exclude attribute is ignored")};if(e.hasAttribute("ignore"))return{replace:e};const o=e.getAttribute("rel");let s,i=e.getAttribute("href");if("stylesheet"===o&&i){i=d(i,this.url),s=document.createComment(`【bk-weweb】style with href=${i}`);let o=this.getStyle(i);return o||(o=new I({code:"",url:i,prefetch:!!e.getAttribute("prefetch"),preload:!!e.getAttribute("preload"),fromHtml:!n}),this.styles.set(i,o)),!n&&t.replaceChild(s,e),{replace:s,style:o}}return o&&["prefetch","preload","prerender","icon","apple-touch-icon"].includes(o)?(s=document.createComment(`【bk-weweb】style with rel=${o}${i?` & href=${i}`:""}`),!n&&t.removeChild(e),{replace:s}):(i&&e.setAttribute("href",d(i,this.url)),{replace:e})}collectScript(e,t,n=!1){if(e.hasAttribute("ignore")||e.hasAttribute("type")&&!["text/javascript","text/ecmascript","application/javascript","application/ecmascript","module"].includes(e.type)||!r&&"module"===e.type)return;let o=null;if(e.hasAttribute("exclude"))return o=document.createComment("【bk-weweb】script element with exclude attribute is removed"),!n&&t.replaceChild(o,e),{replace:o};let s=e.getAttribute("src");if(s){s=d(s,this.url);let i=this.getScript(s);return i||(i=new F({code:"",async:e.hasAttribute("async"),defer:e.defer||"module"===e.type,isModule:"module"===e.type,url:s,fromHtml:!n}),this.scripts.set(s,i)),o=document.createComment(`【bk-weweb】script with src='${s}'`),!n&&t.replaceChild(o,e),{replace:o,script:i}}if(e.textContent){const s=f(),i=new F({code:e.textContent,async:!1,defer:"module"===e.type,isModule:"module"===e.type,url:s,fromHtml:!n});return this.scripts.set(s,i),o=document.createComment("【bk-weweb】script with texcontent"),!n&&t.replaceChild(o,e),{replace:o,script:i}}return{replace:e}}setScript(e,t){this.scripts.set(e,new F(t))}getScript(e){return this.scripts.get(e)}setStyle(e,t){this.styles.set(e,t)}getStyle(e){return this.styles.get(e)}}const X=new class{cache;baseSource;constructor(){this.cache=new Map,this.baseSource=new Q(location.href)}get hasActiveApp(){return Array.from(this.cache.values()).some((e=>e.status!==l.UNMOUNT))}setApp(e){this.cache.set(e.appCacheKey,e)}getApp(e){if(!e)return;const t=this.cache.get(e);return t||Array.from(this.cache.values()).find((t=>t.name===e))}getCacheHtml(e){const t=Array.from(this.cache.values()).find((t=>t.url===e));return t&&t.source?.rawHtml||""}getCacheStyle(e){let t=this.baseSource.getStyle(e);if(t)return;return Array.from(this.cache.values()).some((n=>(t=n.source?.getStyle(e),!!t))),t}getCacheScript(e){let t=this.baseSource.getScript(e);if(t)return;return Array.from(this.cache.values()).some((n=>(t=n.source?.getScript(e),!!t))),t}deleteApp(e){this.cache.delete(e)}setBaseAppStyle(e,t){this.baseSource.setStyle(e,t)}setBaseAppScript(e,t){this.baseSource.setScript(e,t)}};window.__getAppOrInstance__=function(e){return e?X.getApp(e):X};const{document:ee}=window,{createElement:te,querySelector:ne,querySelectorAll:oe,getElementById:se,getElementsByClassName:ie,getElementsByTagName:re,getElementsByName:ce}=Document.prototype;function ae(){Document.prototype.createElement=te,Document.prototype.querySelector=ne,Document.prototype.querySelectorAll=oe,Document.prototype.getElementById=se,Document.prototype.getElementsByClassName=ie,Document.prototype.getElementsByTagName=re,Document.prototype.getElementsByName=ce}const{setAttribute:le}=Element.prototype,{appendChild:he,removeChild:ue,append:pe}=HTMLBodyElement.prototype,{appendChild:de,removeChild:me,insertBefore:fe}=HTMLHeadElement.prototype,ye=document.head;function we(){Element.prototype.setAttribute=function(e,t){const n=this.tagName.toLocaleUpperCase();(["src","srcset"].includes(e)&&["SCRIPT","IMG"].includes(n)||"href"===e&&["LINK"].includes(n))&&this.__BK_WEWEB_APP_KEY__&&X.getApp(this.__BK_WEWEB_APP_KEY__||"")?le.call(this,e,d(t,X.getApp(this.__BK_WEWEB_APP_KEY__).url)):le.call(this,e,t)},HTMLBodyElement.prototype.appendChild=function(e){return e.__KEEP_ALIVE__&&H(e)?de.call(ye,e):U(this,e,he)},HTMLBodyElement.prototype.append=function(...e){let t=0;const{length:n}=e;for(;t<n;){if(e[t].__KEEP_ALIVE__&&H(e[t]))return de.call(ye,e[t]);U(this,e[t],he),t+=1}},HTMLHeadElement.prototype.appendChild=HTMLBodyElement.prototype.appendChild,HTMLHeadElement.prototype.insertBefore=function(e,t){return function(e,t,n,o){if(t.__BK_WEWEB_APP_KEY__){const s=X.getApp(t.__BK_WEWEB_APP_KEY__);if(s?.container){const i=H(t)&&s.keepAlive&&!(s.container instanceof ShadowRoot),r=i?document.head:s?.container,c=k(e,t,s);return i&&(c.__KEEP_ALIVE__=s.appCacheKey,c.setAttribute("data-from",s.name),c.setAttribute("data-keep-alive","true")),n&&!r.contains(n)?K.call(r,c):o.call(r,c,n)}}return o.call(e,t,n)}(this,e,t,fe)},HTMLBodyElement.prototype.removeChild=function(e){const t=X.getApp(e.__BK_WEWEB_APP_KEY__);if(t?.container?.contains(e)){return ue.call(t.container,e)}return this.contains(e)?ue.call(this,e):e},HTMLHeadElement.prototype.removeChild=HTMLBodyElement.prototype.removeChild}function Ee(){o(null),Element.prototype.setAttribute=le,HTMLBodyElement.prototype.appendChild=he,HTMLBodyElement.prototype.append=pe,HTMLBodyElement.prototype.removeChild=ue,HTMLHeadElement.prototype.appendChild=de,HTMLHeadElement.prototype.insertBefore=fe,HTMLHeadElement.prototype.removeChild=me}function Ae(){we(),function(){function e(e){const t=n();return t&&e&&!E(e)&&ee===this?t?.container?.querySelector(e)??null:ne.call(this,e)}function t(e){const t=n();return t&&e&&!E(e)&&ee===this?t?.container?.querySelectorAll(e)??[]:oe.call(this,e)}Document.prototype.createElement=function(e,t){const o=te.call(this,e,t),s=n();return s&&(o.__BK_WEWEB_APP_KEY__=s.appCacheKey),o},Document.prototype.querySelector=e,Document.prototype.querySelectorAll=t,Document.prototype.getElementById=function(t){if(!n())return se.call(this,t);try{return e.call(this,`#${t}`)}catch{return se.call(this,t)}},Document.prototype.getElementsByClassName=function(e){if(!n())return ie.call(this,e);try{return t.call(this,`.${e}`)}catch{return ie.call(this,e)}},Document.prototype.getElementsByTagName=function(e){const o=n();if(!o||E(e)||!o?.showSourceCode&&"script"===e.toLocaleLowerCase())return re.call(this,e);try{return t.call(this,e)}catch{return re.call(this,e)}},Document.prototype.getElementsByName=function(e){if(!n())return ce.call(this,e);try{return t.call(this,`[name=${e}]`)}catch{return ce.call(this,e)}}}()}async function _e(e){return"app"===e.mode?await Se(e):"js"===e.mode?await ge(e):await Se(e)}async function Se(e){let t=X.getApp(e.id);return t||(t=new z(e),X.setApp(t)),await t.start(),t}function ge(e){return new Promise((t=>{let n=X.getApp(e.id);if(n)if([l.UNSET,l.MOUNTING].includes(n.status)){const e=setInterval((()=>{[l.ERROR,l.MOUNTED].includes(n.status)&&(t(n),clearInterval(e))}),300)}else t(n);else n=new j(e),X.setApp(n),n.start().then((()=>t(n)))}))}function be(e){const t=X.getApp(e);t?.status!==l.UNMOUNT&&t?.unmount(),X.hasActiveApp||(Ee(),ae())}function Ce(e,t,n){const o=X.getApp(e);o?.status===l.DEACTIVATED&&o.keepAlive?u((()=>o?.activated(t,n))):u((()=>o?.mount(t,n)))}function ve(e){const t=X.getApp(e);t&&[l.ACTIVATED,l.MOUNTED].includes(t.status)&&(t.keepAlive?t.deactivated():t.unmount()),X.hasActiveApp||(Ee(),ae())}var Le;!function(e){e.URL="url",e.showSourceCode="showSourceCode",e.scopeLocation="scopeLocation",e.setShodowDom="setShodowDom",e.mode="mode",e.data="data",e.id="id",e.scopeJs="scopeJs",e.scopeCss="scopeCss",e.keepAlive="keepAlive"}(Le||(Le={}));class Te extends HTMLElement{static get observedAttributes(){return[Le.URL]}connected=!1;appUrl="";get appKey(){return this.getAttribute(Le.id)||this.getAttribute(Le.URL)}get appData(){if(this.hasAttribute(Le.data))try{return JSON.parse(this.getAttribute(Le.data))}catch{}return{}}get appProps(){return"js"===this.getAttribute("mode")?{url:this.getAttribute(Le.URL),mode:"js",id:this.appKey,data:this.appData,container:this.shadowRoot??this,showSourceCode:this.getBooleanAttr(Le.showSourceCode),scopeCss:this.getBooleanAttr(Le.scopeCss)&&!this.getBooleanAttr(Le.setShodowDom),scopeJs:this.getBooleanAttr(Le.scopeJs),keepAlive:this.getBooleanAttr(Le.keepAlive)}:{url:this.getAttribute(Le.URL),mode:"app",id:this.appKey,data:this.appData,container:this.shadowRoot??this,scopeLocation:this.getBooleanAttr(Le.scopeLocation),showSourceCode:this.getBooleanAttr(Le.showSourceCode),scopeCss:!this.getBooleanAttr(Le.setShodowDom),scopeJs:!this.getBooleanAttr(Le.scopeJs),keepAlive:this.getBooleanAttr(Le.keepAlive)}}async connectedCallback(){Ae(),this.getBooleanAttr(Le.setShodowDom)&&!this.shadowRoot&&this.attachShadow({mode:"open",delegatesFocus:!0}),await _e(this.appProps),Ce(this.appKey,this.shadowRoot??this),this.connected=!0}disconnectedCallback(){this.connected=!1,this.appProps.keepAlive?ve(this.appKey):be(this.appKey)}attributeChangedCallback(e,t,n){e===Le.URL&&this[e]!==n&&(this.appUrl=n,(this.connected||X.getApp(this.appKey))&&this.handleAttributeChanged())}async handleAttributeChanged(){if(!this.appKey)return;this.getBooleanAttr(Le.setShodowDom)&&this.attachShadow({mode:"open"});const e=X.getApp(this.appKey);!e||e.url!==this.appUrl||!e.isPreLoad&&e.status!==l.UNMOUNT?await _e(this.appProps):Ce(this.appKey,this.shadowRoot??this)}getBooleanAttr(e){return this.hasAttribute(e)?"false"!==this.getAttribute(e):void 0}}const Pe="bk-weweb";class Re{fetchSource;webcomponentTag=Pe;constructor(){window.customElements.get(Pe)||window.customElements.define(Pe,Te)}start(e){"function"==typeof e?.fetchSource&&(this.fetchSource=e.fetchSource),this.webcomponentTag=e?.webcomponentTag||Pe,this.setWebComponentTag()}setWebComponentTag(){window.customElements.get(this.webcomponentTag)||window.customElements.define(this.webcomponentTag,Te)}}const Be=new Re;e.IframeApp=Re,e.activated=Ce,e.beforeLoad=Ae,e.deactivated=ve,e.default=Be,e.load=_e,e.loadApp=Se,e.loadInstance=ge,e.mount=function(e,t,n){const o=X.getApp(e);u((()=>o?.mount(t,n)))},e.preLoadApp=function(e){y((()=>Se({...e,isPreLoad:!0})))},e.preLoadInstance=function(e){y((()=>ge({...e,isPreLoad:!0})))},e.preLoadSource=function(e){y((()=>{!async function(e){const{collectScript:t,collectStyle:n}=await Z(e),o=[];t&&Array.from(t.entries()).forEach((e=>{o.push(e[1].getCode()),X.setBaseAppScript(...e)})),n&&Array.from(n.entries()).forEach((e=>{o.push(e[1].getCode()),X.setBaseAppStyle(...e)})),await Promise.all(o).catch((e=>{throw e}))}(e)}))},e.unload=function(e){X.deleteApp(e)},e.unmount=be,Object.defineProperty(e,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=index.umd.js.map