@micro-zoe/micro-app 1.0.0-rc.3 → 1.0.0-rc.4

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","sources":["../src/libs/utils.ts","../src/interact/lifecycles_event.ts","../src/source/fetch.ts","../src/source/loader/html.ts","../src/sandbox/scoped_css.ts","../src/source/load_event.ts","../src/constants.ts","../src/source/source_center.ts","../src/source/links.ts","../src/source/scripts.ts","../src/source/index.ts","../src/interact/index.ts","../src/interact/event_center.ts","../src/app_manager.ts","../src/libs/nest_app.ts","../src/sandbox/bind_function.ts","../src/sandbox/with/document.ts","../src/sandbox/with/window.ts","../src/sandbox/router/core.ts","../src/sandbox/router/event.ts","../src/sandbox/router/history.ts","../src/sandbox/router/api.ts","../src/sandbox/iframe/special_key.ts","../src/sandbox/router/location.ts","../src/sandbox/router/index.ts","../src/sandbox/adapter.ts","../src/sandbox/request.ts","../src/sandbox/with/index.ts","../src/sandbox/iframe/window.ts","../src/sandbox/iframe/document.ts","../src/sandbox/iframe/element.ts","../src/sandbox/iframe/index.ts","../src/sandbox/iframe/router.ts","../src/create_app.ts","../src/source/patch.ts","../src/libs/global_env.ts","../src/micro_app_element.ts","../src/prefetch.ts","../src/micro_app.ts"],"sourcesContent":["/* eslint-disable no-new-func, indent, @typescript-eslint/explicit-module-boundary-types */\nimport type {\n Func,\n LocationQueryObject,\n LocationQueryValue,\n MicroLocation,\n AttrsType,\n fiberTasks,\n MicroAppElementTagNameMap,\n} from '@micro-app/types'\n\nexport const version = '__MICRO_APP_VERSION__'\n\n// do not use isUndefined\nexport const isBrowser = typeof window !== 'undefined'\n\n// do not use isUndefined\nexport const globalThis = (typeof global !== 'undefined')\n ? global\n : (\n (typeof window !== 'undefined')\n ? window\n : (\n (typeof self !== 'undefined') ? self : Function('return this')()\n )\n )\n\nexport const noop = () => {}\nexport const noopFalse = () => false\n\n// Array.isArray\nexport const isArray = Array.isArray\n// Object.assign\nexport const assign = Object.assign\n\n// Object prototype methods\nexport const rawDefineProperty = Object.defineProperty\nexport const rawDefineProperties = Object.defineProperties\nexport const rawToString = Object.prototype.toString\nexport const rawHasOwnProperty = Object.prototype.hasOwnProperty\n\nexport const toTypeString = (value: unknown): string => rawToString.call(value)\n\n// is Undefined\nexport function isUndefined (target: unknown): target is undefined {\n return target === undefined\n}\n\n// is Null\nexport function isNull (target: unknown): target is null {\n return target === null\n}\n\n// is String\nexport function isString (target: unknown): target is string {\n return typeof target === 'string'\n}\n\n// is Boolean\nexport function isBoolean (target: unknown): target is boolean {\n return typeof target === 'boolean'\n}\n\n// is Number\nexport function isNumber (target: unknown): target is Number {\n return typeof target === 'number'\n}\n\n// is function\nexport function isFunction (target: unknown): target is Function {\n return typeof target === 'function'\n}\n\n// is PlainObject\nexport function isPlainObject <T = Record<PropertyKey, unknown>> (target: unknown): target is T {\n return toTypeString(target) === '[object Object]'\n}\n\n// is Object\nexport function isObject (target: unknown): target is Object {\n return !isNull(target) && typeof target === 'object'\n}\n\n// is Promise\nexport function isPromise (target: unknown): target is Promise<unknown> {\n return toTypeString(target) === '[object Promise]'\n}\n\n// is bind function\nexport function isBoundFunction (target: unknown): boolean {\n return isFunction(target) && target.name.indexOf('bound ') === 0 && !target.hasOwnProperty('prototype')\n}\n\n// is constructor function\nexport function isConstructor (target: unknown): boolean {\n if (isFunction(target)) {\n const targetStr = target.toString()\n return (\n target.prototype?.constructor === target &&\n Object.getOwnPropertyNames(target.prototype).length > 1\n ) ||\n /^function\\s+[A-Z]/.test(targetStr) ||\n /^class\\s+/.test(targetStr)\n }\n return false\n}\n\n// is ShadowRoot\nexport function isShadowRoot (target: unknown): target is ShadowRoot {\n return typeof ShadowRoot !== 'undefined' && target instanceof ShadowRoot\n}\n\nexport function isURL (target: unknown): target is URL {\n return target instanceof URL || !!(target as URL)?.href\n}\n\n// iframe element not instanceof base app Element, use tagName instead\nexport function isElement (target: unknown): target is Element {\n return target instanceof Element || isString((target as Element)?.tagName)\n}\n\n// iframe node not instanceof base app Node, use nodeType instead\nexport function isNode (target: unknown): target is Node {\n return target instanceof Node || isNumber((target as Node)?.nodeType)\n}\n\nexport function isLinkElement (target: unknown): target is HTMLLinkElement {\n return toTypeString(target) === '[object HTMLLinkElement]'\n}\n\nexport function isStyleElement (target: unknown): target is HTMLStyleElement {\n return toTypeString(target) === '[object HTMLStyleElement]'\n}\n\nexport function isScriptElement (target: unknown): target is HTMLScriptElement {\n return toTypeString(target) === '[object HTMLScriptElement]'\n}\n\nexport function isIFrameElement (target: unknown): target is HTMLIFrameElement {\n return toTypeString(target) === '[object HTMLIFrameElement]'\n}\n\nexport function isDivElement (target: unknown): target is HTMLDivElement {\n return toTypeString(target) === '[object HTMLDivElement]'\n}\n\nexport function isImageElement (target: unknown): target is HTMLImageElement {\n return toTypeString(target) === '[object HTMLImageElement]'\n}\n\nexport function isBaseElement (target: unknown): target is HTMLBaseElement {\n return toTypeString(target) === '[object HTMLBaseElement]'\n}\n\nexport function isMicroAppBody (target: unknown): target is HTMLElement {\n return isElement(target) && target.tagName.toUpperCase() === 'MICRO-APP-BODY'\n}\n\n// is ProxyDocument\nexport function isProxyDocument (target: unknown): target is Document {\n return toTypeString(target) === '[object ProxyDocument]'\n}\n\n/**\n * format error log\n * @param msg message\n * @param appName app name, default is null\n */\nexport function logError (\n msg: unknown,\n appName: string | null = null,\n ...rest: unknown[]\n): void {\n const appNameTip = appName && isString(appName) ? ` app ${appName}:` : ''\n if (isString(msg)) {\n console.error(`[micro-app]${appNameTip} ${msg}`, ...rest)\n } else {\n console.error(`[micro-app]${appNameTip}`, msg, ...rest)\n }\n}\n\n/**\n * format warn log\n * @param msg message\n * @param appName app name, default is null\n */\nexport function logWarn (\n msg: unknown,\n appName: string | null = null,\n ...rest: unknown[]\n): void {\n const appNameTip = appName && isString(appName) ? ` app ${appName}:` : ''\n if (isString(msg)) {\n console.warn(`[micro-app]${appNameTip} ${msg}`, ...rest)\n } else {\n console.warn(`[micro-app]${appNameTip}`, msg, ...rest)\n }\n}\n\n/**\n * async execution\n * @param fn callback\n * @param args params\n */\nexport function defer (fn: Func, ...args: unknown[]): void {\n Promise.resolve().then(fn.bind(null, ...args))\n}\n\n/**\n * create URL as MicroLocation\n */\nexport const createURL = (function (): (path: string | URL, base?: string) => MicroLocation {\n class Location extends URL {}\n return (path: string | URL, base?: string): MicroLocation => {\n return (base ? new Location('' + path, base) : new Location('' + path)) as MicroLocation\n }\n})()\n\n/**\n * Add address protocol\n * @param url address\n */\nexport function addProtocol (url: string): string {\n return url.startsWith('//') ? `${globalThis.location.protocol}${url}` : url\n}\n\n/**\n * format URL address\n * note the scenes:\n * 1. micro-app -> attributeChangedCallback\n * 2. preFetch\n */\nexport function formatAppURL (url: string | null, appName: string | null = null): string {\n if (!isString(url) || !url) return ''\n\n try {\n const { origin, pathname, search } = createURL(addProtocol(url))\n // If it ends with .html/.node/.php/.net/.etc, don’t need to add /\n if (/\\.(\\w+)$/.test(pathname)) {\n return `${origin}${pathname}${search}`\n }\n const fullPath = `${origin}${pathname}/`.replace(/\\/\\/$/, '/')\n return /^https?:\\/\\//.test(fullPath) ? `${fullPath}${search}` : ''\n } catch (e) {\n logError(e, appName)\n return ''\n }\n}\n\n/**\n * format name\n * note the scenes:\n * 1. micro-app -> attributeChangedCallback\n * 2. event_center -> EventCenterForMicroApp -> constructor\n * 3. event_center -> EventCenterForBaseApp -> all methods\n * 4. preFetch\n * 5. plugins\n * 6. router api (push, replace)\n */\nexport function formatAppName (name: string | null): string {\n if (!isString(name) || !name) return ''\n return name.replace(/(^\\d+)|([^\\w\\d-_])/gi, '')\n}\n\n/**\n * Get valid address, such as https://xxx/xx/xx.html to https://xxx/xx/\n * @param url app.url\n */\nexport function getEffectivePath (url: string): string {\n const { origin, pathname } = createURL(url)\n if (/\\.(\\w+)$/.test(pathname)) {\n const fullPath = `${origin}${pathname}`\n const pathArr = fullPath.split('/')\n pathArr.pop()\n return pathArr.join('/') + '/'\n }\n\n return `${origin}${pathname}/`.replace(/\\/\\/$/, '/')\n}\n\n/**\n * Complete address\n * @param path address\n * @param baseURI base url(app.url)\n */\nexport function CompletionPath (path: string, baseURI: string): string {\n if (\n !path ||\n /^((((ht|f)tps?)|file):)?\\/\\//.test(path) ||\n /^(data|blob):/.test(path)\n ) return path\n\n return createURL(path, getEffectivePath(addProtocol(baseURI))).toString()\n}\n\n/**\n * Get the folder where the link resource is located,\n * which is used to complete the relative address in the css\n * @param linkPath full link address\n */\nexport function getLinkFileDir (linkPath: string): string {\n const pathArr = linkPath.split('/')\n pathArr.pop()\n return addProtocol(pathArr.join('/') + '/')\n}\n\n/**\n * promise stream\n * @param promiseList promise list\n * @param successCb success callback\n * @param errorCb failed callback\n * @param finallyCb finally callback\n */\nexport function promiseStream <T> (\n promiseList: Array<Promise<T> | T>,\n successCb: CallableFunction,\n errorCb: CallableFunction,\n finallyCb?: CallableFunction,\n): void {\n let finishedNum = 0\n\n function isFinished () {\n if (++finishedNum === promiseList.length && finallyCb) finallyCb()\n }\n\n promiseList.forEach((p, i) => {\n if (isPromise(p)) {\n (p as Promise<T>).then((res: T) => {\n successCb({ data: res, index: i })\n isFinished()\n }).catch((err: Error) => {\n errorCb({ error: err, index: i })\n isFinished()\n })\n } else {\n successCb({ data: p, index: i })\n isFinished()\n }\n })\n}\n\n// Check whether the browser supports module script\nexport function isSupportModuleScript (): boolean {\n const s = document.createElement('script')\n return 'noModule' in s\n}\n\n// Create a random symbol string\nexport function createNonceSrc (): string {\n return 'inline-' + Math.random().toString(36).substr(2, 15)\n}\n\n// Array deduplication\nexport function unique (array: any[]): any[] {\n return array.filter(function (this: Record<PropertyKey, boolean>, item) {\n return item in this ? false : (this[item] = true)\n }, Object.create(null))\n}\n\n// requestIdleCallback polyfill\nexport const requestIdleCallback = globalThis.requestIdleCallback ||\n function (fn: CallableFunction) {\n const lastTime = Date.now()\n return setTimeout(function () {\n fn({\n didTimeout: false,\n timeRemaining () {\n return Math.max(0, 50 - (Date.now() - lastTime))\n },\n })\n }, 1)\n }\n\n/**\n * Wrap requestIdleCallback with promise\n * Exec callback when browser idle\n */\nexport function promiseRequestIdle (callback: CallableFunction): Promise<void> {\n return new Promise((resolve) => {\n requestIdleCallback(() => {\n callback(resolve)\n })\n })\n}\n\n/**\n * Record the currently running app.name\n */\nlet currentMicroAppName: string | null = null\nexport function setCurrentAppName (appName: string | null): void {\n currentMicroAppName = appName\n}\n\nexport function throttleDeferForSetAppName (appName: string) {\n if (currentMicroAppName !== appName) {\n setCurrentAppName(appName)\n defer(() => {\n setCurrentAppName(null)\n })\n }\n}\n\n// get the currently running app.name\nexport function getCurrentAppName (): string | null {\n return currentMicroAppName\n}\n\n// Clear appName\nexport function removeDomScope (): void {\n setCurrentAppName(null)\n}\n\n// is safari browser\nexport function isSafari (): boolean {\n return /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)\n}\n\n/**\n * Create pure elements\n */\nexport function pureCreateElement<K extends keyof MicroAppElementTagNameMap> (tagName: K, options?: ElementCreationOptions): MicroAppElementTagNameMap[K] {\n const element = (window.rawDocument || document).createElement(tagName, options)\n if (element.__MICRO_APP_NAME__) delete element.__MICRO_APP_NAME__\n element.__PURE_ELEMENT__ = true\n return element\n}\n\n/**\n * clone origin elements to target\n * @param origin Cloned element\n * @param target Accept cloned elements\n * @param deep deep clone or transfer dom\n */\nexport function cloneContainer <T extends Element | ShadowRoot, Q extends Element | ShadowRoot> (\n target: Q,\n origin: T,\n deep: boolean,\n): Q {\n // 在基座接受到afterhidden方法后立即执行unmount,彻底destroy应用时,因为unmount时同步执行,所以this.container为null后才执行cloneContainer\n if (origin) {\n target.innerHTML = ''\n if (deep) {\n // TODO: ShadowRoot兼容,ShadowRoot不能直接使用cloneNode\n const clonedNode = origin.cloneNode(true)\n const fragment = document.createDocumentFragment()\n Array.from(clonedNode.childNodes).forEach((node: Node | Element) => {\n fragment.appendChild(node)\n })\n target.appendChild(fragment)\n } else {\n Array.from(origin.childNodes).forEach((node: Node | Element) => {\n target.appendChild(node)\n })\n }\n }\n return target\n}\n\n// is invalid key of querySelector\nexport function isInvalidQuerySelectorKey (key: string): boolean {\n if (__TEST__) return !key || /(^\\d)|([^\\w\\d-_$])/gi.test(key)\n return !key || /(^\\d)|([^\\w\\d-_\\u4e00-\\u9fa5])/gi.test(key)\n}\n\n// unique element\nexport function isUniqueElement (key: string): boolean {\n return (\n /^body$/i.test(key) ||\n /^head$/i.test(key) ||\n /^html$/i.test(key) ||\n /^title$/i.test(key) ||\n /^:root$/i.test(key)\n )\n}\n\n/**\n * get micro-app element\n * @param target app container\n */\nexport function getRootContainer (target: HTMLElement | ShadowRoot): HTMLElement {\n return (isShadowRoot(target) ? (target as ShadowRoot).host : target) as HTMLElement\n}\n\n/**\n * trim start & end\n */\nexport function trim (str: string): string {\n return str ? str.replace(/^\\s+|\\s+$/g, '') : ''\n}\n\nexport function isFireFox (): boolean {\n return navigator.userAgent.indexOf('Firefox') > -1\n}\n\n/**\n * Transforms a queryString into object.\n * @param search - search string to parse\n * @returns a query object\n */\nexport function parseQuery (search: string): LocationQueryObject {\n const result: LocationQueryObject = {}\n const queryList = search.split('&')\n\n // we will not decode the key/value to ensure that the values are consistent when update URL\n for (const queryItem of queryList) {\n const eqPos = queryItem.indexOf('=')\n const key = eqPos < 0 ? queryItem : queryItem.slice(0, eqPos)\n const value = eqPos < 0 ? null : queryItem.slice(eqPos + 1)\n\n if (key in result) {\n let currentValue = result[key]\n if (!isArray(currentValue)) {\n currentValue = result[key] = [currentValue]\n }\n currentValue.push(value)\n } else {\n result[key] = value\n }\n }\n\n return result\n}\n\n/**\n * Transforms an object to query string\n * @param queryObject - query object to stringify\n * @returns query string without the leading `?`\n */\nexport function stringifyQuery (queryObject: LocationQueryObject): string {\n let result = ''\n\n for (const key in queryObject) {\n const value = queryObject[key]\n if (isNull(value)) {\n result += (result.length ? '&' : '') + key\n } else {\n const valueList: LocationQueryValue[] = isArray(value) ? value : [value]\n\n valueList.forEach(value => {\n if (!isUndefined(value)) {\n result += (result.length ? '&' : '') + key\n if (!isNull(value)) result += '=' + value\n }\n })\n }\n }\n\n return result\n}\n\n/**\n * Register or unregister callback/guard with Set\n */\nexport function useSetRecord<T> () {\n const handlers: Set<T> = new Set()\n\n function add (handler: T): () => boolean {\n handlers.add(handler)\n return (): boolean => {\n if (handlers.has(handler)) return handlers.delete(handler)\n return false\n }\n }\n\n return {\n add,\n list: () => handlers,\n }\n}\n\n/**\n * record data with Map\n */\nexport function useMapRecord<T> () {\n const data: Map<PropertyKey, T> = new Map()\n\n function add (key: PropertyKey, value: T): () => boolean {\n data.set(key, value)\n return (): boolean => {\n if (data.has(key)) return data.delete(key)\n return false\n }\n }\n\n return {\n add,\n get: (key: PropertyKey) => data.get(key),\n delete: (key: PropertyKey): boolean => {\n if (data.has(key)) return data.delete(key)\n return false\n }\n }\n}\n\nexport function getAttributes (element: Element): AttrsType {\n const attr = element.attributes\n const attrMap: AttrsType = new Map()\n for (let i = 0; i < attr.length; i++) {\n attrMap.set(attr[i].name, attr[i].value)\n }\n return attrMap\n}\n\n/**\n * if fiberTasks exist, wrap callback with promiseRequestIdle\n * if not, execute callback\n * @param fiberTasks fiber task list\n * @param callback action callback\n */\nexport function injectFiberTask (fiberTasks: fiberTasks, callback: CallableFunction): void {\n if (fiberTasks) {\n fiberTasks.push(() => promiseRequestIdle((resolve: PromiseConstructor['resolve']) => {\n callback()\n resolve()\n }))\n } else {\n callback()\n }\n}\n\n/**\n * serial exec fiber task of link, style, script\n * @param tasks task array or null\n */\nexport function serialExecFiberTasks (tasks: fiberTasks): Promise<void> | null {\n return tasks?.reduce((pre, next) => pre.then(next), Promise.resolve()) || null\n}\n\n/**\n * inline script start with inline-xxx\n * @param address source address\n */\nexport function isInlineScript (address: string): boolean {\n return address.startsWith('inline-')\n}\n\n/**\n * call function with try catch\n * @param fn target function\n * @param appName app.name\n * @param args arguments\n */\nexport function execMicroAppGlobalHook (\n fn: Func | null,\n appName: string,\n hookName: string,\n ...args: unknown[]\n): void {\n try {\n isFunction(fn) && fn(...args)\n } catch (e) {\n logError(`An error occurred in app ${appName} window.${hookName} \\n`, null, e)\n }\n}\n\n/**\n * remove all childNode from target node\n * @param $dom target node\n */\nexport function clearDOM ($dom: HTMLElement | ShadowRoot | Document): void {\n while ($dom?.firstChild) {\n $dom.removeChild($dom.firstChild)\n }\n}\n\ntype BaseHTMLElementType = HTMLElement & {\n new (): HTMLElement;\n prototype: HTMLElement;\n}\n\n/**\n * get HTMLElement from base app\n * @returns HTMLElement\n */\nexport function getBaseHTMLElement (): BaseHTMLElementType {\n return (window.rawWindow?.HTMLElement || window.HTMLElement) as BaseHTMLElementType\n}\n","import type { lifeCyclesType, AppInterface } from '@micro-app/types'\nimport microApp from '../micro_app'\nimport { logError, isFunction, removeDomScope, getRootContainer, assign } from '../libs/utils'\n\nfunction formatEventInfo (event: CustomEvent, element: HTMLElement): void {\n Object.defineProperties(event, {\n currentTarget: {\n get () {\n return element\n }\n },\n target: {\n get () {\n return element\n }\n },\n })\n}\n\ntype LifecycleEventName = keyof lifeCyclesType\n\n/**\n * dispatch lifeCycles event to base app\n * created, beforemount, mounted, unmount, error\n * @param element container\n * @param appName app.name\n * @param lifecycleName lifeCycle name\n * @param error param from error hook\n */\nexport default function dispatchLifecyclesEvent (\n element: HTMLElement | ShadowRoot,\n appName: string,\n lifecycleName: LifecycleEventName,\n error?: Error,\n): void {\n if (!element) {\n return logError(`element does not exist in lifecycle ${lifecycleName}`, appName)\n }\n\n element = getRootContainer(element)\n\n // clear dom scope before dispatch lifeCycles event to base app, especially mounted & unmount\n removeDomScope()\n\n const detail = assign({\n name: appName,\n container: element,\n }, error && {\n error\n })\n\n const event = new CustomEvent(lifecycleName, {\n detail,\n })\n\n formatEventInfo(event, element)\n // global hooks\n if (isFunction(microApp.options.lifeCycles?.[lifecycleName])) {\n microApp.options.lifeCycles![lifecycleName]!(event)\n }\n\n element.dispatchEvent(event)\n}\n\n/**\n * Dispatch custom event to micro app\n * @param app app\n * @param eventName event name ['unmount', 'appstate-change']\n * @param detail event detail\n */\nexport function dispatchCustomEventToMicroApp (\n app: AppInterface,\n eventName: string,\n detail: Record<string, any> = {},\n): void {\n const event = new CustomEvent(eventName, {\n detail,\n })\n\n app.sandBox?.microAppWindow.dispatchEvent(event)\n}\n","import { isFunction, removeDomScope } from '../libs/utils'\nimport microApp from '../micro_app'\n\n/**\n * fetch source of html, js, css\n * @param url source path\n * @param appName app name\n * @param config fetch options\n */\nexport function fetchSource (url: string, appName: string | null = null, options = {}): Promise<string> {\n /**\n * When child navigate to new async page, click event will scope dom to child and then fetch new source\n * this may cause error when fetch rewrite by baseApp\n * e.g.\n * baseApp: <script crossorigin src=\"https://sgm-static.jd.com/sgm-2.8.0.js\" name=\"SGMH5\" sid=\"6f88a6e4ba4b4ae5acef2ec22c075085\" appKey=\"jdb-adminb2b-pc\"></script>\n */\n removeDomScope()\n if (isFunction(microApp.options.fetch)) {\n return microApp.options.fetch(url, options, appName)\n }\n // Don’t use globalEnv.rawWindow.fetch, will cause sgm-2.8.0.js throw error in nest app\n return window.fetch(url, options).then((res: Response) => {\n return res.text()\n })\n}\n","import { AppInterface, plugins } from '@micro-app/types'\nimport { fetchSource } from '../fetch'\nimport { isFunction, isPlainObject, logError } from '../../libs/utils'\nimport microApp from '../../micro_app'\n\nexport interface IHTMLLoader {\n run (app: AppInterface, successCb: CallableFunction): void\n}\n\nexport class HTMLLoader implements IHTMLLoader {\n private static instance: HTMLLoader;\n public static getInstance (): HTMLLoader {\n if (!this.instance) {\n this.instance = new HTMLLoader()\n }\n return this.instance\n }\n\n /**\n * run logic of load and format html\n * @param successCb success callback\n * @param errorCb error callback, type: (err: Error, meetFetchErr: boolean) => void\n */\n public run (app: AppInterface, successCb: CallableFunction): void {\n const appName = app.name\n const htmlUrl = app.ssrUrl || app.url\n const htmlPromise = htmlUrl.includes('.js')\n ? Promise.resolve(`<micro-app-head><script src='${htmlUrl}'></script></micro-app-head><micro-app-body></micro-app-body>`)\n : fetchSource(htmlUrl, appName, { cache: 'no-cache' })\n htmlPromise.then((htmlStr: string) => {\n if (!htmlStr) {\n const msg = 'html is empty, please check in detail'\n app.onerror(new Error(msg))\n return logError(msg, appName)\n }\n\n htmlStr = this.formatHTML(htmlUrl, htmlStr, appName)\n\n successCb(htmlStr, app)\n }).catch((e) => {\n logError(`Failed to fetch data from ${app.url}, micro-app stop rendering`, appName, e)\n app.onLoadError(e)\n })\n }\n\n private formatHTML (htmlUrl: string, htmlStr: string, appName: string) {\n return this.processHtml(htmlUrl, htmlStr, appName, microApp.options.plugins)\n .replace(/<head[^>]*>[\\s\\S]*?<\\/head>/i, (match) => {\n return match\n .replace(/<head/i, '<micro-app-head')\n .replace(/<\\/head>/i, '</micro-app-head>')\n })\n .replace(/<body[^>]*>[\\s\\S]*?<\\/body>/i, (match) => {\n return match\n .replace(/<body/i, '<micro-app-body')\n .replace(/<\\/body>/i, '</micro-app-body>')\n })\n }\n\n private processHtml (url: string, code: string, appName: string, plugins: plugins | void): string {\n if (!plugins) return code\n\n const mergedPlugins: NonNullable<plugins['global']> = []\n plugins.global && mergedPlugins.push(...plugins.global)\n plugins.modules?.[appName] && mergedPlugins.push(...plugins.modules[appName])\n\n if (mergedPlugins.length > 0) {\n return mergedPlugins.reduce((preCode, plugin) => {\n if (isPlainObject(plugin) && isFunction(plugin.processHtml)) {\n return plugin.processHtml!(preCode, url)\n }\n return preCode\n }, code)\n }\n return code\n }\n}\n","/* eslint-disable no-useless-escape, no-cond-assign */\nimport type { AppInterface } from '@micro-app/types'\nimport { CompletionPath, getLinkFileDir, logError, trim, isFireFox } from '../libs/utils'\nimport microApp from '../micro_app'\n\n// common reg\nconst rootSelectorREG = /(^|\\s+)(html|:root)(?=[\\s>~[.#:]+|$)/\nconst bodySelectorREG = /(^|\\s+)((html[\\s>~]+body)|body)(?=[\\s>~[.#:]+|$)/\n\ntype parseErrorType = Error & { reason: string, filename?: string }\nfunction parseError (msg: string, linkPath?: string): void {\n msg = linkPath ? `${linkPath} ${msg}` : msg\n const err = new Error(msg) as parseErrorType\n err.reason = msg\n if (linkPath) {\n err.filename = linkPath\n }\n\n throw err\n}\n\n/**\n * Reference https://github.com/reworkcss/css\n * CSSParser mainly deals with 3 scenes: styleRule, @, and comment\n * And scopecss deals with 2 scenes: selector & url\n * And can also disable scopecss with inline comments\n */\nclass CSSParser {\n private cssText = '' // css content\n private prefix = '' // prefix as micro-app[name=xxx]\n private baseURI = '' // domain name\n private linkPath = '' // link resource address, if it is the style converted from link, it will have linkPath\n private result = '' // parsed cssText\n private scopecssDisable = false // use block comments /* scopecss-disable */ to disable scopecss in your file, and use /* scopecss-enable */ to enable scopecss\n private scopecssDisableSelectors: Array<string> = [] // disable or enable scopecss for specific selectors\n private scopecssDisableNextLine = false // use block comments /* scopecss-disable-next-line */ to disable scopecss on a specific line\n\n public exec (\n cssText: string,\n prefix: string,\n baseURI: string,\n linkPath?: string,\n ): string {\n this.cssText = cssText\n this.prefix = prefix\n this.baseURI = baseURI\n this.linkPath = linkPath || ''\n this.matchRules()\n return isFireFox() ? decodeURIComponent(this.result) : this.result\n }\n\n public reset (): void {\n this.cssText = this.prefix = this.baseURI = this.linkPath = this.result = ''\n this.scopecssDisable = this.scopecssDisableNextLine = false\n this.scopecssDisableSelectors = []\n }\n\n // core action for match rules\n private matchRules (): void {\n this.matchLeadingSpaces()\n this.matchComments()\n while (\n this.cssText.length &&\n this.cssText.charAt(0) !== '}' &&\n (this.matchAtRule() || this.matchStyleRule())\n ) {\n this.matchComments()\n }\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule\n private matchStyleRule (): boolean | void {\n const selectors = this.formatSelector(true)\n\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n\n if (!selectors) return parseError('selector missing', this.linkPath)\n\n this.recordResult(selectors)\n\n this.matchComments()\n\n this.styleDeclarations()\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n private formatSelector (skip: boolean): false | string {\n const m = this.commonMatch(/^[^{]+/, skip)\n if (!m) return false\n\n return m[0].replace(/(^|,[\\n\\s]*)([^,]+)/g, (_, separator, selector) => {\n selector = trim(selector)\n if (!(\n this.scopecssDisableNextLine ||\n (\n this.scopecssDisable && (\n !this.scopecssDisableSelectors.length ||\n this.scopecssDisableSelectors.includes(selector)\n )\n ) ||\n rootSelectorREG.test(selector)\n )) {\n if (bodySelectorREG.test(selector)) {\n selector = selector.replace(bodySelectorREG, this.prefix + ' micro-app-body')\n } else {\n selector = this.prefix + ' ' + selector\n }\n }\n\n return separator + selector\n })\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration\n private styleDeclarations (): boolean | void {\n if (!this.matchOpenBrace()) return parseError(\"Declaration missing '{'\", this.linkPath)\n\n this.matchAllDeclarations()\n\n if (!this.matchCloseBrace()) return parseError(\"Declaration missing '}'\", this.linkPath)\n\n return true\n }\n\n private matchAllDeclarations (nesting = 1): void {\n let cssValue = (this.commonMatch(/^(?:url\\([\"']?(?:[^)\"'}]+)[\"']?\\)|[^{}/])*/, true) as RegExpExecArray)[0]\n\n if (cssValue) {\n if (\n !this.scopecssDisableNextLine &&\n (!this.scopecssDisable || this.scopecssDisableSelectors.length)\n ) {\n cssValue = cssValue.replace(/url\\([\"']?([^)\"']+)[\"']?\\)/gm, (all, $1) => {\n if (/^((data|blob):|#)/.test($1) || /^(https?:)?\\/\\//.test($1)) {\n return all\n }\n\n // ./a/b.png ../a/b.png a/b.png\n if (/^((\\.\\.?\\/)|[^/])/.test($1) && this.linkPath) {\n this.baseURI = getLinkFileDir(this.linkPath)\n }\n\n return `url(\"${CompletionPath($1, this.baseURI)}\")`\n })\n }\n\n this.recordResult(cssValue)\n }\n\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n\n if (!this.cssText) return\n\n if (this.cssText.charAt(0) === '}') {\n if (!nesting) return\n if (nesting > 1) {\n this.commonMatch(/}+/)\n }\n return this.matchAllDeclarations(nesting - 1)\n }\n\n // extract comments in declarations\n if (this.cssText.charAt(0) === '/') {\n if (this.cssText.charAt(1) === '*') {\n this.matchComments()\n } else {\n this.commonMatch(/\\/+/)\n }\n }\n\n if (this.cssText.charAt(0) === '{') {\n this.commonMatch(/{+\\s*/)\n nesting++\n }\n\n return this.matchAllDeclarations(nesting)\n }\n\n private matchAtRule (): boolean | void {\n if (this.cssText[0] !== '@') return false\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n return this.keyframesRule() ||\n this.mediaRule() ||\n this.customMediaRule() ||\n this.supportsRule() ||\n this.importRule() ||\n this.charsetRule() ||\n this.namespaceRule() ||\n this.containerRule() ||\n this.documentRule() ||\n this.pageRule() ||\n this.hostRule() ||\n this.fontFaceRule()\n }\n\n // :global is CSS Modules rule, it will be converted to normal syntax\n // private matchGlobalRule (): boolean | void {\n // if (this.cssText[0] !== ':') return false\n // // reset scopecssDisableNextLine\n // this.scopecssDisableNextLine = false\n\n // return this.globalRule()\n // }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframesRule\n private keyframesRule (): boolean | void {\n if (!this.commonMatch(/^@([-\\w]+)?keyframes\\s*/)) return false\n\n if (!this.commonMatch(/^[^{]+/)) return parseError('@keyframes missing name', this.linkPath)\n\n this.matchComments()\n\n if (!this.matchOpenBrace()) return parseError(\"@keyframes missing '{'\", this.linkPath)\n\n this.matchComments()\n while (this.keyframeRule()) {\n this.matchComments()\n }\n\n if (!this.matchCloseBrace()) return parseError(\"@keyframes missing '}'\", this.linkPath)\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n private keyframeRule (): boolean {\n let r; const valList = []\n\n while (r = this.commonMatch(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/)) {\n valList.push(r[1])\n this.commonMatch(/^,\\s*/)\n }\n\n if (!valList.length) return false\n\n this.styleDeclarations()\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n // https://github.com/postcss/postcss-custom-media\n private customMediaRule (): boolean {\n if (!this.commonMatch(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/)) return false\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSPageRule\n private pageRule (): boolean | void {\n if (!this.commonMatch(/^@page */)) return false\n\n this.formatSelector(false)\n\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n\n return this.commonHandlerForAtRuleWithSelfRule('page')\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSFontFaceRule\n private fontFaceRule (): boolean | void {\n if (!this.commonMatch(/^@font-face\\s*/)) return false\n\n return this.commonHandlerForAtRuleWithSelfRule('font-face')\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSMediaRule\n private mediaRule = this.createMatcherForRuleWithChildRule(/^@media *([^{]+)/, '@media')\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSSupportsRule\n private supportsRule = this.createMatcherForRuleWithChildRule(/^@supports *([^{]+)/, '@supports')\n private documentRule = this.createMatcherForRuleWithChildRule(/^@([-\\w]+)?document *([^{]+)/, '@document')\n private hostRule = this.createMatcherForRuleWithChildRule(/^@host\\s*/, '@host')\n // :global is CSS Modules rule, it will be converted to normal syntax\n // private globalRule = this.createMatcherForRuleWithChildRule(/^:global([^{]*)/, ':global')\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSImportRule\n private importRule = this.createMatcherForNoneBraceAtRule('import')\n // Removed in most browsers\n private charsetRule = this.createMatcherForNoneBraceAtRule('charset')\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSNamespaceRule\n private namespaceRule = this.createMatcherForNoneBraceAtRule('namespace')\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@container\n private containerRule = this.createMatcherForRuleWithChildRule(/^@container *([^{]+)/, '@container')\n\n // common matcher for @media, @supports, @document, @host, :global, @container\n private createMatcherForRuleWithChildRule (reg: RegExp, name: string): () => boolean | void {\n return () => {\n if (!this.commonMatch(reg)) return false\n\n if (!this.matchOpenBrace()) return parseError(`${name} missing '{'`, this.linkPath)\n\n this.matchComments()\n\n this.matchRules()\n\n if (!this.matchCloseBrace()) return parseError(`${name} missing '}'`, this.linkPath)\n\n this.matchLeadingSpaces()\n\n return true\n }\n }\n\n // common matcher for @import, @charset, @namespace\n private createMatcherForNoneBraceAtRule (name: string): () => boolean {\n const reg = new RegExp('^@' + name + '\\\\s*([^;]+);')\n return () => {\n if (!this.commonMatch(reg)) return false\n this.matchLeadingSpaces()\n return true\n }\n }\n\n // common handler for @font-face, @page\n private commonHandlerForAtRuleWithSelfRule (name: string): boolean | void {\n if (!this.matchOpenBrace()) return parseError(`@${name} missing '{'`, this.linkPath)\n\n this.matchAllDeclarations()\n\n if (!this.matchCloseBrace()) return parseError(`@${name} missing '}'`, this.linkPath)\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n // match and slice comments\n private matchComments (): void {\n while (this.matchComment());\n }\n\n // css comment\n private matchComment (): boolean | void {\n if (this.cssText.charAt(0) !== '/' || this.cssText.charAt(1) !== '*') return false\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n\n let i = 2\n while (this.cssText.charAt(i) !== '' && (this.cssText.charAt(i) !== '*' || this.cssText.charAt(i + 1) !== '/')) ++i\n i += 2\n\n if (this.cssText.charAt(i - 1) === '') {\n return parseError('End of comment missing', this.linkPath)\n }\n\n // get comment content\n let commentText = this.cssText.slice(2, i - 2)\n\n this.recordResult(`/*${commentText}*/`)\n\n commentText = trim(commentText.replace(/^\\s*!/, ''))\n\n // set ignore config\n if (commentText === 'scopecss-disable-next-line') {\n this.scopecssDisableNextLine = true\n } else if (/^scopecss-disable/.test(commentText)) {\n if (commentText === 'scopecss-disable') {\n this.scopecssDisable = true\n } else {\n this.scopecssDisable = true\n const ignoreRules = commentText.replace('scopecss-disable', '').split(',')\n ignoreRules.forEach((rule: string) => {\n this.scopecssDisableSelectors.push(trim(rule))\n })\n }\n } else if (commentText === 'scopecss-enable') {\n this.scopecssDisable = false\n this.scopecssDisableSelectors = []\n }\n\n this.cssText = this.cssText.slice(i)\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n private commonMatch (reg: RegExp, skip = false): RegExpExecArray | null | void {\n const matchArray = reg.exec(this.cssText)\n if (!matchArray) return\n const matchStr = matchArray[0]\n this.cssText = this.cssText.slice(matchStr.length)\n if (!skip) this.recordResult(matchStr)\n return matchArray\n }\n\n private matchOpenBrace () {\n return this.commonMatch(/^{\\s*/)\n }\n\n private matchCloseBrace () {\n return this.commonMatch(/^}/)\n }\n\n // match and slice the leading spaces\n private matchLeadingSpaces (): void {\n this.commonMatch(/^\\s*/)\n }\n\n // splice string\n private recordResult (strFragment: string): void {\n // Firefox performance degradation when string contain special characters, see https://github.com/micro-zoe/micro-app/issues/256\n if (isFireFox()) {\n this.result += encodeURIComponent(strFragment)\n } else {\n this.result += strFragment\n }\n }\n}\n\n/**\n * common method of bind CSS\n */\nfunction commonAction (\n styleElement: HTMLStyleElement,\n appName: string,\n prefix: string,\n baseURI: string,\n linkPath?: string,\n) {\n if (!styleElement.__MICRO_APP_HAS_SCOPED__) {\n styleElement.__MICRO_APP_HAS_SCOPED__ = true\n let result: string | null = null\n try {\n result = parser.exec(\n styleElement.textContent!,\n prefix,\n baseURI,\n linkPath,\n )\n parser.reset()\n } catch (e) {\n parser.reset()\n logError('An error occurred while parsing CSS:\\n', appName, e)\n }\n\n if (result) styleElement.textContent = result\n }\n}\n\nlet parser: CSSParser\n/**\n * scopedCSS\n * @param styleElement target style element\n * @param appName app name\n */\nexport default function scopedCSS (\n styleElement: HTMLStyleElement,\n app: AppInterface,\n linkPath?: string,\n): HTMLStyleElement {\n if (app.scopecss) {\n const prefix = createPrefix(app.name)\n\n if (!parser) parser = new CSSParser()\n\n if (styleElement.textContent) {\n commonAction(\n styleElement,\n app.name,\n prefix,\n app.url,\n linkPath,\n )\n } else {\n const observer = new MutationObserver(function () {\n observer.disconnect()\n // styled-component will be ignore\n if (styleElement.textContent && !styleElement.hasAttribute('data-styled')) {\n commonAction(\n styleElement,\n app.name,\n prefix,\n app.url,\n linkPath,\n )\n }\n })\n\n observer.observe(styleElement, { childList: true })\n }\n }\n\n return styleElement\n}\n\nexport function createPrefix (appName: string, reg = false): string {\n const regCharacter = reg ? '\\\\' : ''\n return `${microApp.tagName}${regCharacter}[name=${appName}${regCharacter}]`\n}\n","import { isFunction } from '../libs/utils'\n\nfunction eventHandler (event: Event, element: HTMLLinkElement | HTMLScriptElement): void {\n Object.defineProperties(event, {\n currentTarget: {\n get () {\n return element\n }\n },\n srcElement: {\n get () {\n return element\n }\n },\n target: {\n get () {\n return element\n }\n },\n })\n}\n\nexport function dispatchOnLoadEvent (element: HTMLLinkElement | HTMLScriptElement): void {\n const event = new CustomEvent('load')\n eventHandler(event, element)\n if (isFunction(element.onload)) {\n element.onload!(event)\n } else {\n element.dispatchEvent(event)\n }\n}\n\nexport function dispatchOnErrorEvent (element: HTMLLinkElement | HTMLScriptElement): void {\n const event = new CustomEvent('error')\n eventHandler(event, element)\n if (isFunction(element.onerror)) {\n element.onerror!(event)\n } else {\n element.dispatchEvent(event)\n }\n}\n","export enum ObservedAttrName {\n NAME = 'name',\n URL = 'url',\n}\n\n// app status\nexport enum appStates {\n CREATED = 'created',\n LOADING = 'loading',\n LOAD_FAILED = 'load_failed',\n BEFORE_MOUNT = 'before_mount',\n MOUNTING = 'mounting',\n MOUNTED = 'mounted',\n UNMOUNT = 'unmount',\n}\n\n// lifecycles\nexport enum lifeCycles {\n CREATED = 'created',\n BEFOREMOUNT = 'beforemount',\n MOUNTED = 'mounted',\n UNMOUNT = 'unmount',\n ERROR = 'error',\n // 👇 keep-alive only\n BEFORESHOW = 'beforeshow',\n AFTERSHOW = 'aftershow',\n AFTERHIDDEN = 'afterhidden',\n}\n\n// global event of child app\nexport enum microGlobalEvent {\n ONMOUNT = 'onmount',\n ONUNMOUNT = 'onunmount',\n}\n\n// keep-alive status\nexport enum keepAliveStates {\n KEEP_ALIVE_SHOW = 'keep_alive_show',\n KEEP_ALIVE_HIDDEN = 'keep_alive_hidden',\n}\n\n// micro-app config\nexport enum MicroAppConfig {\n DESTROY = 'destroy',\n DESTORY = 'destory',\n INLINE = 'inline',\n DISABLESCOPECSS = 'disableScopecss',\n DISABLESANDBOX = 'disableSandbox',\n DISABLE_SCOPECSS = 'disable-scopecss',\n DISABLE_SANDBOX = 'disable-sandbox',\n DISABLE_MEMORY_ROUTER = 'disable-memory-router',\n DISABLE_PATCH_REQUEST = 'disable-patch-request',\n KEEP_ROUTER_STATE = 'keep-router-state',\n HIDDEN_ROUTER = 'hidden-router',\n KEEP_ALIVE = 'keep-alive',\n CLEAR_DATA ='clear-data',\n SSR = 'ssr',\n FIBER = 'fiber',\n}\n\n// prefetch level\nexport const PREFETCH_LEVEL: number[] = [1, 2, 3]\n\n// memory router constants\nexport const DEFAULT_ROUTER_MODE = 'search'\nexport const ROUTER_MODE_HISTORY = 'history'\nexport const ROUTER_MODE_CUSTOM = 'custom'\nexport const ROUTER_MODE_LIST: string[] = [\n DEFAULT_ROUTER_MODE,\n ROUTER_MODE_HISTORY,\n ROUTER_MODE_CUSTOM,\n]\n\n// event bound to child app window\nexport const SCOPE_WINDOW_EVENT = [\n 'popstate',\n 'hashchange',\n 'load',\n 'beforeunload',\n 'unload',\n 'unmount',\n 'appstate-change',\n 'statechange',\n 'mounted',\n]\n\n// on event bound to child app window\nexport const SCOPE_WINDOW_ON_EVENT = [\n 'onpopstate',\n 'onhashchange',\n 'onload',\n 'onbeforeunload',\n 'onunload',\n 'onerror'\n]\n\n// event bound to child app document\nexport const SCOPE_DOCUMENT_EVENT = [\n 'DOMContentLoaded',\n 'readystatechange',\n]\n\n// on event bound to child app document\nexport const SCOPE_DOCUMENT_ON_EVENT = [\n 'onreadystatechange',\n]\n\n// global key point to window\nexport const GLOBAL_KEY_TO_WINDOW: Array<PropertyKey> = [\n 'window',\n 'self',\n 'globalThis',\n]\n\nexport const RAW_GLOBAL_TARGET: Array<PropertyKey> = ['rawWindow', 'rawDocument']\n\n/**\n * global key must be static key, they can not rewrite\n * e.g.\n * window.Promise = newValue\n * new Promise ==> still get old value, not newValue, because they are cached by top function\n * NOTE:\n * 1. Do not add fetch, XMLHttpRequest, EventSource\n */\nexport const GLOBAL_CACHED_KEY = 'window,self,globalThis,document,Document,Array,Object,String,Boolean,Math,Number,Symbol,Date,Function,Proxy,WeakMap,WeakSet,Set,Map,Reflect,Element,Node,RegExp,Error,TypeError,JSON,isNaN,parseFloat,parseInt,performance,console,decodeURI,encodeURI,decodeURIComponent,encodeURIComponent,navigator,undefined,location,history'\n","import type { LinkSourceInfo, ScriptSourceInfo, SourceAddress } from '@micro-app/types'\nimport { isInlineScript } from '../libs/utils'\n\nexport interface SourceCenter<L = LinkSourceInfo, S = ScriptSourceInfo> {\n link: {\n setInfo (address: SourceAddress, info: L): void,\n getInfo (address: SourceAddress): L | null,\n hasInfo (address: SourceAddress): boolean,\n deleteInfo (address: SourceAddress): boolean,\n },\n script: {\n setInfo (address: SourceAddress, info: S): void,\n getInfo (address: SourceAddress): S | null,\n hasInfo (address: SourceAddress): boolean,\n deleteInfo (address: SourceAddress): boolean,\n deleteInlineInfo (addressList: Set<SourceAddress>): void,\n }\n}\n\nexport type LinkListType = Map<SourceAddress, LinkSourceInfo>\nexport type ScriptListType = Map<SourceAddress, ScriptSourceInfo>\n\n/**\n * SourceCenter is a resource management center\n * All html, js, css will be recorded and processed here\n * NOTE:\n * 1. All resources are global and shared between apps\n * 2. Pay attention to the case of html with parameters\n * 3. The resource is first processed by the plugin\n */\nfunction createSourceCenter (): SourceCenter {\n const linkList: LinkListType = new Map()\n const scriptList: ScriptListType = new Map()\n\n function createSourceHandler <P, T extends Map<SourceAddress, P>> (targetList: T): SourceCenter<P>['link'] | SourceCenter<LinkSourceInfo, P>['script'] {\n return {\n setInfo (address: SourceAddress, info: P): void {\n targetList.set(address, info)\n },\n getInfo (address: SourceAddress): P | null {\n return targetList.get(address) ?? null\n },\n hasInfo (address: SourceAddress): boolean {\n return targetList.has(address)\n },\n deleteInfo (address: SourceAddress): boolean {\n return targetList.delete(address)\n }\n }\n }\n\n return {\n link: createSourceHandler<LinkSourceInfo, LinkListType>(linkList),\n script: {\n ...createSourceHandler<ScriptSourceInfo, ScriptListType>(scriptList),\n deleteInlineInfo (addressList: Set<SourceAddress>): void {\n addressList.forEach((address) => {\n if (isInlineScript(address)) {\n scriptList.delete(address)\n }\n })\n }\n },\n }\n}\n\nexport default createSourceCenter()\n","import type {\n AppInterface,\n LinkSourceInfo,\n AttrsType,\n fiberTasks,\n} from '@micro-app/types'\nimport { fetchSource } from './fetch'\nimport {\n CompletionPath,\n promiseStream,\n pureCreateElement,\n defer,\n logError,\n getAttributes,\n injectFiberTask,\n serialExecFiberTasks,\n} from '../libs/utils'\nimport scopedCSS, { createPrefix } from '../sandbox/scoped_css'\nimport {\n dispatchOnLoadEvent,\n dispatchOnErrorEvent,\n} from './load_event'\nimport sourceCenter from './source_center'\nimport globalEnv from '../libs/global_env'\n\n/**\n *\n * @param appName app.name\n * @param linkInfo linkInfo of current address\n */\nfunction getExistParseCode (\n appName: string,\n prefix: string,\n linkInfo: LinkSourceInfo,\n): string | void {\n const appSpace = linkInfo.appSpace\n for (const item in appSpace) {\n if (item !== appName) {\n const appSpaceData = appSpace[item]\n if (appSpaceData.parsedCode) {\n return appSpaceData.parsedCode.replace(new RegExp(createPrefix(item, true), 'g'), prefix)\n }\n }\n }\n}\n\n// transfer the attributes on the link to convertStyle\nfunction setConvertStyleAttr (convertStyle: HTMLStyleElement, attrs: AttrsType): void {\n attrs.forEach((value, key) => {\n if (key === 'rel') return\n if (key === 'href') key = 'data-origin-href'\n globalEnv.rawSetAttribute.call(convertStyle, key, value)\n })\n}\n\n/**\n * Extract link elements\n * @param link link element\n * @param parent parent element of link\n * @param app app\n * @param microAppHead micro-app-head element\n * @param isDynamic dynamic insert\n */\nexport function extractLinkFromHtml (\n link: HTMLLinkElement,\n parent: Node | null,\n app: AppInterface,\n isDynamic = false,\n): any {\n const rel = link.getAttribute('rel')\n let href = link.getAttribute('href')\n let replaceComment: Comment | null = null\n if (rel === 'stylesheet' && href) {\n href = CompletionPath(href, app.url)\n let linkInfo = sourceCenter.link.getInfo(href)\n const appSpaceData = {\n attrs: getAttributes(link),\n }\n if (!linkInfo) {\n linkInfo = {\n code: '',\n appSpace: {\n [app.name]: appSpaceData,\n }\n }\n } else {\n linkInfo.appSpace[app.name] = linkInfo.appSpace[app.name] || appSpaceData\n }\n\n sourceCenter.link.setInfo(href, linkInfo)\n\n if (!isDynamic) {\n app.source.links.add(href)\n replaceComment = document.createComment(`link element with href=${href} move to micro-app-head as style element`)\n linkInfo.appSpace[app.name].placeholder = replaceComment\n } else {\n return { address: href, linkInfo }\n }\n } else if (rel && ['prefetch', 'preload', 'prerender'].includes(rel)) {\n // preload prefetch prerender ....\n if (isDynamic) {\n replaceComment = document.createComment(`link element with rel=${rel}${href ? ' & href=' + href : ''} removed by micro-app`)\n } else {\n parent?.removeChild(link)\n }\n } else if (href) {\n // dns-prefetch preconnect modulepreload search ....\n globalEnv.rawSetAttribute.call(link, 'href', CompletionPath(href, app.url))\n }\n\n if (isDynamic) {\n return { replaceComment }\n } else if (replaceComment) {\n return parent?.replaceChild(replaceComment, link)\n }\n}\n\n/**\n * Get link remote resources\n * @param wrapElement htmlDom\n * @param app app\n * @param microAppHead micro-app-head\n */\nexport function fetchLinksFromHtml (\n wrapElement: HTMLElement,\n app: AppInterface,\n microAppHead: Element,\n fiberStyleResult: Promise<void> | null,\n): void {\n const styleList: Array<string> = Array.from(app.source.links)\n const fetchLinkPromise: Array<Promise<string> | string> = styleList.map((address) => {\n const linkInfo = sourceCenter.link.getInfo(address)!\n return linkInfo.code ? linkInfo.code : fetchSource(address, app.name)\n })\n\n const fiberLinkTasks: fiberTasks = fiberStyleResult ? [] : null\n\n promiseStream<string>(fetchLinkPromise, (res: { data: string, index: number }) => {\n injectFiberTask(fiberLinkTasks, () => fetchLinkSuccess(\n styleList[res.index],\n res.data,\n microAppHead,\n app,\n ))\n }, (err: {error: Error, index: number}) => {\n logError(err, app.name)\n }, () => {\n /**\n * 1. If fiberStyleResult exist, fiberLinkTasks must exist\n * 2. Download link source while processing style\n * 3. Process style first, and then process link\n */\n if (fiberStyleResult) {\n fiberStyleResult.then(() => {\n fiberLinkTasks!.push(() => Promise.resolve(app.onLoad(wrapElement)))\n serialExecFiberTasks(fiberLinkTasks)\n })\n } else {\n app.onLoad(wrapElement)\n }\n })\n}\n\n/**\n * Fetch link succeeded, replace placeholder with style tag\n * NOTE:\n * 1. Only exec when init, no longer exec when remount\n * 2. Only handler html link element, not dynamic link or style\n * 3. The same prefix can reuse parsedCode\n * 4. Async exec with requestIdleCallback in prefetch or fiber\n * 5. appSpace[app.name].placeholder/attrs must exist\n * @param address resource address\n * @param code link source code\n * @param microAppHead micro-app-head\n * @param app app instance\n */\nexport function fetchLinkSuccess (\n address: string,\n code: string,\n microAppHead: Element,\n app: AppInterface,\n): void {\n /**\n * linkInfo must exist, but linkInfo.code not\n * so we set code to linkInfo.code\n */\n const linkInfo = sourceCenter.link.getInfo(address)!\n linkInfo.code = code\n const appSpaceData = linkInfo.appSpace[app.name]\n const placeholder = appSpaceData.placeholder!\n /**\n * When prefetch app is replaced by a new app in the processing phase, since the linkInfo is common, when the linkInfo of the prefetch app is processed, it may have already been processed.\n * This causes placeholder to be possibly null\n * e.g.\n * 1. prefetch app.url different from <micro-app></micro-app>\n * 2. prefetch param different from <micro-app></micro-app>\n */\n if (placeholder) {\n const convertStyle = pureCreateElement('style')\n\n handleConvertStyle(\n app,\n address,\n convertStyle,\n linkInfo,\n appSpaceData.attrs,\n )\n\n if (placeholder.parentNode) {\n placeholder.parentNode.replaceChild(convertStyle, placeholder)\n } else {\n microAppHead.appendChild(convertStyle)\n }\n\n // clear placeholder\n appSpaceData.placeholder = null\n }\n}\n\n/**\n * Get parsedCode, update convertStyle\n * Actions:\n * 1. get scope css (through scopedCSS or oldData)\n * 2. record parsedCode\n * 3. set parsedCode to convertStyle if need\n * @param app app instance\n * @param address resource address\n * @param convertStyle converted style\n * @param linkInfo linkInfo in sourceCenter\n * @param attrs attrs of link\n */\nexport function handleConvertStyle (\n app: AppInterface,\n address: string,\n convertStyle: HTMLStyleElement,\n linkInfo: LinkSourceInfo,\n attrs: AttrsType,\n): void {\n if (app.scopecss) {\n const appSpaceData = linkInfo.appSpace[app.name]\n appSpaceData.prefix = appSpaceData.prefix || createPrefix(app.name)\n if (!appSpaceData.parsedCode) {\n const existParsedCode = getExistParseCode(app.name, appSpaceData.prefix, linkInfo)\n if (!existParsedCode) {\n convertStyle.textContent = linkInfo.code\n scopedCSS(convertStyle, app, address)\n } else {\n convertStyle.textContent = existParsedCode\n }\n appSpaceData.parsedCode = convertStyle.textContent\n } else {\n convertStyle.textContent = appSpaceData.parsedCode\n }\n } else {\n convertStyle.textContent = linkInfo.code\n }\n\n setConvertStyleAttr(convertStyle, attrs)\n}\n\n/**\n * Handle css of dynamic link\n * @param address link address\n * @param app app\n * @param linkInfo linkInfo\n * @param originLink origin link element\n */\nexport function formatDynamicLink (\n address: string,\n app: AppInterface,\n linkInfo: LinkSourceInfo,\n originLink: HTMLLinkElement,\n): HTMLStyleElement {\n const convertStyle = pureCreateElement('style')\n\n const handleDynamicLink = () => {\n handleConvertStyle(\n app,\n address,\n convertStyle,\n linkInfo,\n linkInfo.appSpace[app.name].attrs,\n )\n dispatchOnLoadEvent(originLink)\n }\n\n if (linkInfo.code) {\n defer(handleDynamicLink)\n } else {\n fetchSource(address, app.name).then((data: string) => {\n linkInfo.code = data\n handleDynamicLink()\n }).catch((err) => {\n logError(err, app.name)\n dispatchOnErrorEvent(originLink)\n })\n }\n\n return convertStyle\n}\n","/* eslint-disable node/no-callback-literal, no-void */\nimport type {\n AppInterface,\n ScriptSourceInfo,\n plugins,\n Func,\n fiberTasks,\n AttrsType,\n microAppWindowType,\n} from '@micro-app/types'\nimport { fetchSource } from './fetch'\nimport {\n CompletionPath,\n promiseStream,\n createNonceSrc,\n pureCreateElement,\n defer,\n logError,\n isUndefined,\n isPlainObject,\n isArray,\n isFunction,\n getAttributes,\n injectFiberTask,\n serialExecFiberTasks,\n isInlineScript,\n isString,\n} from '../libs/utils'\nimport {\n dispatchOnLoadEvent,\n dispatchOnErrorEvent,\n} from './load_event'\nimport microApp from '../micro_app'\nimport globalEnv from '../libs/global_env'\nimport { GLOBAL_CACHED_KEY } from '../constants'\nimport sourceCenter from './source_center'\n\nexport type moduleCallBack = Func & { moduleCount?: number, errorCount?: number }\n\nconst scriptTypes = ['text/javascript', 'text/ecmascript', 'application/javascript', 'application/ecmascript', 'module', 'systemjs-module', 'systemjs-importmap']\n\n// whether use type='module' script\nfunction isTypeModule (app: AppInterface, scriptInfo: ScriptSourceInfo): boolean {\n return scriptInfo.appSpace[app.name].module && (!app.useSandbox || app.iframe)\n}\n\n// special script element\nfunction isSpecialScript (app: AppInterface, scriptInfo: ScriptSourceInfo): boolean {\n const attrs = scriptInfo.appSpace[app.name].attrs\n return attrs.has('id')\n}\n\n/**\n * whether to run js in inline mode\n * scene:\n * 1. inline config for app\n * 2. inline attr in script element\n * 3. module script\n * 4. script with special attr\n */\nfunction isInlineMode (app: AppInterface, scriptInfo: ScriptSourceInfo): boolean {\n return (\n app.inline ||\n scriptInfo.appSpace[app.name].inline ||\n isTypeModule(app, scriptInfo) ||\n isSpecialScript(app, scriptInfo)\n )\n}\n\n// TODO: iframe重新插入window前后不一致,通过iframe Function创建的函数无法复用\nfunction getEffectWindow (app: AppInterface): microAppWindowType {\n return app.iframe ? app.sandBox.microAppWindow : globalEnv.rawWindow\n}\n\n// Convert string code to function\nfunction code2Function (app: AppInterface, code: string): Function {\n const targetWindow = getEffectWindow(app)\n return new targetWindow.Function(code)\n}\n\n/**\n * If the appSpace of the current js address has other app, try to reuse parsedFunction of other app\n * @param appName app.name\n * @param scriptInfo scriptInfo of current address\n * @param currentCode pure code of current address\n */\nfunction getExistParseResult (\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n currentCode: string,\n): Function | void {\n const appSpace = scriptInfo.appSpace\n for (const item in appSpace) {\n if (item !== app.name) {\n const appSpaceData = appSpace[item]\n if (appSpaceData.parsedCode === currentCode && appSpaceData.parsedFunction) {\n return appSpaceData.parsedFunction\n }\n }\n }\n}\n\n/**\n * get parsedFunction from exist data or parsedCode\n * @returns parsedFunction\n */\nfunction getParsedFunction (\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n parsedCode: string,\n): Function {\n return getExistParseResult(app, scriptInfo, parsedCode) || code2Function(app, parsedCode)\n}\n\n// Prevent randomly created strings from repeating\nfunction getUniqueNonceSrc (): string {\n const nonceStr: string = createNonceSrc()\n if (sourceCenter.script.hasInfo(nonceStr)) {\n return getUniqueNonceSrc()\n }\n return nonceStr\n}\n\n// transfer the attributes on the script to convertScript\nfunction setConvertScriptAttr (convertScript: HTMLScriptElement, attrs: AttrsType): void {\n attrs.forEach((value, key) => {\n if ((key === 'type' && value === 'module') || key === 'defer' || key === 'async') return\n if (key === 'src') key = 'data-origin-src'\n globalEnv.rawSetAttribute.call(convertScript, key, value)\n })\n}\n\n// wrap code in sandbox\nfunction isWrapInSandBox (app: AppInterface, scriptInfo: ScriptSourceInfo): boolean {\n return app.useSandbox && !isTypeModule(app, scriptInfo)\n}\n\nfunction getSandboxType (app: AppInterface, scriptInfo: ScriptSourceInfo): 'with' | 'iframe' | 'disable' {\n return isWrapInSandBox(app, scriptInfo) ? app.iframe ? 'iframe' : 'with' : 'disable'\n}\n\n/**\n * Extract script elements\n * @param script script element\n * @param parent parent element of script\n * @param app app\n * @param isDynamic dynamic insert\n */\nexport function extractScriptElement (\n script: HTMLScriptElement,\n parent: Node | null,\n app: AppInterface,\n isDynamic = false,\n): any {\n let replaceComment: Comment | null = null\n let src: string | null = script.getAttribute('src')\n if (src) src = CompletionPath(src, app.url)\n if (script.hasAttribute('exclude') || checkExcludeUrl(src, app.name)) {\n replaceComment = document.createComment('script element with exclude attribute removed by micro-app')\n } else if (\n (\n script.type &&\n !scriptTypes.includes(script.type)\n ) ||\n script.hasAttribute('ignore') ||\n checkIgnoreUrl(src, app.name)\n ) {\n // 配置为忽略的脚本,清空 rawDocument.currentScript,避免被忽略的脚本内获取 currentScript 出错\n if (globalEnv.rawDocument?.currentScript) {\n delete globalEnv.rawDocument.currentScript\n }\n return null\n } else if (\n (globalEnv.supportModuleScript && script.noModule) ||\n (!globalEnv.supportModuleScript && script.type === 'module')\n ) {\n replaceComment = document.createComment(`${script.noModule ? 'noModule' : 'module'} script ignored by micro-app`)\n } else if (src) { // remote script\n let scriptInfo = sourceCenter.script.getInfo(src)\n const appSpaceData = {\n async: script.hasAttribute('async'),\n defer: script.defer || script.type === 'module',\n module: script.type === 'module',\n inline: script.hasAttribute('inline'),\n pure: script.hasAttribute('pure'),\n attrs: getAttributes(script),\n }\n if (!scriptInfo) {\n scriptInfo = {\n code: '',\n isExternal: true,\n appSpace: {\n [app.name]: appSpaceData,\n }\n }\n } else {\n /**\n * Reuse when appSpace exists\n * NOTE:\n * 1. The same static script, appSpace must be the same (in fact, it may be different when url change)\n * 2. The same dynamic script, appSpace may be the same, but we still reuse appSpace, which should pay attention\n */\n scriptInfo.appSpace[app.name] = scriptInfo.appSpace[app.name] || appSpaceData\n }\n\n sourceCenter.script.setInfo(src, scriptInfo)\n\n if (!isDynamic) {\n app.source.scripts.add(src)\n replaceComment = document.createComment(`script with src='${src}' extract by micro-app`)\n } else {\n return { address: src, scriptInfo }\n }\n } else if (script.textContent) { // inline script\n /**\n * NOTE:\n * 1. Each inline script is unique\n * 2. Every dynamic created inline script will be re-executed\n * ACTION:\n * 1. Delete dynamic inline script info after exec\n * 2. Delete static inline script info when destroy\n */\n const nonceStr: string = getUniqueNonceSrc()\n const scriptInfo = {\n code: script.textContent,\n isExternal: false,\n appSpace: {\n [app.name]: {\n async: false,\n defer: script.type === 'module',\n module: script.type === 'module',\n inline: script.hasAttribute('inline'),\n pure: script.hasAttribute('pure'),\n attrs: getAttributes(script),\n }\n }\n }\n if (!isDynamic) {\n app.source.scripts.add(nonceStr)\n sourceCenter.script.setInfo(nonceStr, scriptInfo)\n replaceComment = document.createComment('inline script extract by micro-app')\n } else {\n // Because each dynamic script is unique, it is not put into sourceCenter\n return { address: nonceStr, scriptInfo }\n }\n } else if (!isDynamic) {\n /**\n * script with empty src or empty script.textContent remove in static html\n * & not removed if it created by dynamic\n */\n replaceComment = document.createComment('script element removed by micro-app')\n }\n\n if (isDynamic) {\n return { replaceComment }\n } else {\n return parent?.replaceChild(replaceComment!, script)\n }\n}\n\n/**\n * get assets plugins\n * @param appName app name\n */\nexport function getAssetsPlugins (appName: string): plugins['global'] {\n const globalPlugins = microApp.options.plugins?.global || []\n const modulePlugins = microApp.options.plugins?.modules?.[appName] || []\n\n return [...globalPlugins, ...modulePlugins]\n}\n\n/**\n * whether the address needs to be excluded\n * @param address css or js link\n * @param plugins microApp plugins\n */\nexport function checkExcludeUrl (address: string | null, appName: string): boolean {\n if (!address) return false\n const plugins = getAssetsPlugins(appName) || []\n return plugins.some(plugin => {\n if (!plugin.excludeChecker) return false\n return plugin.excludeChecker(address)\n })\n}\n\n/**\n * whether the address needs to be ignore\n * @param address css or js link\n * @param plugins microApp plugins\n */\nexport function checkIgnoreUrl (address: string | null, appName: string): boolean {\n if (!address) return false\n const plugins = getAssetsPlugins(appName) || []\n return plugins.some(plugin => {\n if (!plugin.ignoreChecker) return false\n return plugin.ignoreChecker(address)\n })\n}\n\n/**\n * Get remote resources of script\n * @param wrapElement htmlDom\n * @param app app\n */\nexport function fetchScriptsFromHtml (\n wrapElement: HTMLElement,\n app: AppInterface,\n): void {\n const scriptList: Array<string> = Array.from(app.source.scripts)\n const fetchScriptPromise: Array<Promise<string> | string> = []\n const fetchScriptPromiseInfo: Array<[string, ScriptSourceInfo]> = []\n for (const address of scriptList) {\n const scriptInfo = sourceCenter.script.getInfo(address)!\n const appSpaceData = scriptInfo.appSpace[app.name]\n if ((!appSpaceData.defer && !appSpaceData.async) || (app.isPrefetch && !app.isPrerender)) {\n fetchScriptPromise.push(scriptInfo.code ? scriptInfo.code : fetchSource(address, app.name))\n fetchScriptPromiseInfo.push([address, scriptInfo])\n }\n }\n\n const fiberScriptTasks: fiberTasks = app.isPrefetch || app.fiber ? [] : null\n\n if (fetchScriptPromise.length) {\n promiseStream<string>(fetchScriptPromise, (res: {data: string, index: number}) => {\n injectFiberTask(fiberScriptTasks, () => fetchScriptSuccess(\n fetchScriptPromiseInfo[res.index][0],\n fetchScriptPromiseInfo[res.index][1],\n res.data,\n app,\n ))\n }, (err: {error: Error, index: number}) => {\n logError(err, app.name)\n }, () => {\n if (fiberScriptTasks) {\n fiberScriptTasks.push(() => Promise.resolve(app.onLoad(wrapElement)))\n serialExecFiberTasks(fiberScriptTasks)\n } else {\n app.onLoad(wrapElement)\n }\n })\n } else {\n app.onLoad(wrapElement)\n }\n}\n\n/**\n * fetch js succeeded, record the code value\n * @param address script address\n * @param scriptInfo resource script info\n * @param data code\n */\nexport function fetchScriptSuccess (\n address: string,\n scriptInfo: ScriptSourceInfo,\n code: string,\n app: AppInterface,\n): void {\n // reset scriptInfo.code\n scriptInfo.code = code\n\n /**\n * Pre parse script for prefetch, improve rendering performance\n * NOTE:\n * 1. if global parseResult exist, skip this step\n * 2. if app is inline or script is esmodule, skip this step\n * 3. if global parseResult not exist, the current script occupies the position, when js is reused, parseResult is reference\n */\n if (app.isPrefetch && app.prefetchLevel === 2) {\n const appSpaceData = scriptInfo.appSpace[app.name]\n /**\n * When prefetch app is replaced by a new app in the processing phase, since the scriptInfo is common, when the scriptInfo of the prefetch app is processed, it may have already been processed.\n * This causes parsedCode to already exist when preloading ends\n * e.g.\n * 1. prefetch app.url different from <micro-app></micro-app>\n * 2. prefetch param different from <micro-app></micro-app>\n */\n if (!appSpaceData.parsedCode) {\n appSpaceData.parsedCode = bindScope(address, app, code, scriptInfo)\n appSpaceData.sandboxType = getSandboxType(app, scriptInfo)\n if (!isInlineMode(app, scriptInfo)) {\n try {\n appSpaceData.parsedFunction = getParsedFunction(app, scriptInfo, appSpaceData.parsedCode)\n } catch (err) {\n logError('Something went wrong while handling preloaded resources', app.name, '\\n', err)\n }\n }\n }\n }\n}\n\n/**\n * Execute js in the mount lifecycle\n * @param app app\n * @param initHook callback for umd mode\n */\nexport function execScripts (\n app: AppInterface,\n initHook: moduleCallBack,\n): void {\n const fiberScriptTasks: fiberTasks = app.fiber ? [] : null\n const scriptList: Array<string> = Array.from(app.source.scripts)\n const deferScriptPromise: Array<Promise<string>|string> = []\n const deferScriptInfo: Array<[string, ScriptSourceInfo]> = []\n for (const address of scriptList) {\n const scriptInfo = sourceCenter.script.getInfo(address)!\n const appSpaceData = scriptInfo.appSpace[app.name]\n // Notice the second render\n if (appSpaceData.defer || appSpaceData.async) {\n // TODO: defer和module彻底分开,不要混在一起\n if (scriptInfo.isExternal && !scriptInfo.code && !isTypeModule(app, scriptInfo)) {\n deferScriptPromise.push(fetchSource(address, app.name))\n } else {\n deferScriptPromise.push(scriptInfo.code)\n }\n deferScriptInfo.push([address, scriptInfo])\n\n isTypeModule(app, scriptInfo) && (initHook.moduleCount = initHook.moduleCount ? ++initHook.moduleCount : 1)\n } else {\n injectFiberTask(fiberScriptTasks, () => {\n runScript(address, app, scriptInfo)\n initHook(false)\n })\n }\n }\n\n if (deferScriptPromise.length) {\n promiseStream<string>(deferScriptPromise, (res: {data: string, index: number}) => {\n const scriptInfo = deferScriptInfo[res.index][1]\n scriptInfo.code = scriptInfo.code || res.data\n }, (err: {error: Error, index: number}) => {\n initHook.errorCount = initHook.errorCount ? ++initHook.errorCount : 1\n logError(err, app.name)\n }, () => {\n deferScriptInfo.forEach(([address, scriptInfo]) => {\n if (isString(scriptInfo.code)) {\n injectFiberTask(fiberScriptTasks, () => {\n runScript(address, app, scriptInfo, initHook)\n !isTypeModule(app, scriptInfo) && initHook(false)\n })\n }\n })\n\n /**\n * Fiber wraps js in requestIdleCallback and executes it in sequence\n * NOTE:\n * 1. In order to ensure the execution order, wait for all js loaded and then execute\n * 2. If js create a dynamic script, it may be errors in the execution order, because the subsequent js is wrapped in requestIdleCallback, even putting dynamic script in requestIdleCallback doesn't solve it\n *\n * BUG: NOTE.2 - execution order problem\n */\n if (fiberScriptTasks) {\n fiberScriptTasks.push(() => Promise.resolve(initHook(\n isUndefined(initHook.moduleCount) ||\n initHook.errorCount === deferScriptPromise.length\n )))\n serialExecFiberTasks(fiberScriptTasks)\n } else {\n initHook(\n isUndefined(initHook.moduleCount) ||\n initHook.errorCount === deferScriptPromise.length\n )\n }\n })\n } else {\n if (fiberScriptTasks) {\n fiberScriptTasks.push(() => Promise.resolve(initHook(true)))\n serialExecFiberTasks(fiberScriptTasks)\n } else {\n initHook(true)\n }\n }\n}\n\n/**\n * run code\n * @param address script address\n * @param app app\n * @param scriptInfo script info\n * @param callback callback of module script\n */\nexport function runScript (\n address: string,\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n callback?: moduleCallBack,\n replaceElement?: HTMLScriptElement,\n): void {\n try {\n actionsBeforeRunScript(app)\n const appSpaceData = scriptInfo.appSpace[app.name]\n const sandboxType = getSandboxType(app, scriptInfo)\n /**\n * NOTE:\n * 1. plugins and wrapCode will only be executed once\n * 2. if parsedCode not exist, parsedFunction is not exist\n * 3. if parsedCode exist, parsedFunction does not necessarily exist\n */\n if (!appSpaceData.parsedCode || appSpaceData.sandboxType !== sandboxType) {\n appSpaceData.parsedCode = bindScope(address, app, scriptInfo.code, scriptInfo)\n appSpaceData.sandboxType = sandboxType\n appSpaceData.parsedFunction = null\n }\n\n /**\n * TODO: 优化逻辑\n * 是否是内联模式应该由外部传入,这样自外而内更加统一,逻辑更加清晰\n */\n if (isInlineMode(app, scriptInfo)) {\n const scriptElement = replaceElement || pureCreateElement('script')\n runCode2InlineScript(\n address,\n appSpaceData.parsedCode,\n isTypeModule(app, scriptInfo),\n scriptElement,\n appSpaceData.attrs,\n callback,\n )\n\n /**\n * TODO: 优化逻辑\n * replaceElement不存在说明是初始化执行,需要主动插入script\n * 但这里的逻辑不清晰,应该明确声明是什么环境下才需要主动插入,而不是用replaceElement间接判断\n * replaceElement还有可能是注释类型(一定是在后台执行),这里的判断都是间接判断,不够直观\n */\n if (!replaceElement) {\n // TEST IGNORE\n const parent = app.iframe ? app.sandBox!.microBody : app.querySelector('micro-app-body')\n parent?.appendChild(scriptElement)\n }\n } else {\n runParsedFunction(app, scriptInfo)\n }\n } catch (e) {\n console.error(`[micro-app from ${replaceElement ? 'runDynamicScript' : 'runScript'}] app ${app.name}: `, e, address)\n // throw error in with sandbox to parent app\n throw e\n }\n}\n\n/**\n * Get dynamically created remote script\n * @param address script address\n * @param app app instance\n * @param scriptInfo scriptInfo\n * @param originScript origin script element\n */\nexport function runDynamicRemoteScript (\n address: string,\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n originScript: HTMLScriptElement,\n): HTMLScriptElement | Comment {\n const replaceElement = isInlineMode(app, scriptInfo) ? pureCreateElement('script') : document.createComment('dynamic script extract by micro-app')\n\n const dispatchScriptOnLoadEvent = () => dispatchOnLoadEvent(originScript)\n\n const runDynamicScript = () => {\n const descriptor = Object.getOwnPropertyDescriptor(globalEnv.rawDocument, 'currentScript')\n if (!descriptor || descriptor.configurable) {\n Object.defineProperty(globalEnv.rawDocument, 'currentScript', {\n value: originScript,\n configurable: true,\n })\n }\n\n runScript(address, app, scriptInfo, dispatchScriptOnLoadEvent, replaceElement as HTMLScriptElement)\n\n !isTypeModule(app, scriptInfo) && dispatchScriptOnLoadEvent()\n }\n\n if (scriptInfo.code || isTypeModule(app, scriptInfo)) {\n defer(runDynamicScript)\n } else {\n fetchSource(address, app.name).then((code: string) => {\n scriptInfo.code = code\n runDynamicScript()\n }).catch((err) => {\n logError(err, app.name)\n dispatchOnErrorEvent(originScript)\n })\n }\n\n return replaceElement\n}\n\n/**\n * Get dynamically created inline script\n * @param address script address\n * @param app app instance\n * @param scriptInfo scriptInfo\n */\nexport function runDynamicInlineScript (\n address: string,\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n): HTMLScriptElement | Comment {\n const replaceElement = isInlineMode(app, scriptInfo) ? pureCreateElement('script') : document.createComment('dynamic script extract by micro-app')\n\n runScript(address, app, scriptInfo, void 0, replaceElement as HTMLScriptElement)\n\n return replaceElement\n}\n\n/**\n * common handle for inline script\n * @param address script address\n * @param code bound code\n * @param module type='module' of script\n * @param scriptElement target script element\n * @param attrs attributes of script element\n * @param callback callback of module script\n */\nfunction runCode2InlineScript (\n address: string,\n code: string,\n module: boolean,\n scriptElement: HTMLScriptElement,\n attrs: AttrsType,\n callback?: moduleCallBack,\n): void {\n if (module) {\n globalEnv.rawSetAttribute.call(scriptElement, 'type', 'module')\n if (isInlineScript(address)) {\n /**\n * inline module script cannot convert to blob mode\n * Issue: https://github.com/micro-zoe/micro-app/issues/805\n */\n scriptElement.textContent = code\n } else {\n scriptElement.src = address\n }\n if (callback) {\n const onloadHandler = () => {\n callback.moduleCount && callback.moduleCount--\n callback(callback.moduleCount === 0)\n }\n /**\n * NOTE:\n * 1. module script will execute onload method only after it insert to document/iframe\n * 2. we can't know when the inline module script onload, and we use defer to simulate, this maybe cause some problems\n */\n if (isInlineScript(address)) {\n defer(onloadHandler)\n } else {\n scriptElement.onload = onloadHandler\n }\n }\n } else {\n scriptElement.textContent = code\n }\n\n setConvertScriptAttr(scriptElement, attrs)\n}\n\n// init & run code2Function\nfunction runParsedFunction (app: AppInterface, scriptInfo: ScriptSourceInfo) {\n const appSpaceData = scriptInfo.appSpace[app.name]\n if (!appSpaceData.parsedFunction) {\n appSpaceData.parsedFunction = getParsedFunction(app, scriptInfo, appSpaceData.parsedCode!)\n }\n appSpaceData.parsedFunction.call(getEffectWindow(app))\n}\n\n/**\n * bind js scope\n * @param app app\n * @param code code\n * @param scriptInfo source script info\n */\nfunction bindScope (\n address: string,\n app: AppInterface,\n code: string,\n scriptInfo: ScriptSourceInfo,\n): string {\n // TODO: 1、cache 2、esm code is null\n if (isPlainObject(microApp.options.plugins)) {\n code = usePlugins(address, code, app.name, microApp.options.plugins)\n }\n\n if (isWrapInSandBox(app, scriptInfo)) {\n return app.iframe ? `(function(window,self,global,location){;${code}\\n${isInlineScript(address) ? '' : `//# sourceURL=${address}\\n`}}).call(window.__MICRO_APP_SANDBOX__.proxyWindow,window.__MICRO_APP_SANDBOX__.proxyWindow,window.__MICRO_APP_SANDBOX__.proxyWindow,window.__MICRO_APP_SANDBOX__.proxyWindow,window.__MICRO_APP_SANDBOX__.proxyLocation);` : `;(function(proxyWindow){with(proxyWindow.__MICRO_APP_WINDOW__){(function(${GLOBAL_CACHED_KEY}){;${code}\\n${isInlineScript(address) ? '' : `//# sourceURL=${address}\\n`}}).call(proxyWindow,${GLOBAL_CACHED_KEY})}})(window.__MICRO_APP_PROXY_WINDOW__);`\n }\n\n return code\n}\n\n/**\n * actions before run script\n */\nfunction actionsBeforeRunScript (app: AppInterface): void {\n setActiveProxyWindow(app)\n}\n\n/**\n * set active sandBox.proxyWindow to window.__MICRO_APP_PROXY_WINDOW__\n */\nfunction setActiveProxyWindow (app: AppInterface): void {\n if (app.sandBox) {\n globalEnv.rawWindow.__MICRO_APP_PROXY_WINDOW__ = app.sandBox.proxyWindow\n }\n}\n\n/**\n * Call the plugin to process the file\n * @param address script address\n * @param code code\n * @param appName app name\n * @param plugins plugin list\n */\nfunction usePlugins (address: string, code: string, appName: string, plugins: plugins): string {\n const newCode = processCode(plugins.global, code, address)\n\n return processCode(plugins.modules?.[appName], newCode, address)\n}\n\nfunction processCode (configs: plugins['global'], code: string, address: string) {\n if (!isArray(configs)) {\n return code\n }\n\n return configs.reduce((preCode, config) => {\n if (isPlainObject(config) && isFunction(config.loader)) {\n return config.loader(preCode, address)\n }\n\n return preCode\n }, code)\n}\n","import type { AppInterface, fiberTasks } from '@micro-app/types'\nimport {\n logError,\n CompletionPath,\n pureCreateElement,\n injectFiberTask,\n serialExecFiberTasks,\n isLinkElement,\n isScriptElement,\n isStyleElement,\n isImageElement,\n} from '../libs/utils'\nimport {\n extractLinkFromHtml,\n fetchLinksFromHtml,\n} from './links'\nimport {\n extractScriptElement,\n fetchScriptsFromHtml,\n checkExcludeUrl,\n checkIgnoreUrl,\n} from './scripts'\nimport scopedCSS from '../sandbox/scoped_css'\nimport globalEnv from '../libs/global_env'\n\n/**\n * transform html string to dom\n * @param str string dom\n */\nfunction getWrapElement (str: string): HTMLElement {\n const wrapDiv = pureCreateElement('div')\n\n wrapDiv.innerHTML = str\n\n return wrapDiv\n}\n\n/**\n * Recursively process each child element\n * @param parent parent element\n * @param app app\n * @param microAppHead micro-app-head element\n */\nfunction flatChildren (\n parent: HTMLElement,\n app: AppInterface,\n microAppHead: Element,\n fiberStyleTasks: fiberTasks,\n): void {\n const children = Array.from(parent.children)\n\n children.length && children.forEach((child) => {\n flatChildren(child as HTMLElement, app, microAppHead, fiberStyleTasks)\n })\n\n for (const dom of children) {\n if (isLinkElement(dom)) {\n if (dom.hasAttribute('exclude') || checkExcludeUrl(dom.getAttribute('href'), app.name)) {\n parent.replaceChild(document.createComment('link element with exclude attribute ignored by micro-app'), dom)\n } else if (!(dom.hasAttribute('ignore') || checkIgnoreUrl(dom.getAttribute('href'), app.name))) {\n extractLinkFromHtml(dom, parent, app)\n } else if (dom.hasAttribute('href')) {\n globalEnv.rawSetAttribute.call(dom, 'href', CompletionPath(dom.getAttribute('href')!, app.url))\n }\n } else if (isStyleElement(dom)) {\n if (dom.hasAttribute('exclude')) {\n parent.replaceChild(document.createComment('style element with exclude attribute ignored by micro-app'), dom)\n } else if (app.scopecss && !dom.hasAttribute('ignore')) {\n injectFiberTask(fiberStyleTasks, () => scopedCSS(dom, app))\n }\n } else if (isScriptElement(dom)) {\n extractScriptElement(dom, parent, app)\n } else if (isImageElement(dom) && dom.hasAttribute('src')) {\n globalEnv.rawSetAttribute.call(dom, 'src', CompletionPath(dom.getAttribute('src')!, app.url))\n }\n /**\n * Don't remove meta and title, they have some special scenes\n * e.g.\n * document.querySelector('meta[name=\"viewport\"]') // for flexible\n * document.querySelector('meta[name=\"baseurl\"]').baseurl // for api request\n *\n * Title point to main app title, child app title used to be compatible with some special scenes\n */\n // else if (dom instanceof HTMLMetaElement || dom instanceof HTMLTitleElement) {\n // parent.removeChild(dom)\n // }\n }\n}\n\n/**\n * Extract link and script, bind style scope\n * @param htmlStr html string\n * @param app app\n */\nexport function extractSourceDom (htmlStr: string, app: AppInterface): void {\n const wrapElement = getWrapElement(htmlStr)\n const microAppHead = globalEnv.rawElementQuerySelector.call(wrapElement, 'micro-app-head')\n const microAppBody = globalEnv.rawElementQuerySelector.call(wrapElement, 'micro-app-body')\n\n if (!microAppHead || !microAppBody) {\n const msg = `element ${microAppHead ? 'body' : 'head'} is missing`\n app.onerror(new Error(msg))\n return logError(msg, app.name)\n }\n\n const fiberStyleTasks: fiberTasks = app.isPrefetch || app.fiber ? [] : null\n\n flatChildren(wrapElement, app, microAppHead, fiberStyleTasks)\n\n /**\n * Style and link are parallel, because it takes a lot of time for link to request resources. During this period, style processing can be performed to improve efficiency.\n */\n const fiberStyleResult = serialExecFiberTasks(fiberStyleTasks)\n\n if (app.source.links.size) {\n fetchLinksFromHtml(wrapElement, app, microAppHead, fiberStyleResult)\n } else if (fiberStyleResult) {\n fiberStyleResult.then(() => app.onLoad(wrapElement))\n } else {\n app.onLoad(wrapElement)\n }\n\n if (app.source.scripts.size) {\n fetchScriptsFromHtml(wrapElement, app)\n } else {\n app.onLoad(wrapElement)\n }\n}\n","import { CallableFunctionForInteract } from '@micro-app/types'\nimport EventCenter from './event_center'\nimport { appInstanceMap } from '../create_app'\nimport {\n removeDomScope,\n isString,\n isFunction,\n isPlainObject,\n formatAppName,\n logError,\n getRootContainer,\n} from '../libs/utils'\n\nconst eventCenter = new EventCenter()\n\n/**\n * Format event name\n * @param appName app.name\n * @param fromBaseApp is from base app\n */\nfunction createEventName (appName: string, fromBaseApp: boolean): string {\n if (!isString(appName) || !appName) return ''\n return fromBaseApp ? `__from_base_app_${appName}__` : `__from_micro_app_${appName}__`\n}\n\n// Global data\nclass EventCenterForGlobal {\n /**\n * add listener of global data\n * @param cb listener\n * @param autoTrigger If there is cached data when first bind listener, whether it needs to trigger, default is false\n */\n addGlobalDataListener (cb: CallableFunctionForInteract, autoTrigger?: boolean): void {\n const appName = (this as any).appName\n // if appName exists, this is in sub app\n if (appName) {\n cb.__APP_NAME__ = appName\n cb.__AUTO_TRIGGER__ = autoTrigger\n }\n eventCenter.on('global', cb, autoTrigger)\n }\n\n /**\n * remove listener of global data\n * @param cb listener\n */\n removeGlobalDataListener (cb: CallableFunctionForInteract): void {\n isFunction(cb) && eventCenter.off('global', cb)\n }\n\n /**\n * dispatch global data\n * @param data data\n */\n setGlobalData (\n data: Record<PropertyKey, unknown>,\n nextStep?: CallableFunction,\n force?: boolean,\n ): void {\n // clear dom scope before dispatch global data, apply to micro app\n removeDomScope()\n\n eventCenter.dispatch(\n 'global',\n data,\n (resArr: unknown[]) => isFunction(nextStep) && nextStep(resArr),\n force,\n )\n }\n\n forceSetGlobalData (\n data: Record<PropertyKey, unknown>,\n nextStep?: CallableFunction,\n ): void {\n this.setGlobalData(data, nextStep, true)\n }\n\n /**\n * get global data\n */\n getGlobalData (): Record<PropertyKey, unknown> | null {\n return eventCenter.getData('global')\n }\n\n /**\n * clear global data\n */\n clearGlobalData (): void {\n eventCenter.clearData('global')\n }\n\n /**\n * clear all listener of global data\n * if appName exists, only the specified functions is cleared\n * if appName not exists, only clear the base app functions\n */\n clearGlobalDataListener (): void {\n const appName = (this as any).appName\n const eventInfo = eventCenter.eventList.get('global')\n if (eventInfo) {\n for (const cb of eventInfo.callbacks) {\n if (\n (appName && appName === cb.__APP_NAME__) ||\n !(appName || cb.__APP_NAME__)\n ) {\n eventInfo.callbacks.delete(cb)\n }\n }\n }\n }\n}\n\n// Event center for base app\nexport class EventCenterForBaseApp extends EventCenterForGlobal {\n /**\n * add listener\n * @param appName app.name\n * @param cb listener\n * @param autoTrigger If there is cached data when first bind listener, whether it needs to trigger, default is false\n */\n addDataListener (appName: string, cb: CallableFunction, autoTrigger?: boolean): void {\n eventCenter.on(createEventName(formatAppName(appName), false), cb, autoTrigger)\n }\n\n /**\n * remove listener\n * @param appName app.name\n * @param cb listener\n */\n removeDataListener (appName: string, cb: CallableFunction): void {\n isFunction(cb) && eventCenter.off(createEventName(formatAppName(appName), false), cb)\n }\n\n /**\n * get data from micro app or base app\n * @param appName app.name\n * @param fromBaseApp whether get data from base app, default is false\n */\n getData (appName: string, fromBaseApp = false): Record<PropertyKey, unknown> | null {\n return eventCenter.getData(createEventName(formatAppName(appName), fromBaseApp))\n }\n\n /**\n * Dispatch data to the specified micro app\n * @param appName app.name\n * @param data data\n */\n setData (\n appName: string,\n data: Record<PropertyKey, unknown>,\n nextStep?: CallableFunction,\n force?: boolean,\n ): void {\n eventCenter.dispatch(\n createEventName(formatAppName(appName), true),\n data,\n (resArr: unknown[]) => isFunction(nextStep) && nextStep(resArr),\n force,\n )\n }\n\n forceSetData (\n appName: string,\n data: Record<PropertyKey, unknown>,\n nextStep?: CallableFunction,\n ): void {\n this.setData(appName, data, nextStep, true)\n }\n\n /**\n * clear data from base app\n * @param appName app.name\n * @param fromBaseApp whether clear data from child app, default is true\n */\n clearData (appName: string, fromBaseApp = true): void {\n eventCenter.clearData(createEventName(formatAppName(appName), fromBaseApp))\n }\n\n /**\n * clear all listener for specified micro app\n * @param appName app.name\n */\n clearDataListener (appName: string): void {\n eventCenter.off(createEventName(formatAppName(appName), false))\n }\n}\n\n// Event center for sub app\nexport class EventCenterForMicroApp extends EventCenterForGlobal {\n appName: string\n umdDataListeners?: {\n global: Set<CallableFunctionForInteract>,\n normal: Set<CallableFunctionForInteract>,\n }\n\n constructor (appName: string) {\n super()\n this.appName = formatAppName(appName)\n !this.appName && logError(`Invalid appName ${appName}`)\n }\n\n /**\n * add listener, monitor the data sent by the base app\n * @param cb listener\n * @param autoTrigger If there is cached data when first bind listener, whether it needs to trigger, default is false\n */\n addDataListener (cb: CallableFunctionForInteract, autoTrigger?: boolean): void {\n cb.__AUTO_TRIGGER__ = autoTrigger\n eventCenter.on(createEventName(this.appName, true), cb, autoTrigger)\n }\n\n /**\n * remove listener\n * @param cb listener\n */\n removeDataListener (cb: CallableFunctionForInteract): void {\n isFunction(cb) && eventCenter.off(createEventName(this.appName, true), cb)\n }\n\n /**\n * get data from base app\n */\n getData (fromBaseApp = true): Record<PropertyKey, unknown> | null {\n return eventCenter.getData(createEventName(this.appName, fromBaseApp))\n }\n\n /**\n * dispatch data to base app\n * @param data data\n */\n dispatch (data: Record<PropertyKey, unknown>, nextStep?: CallableFunction, force?: boolean): void {\n removeDomScope()\n\n eventCenter.dispatch(\n createEventName(this.appName, false),\n data,\n (resArr: unknown[]) => isFunction(nextStep) && nextStep(resArr),\n force,\n () => {\n const app = appInstanceMap.get(this.appName)\n if (app?.container && isPlainObject(data)) {\n const event = new CustomEvent('datachange', {\n detail: {\n data: eventCenter.getData(createEventName(this.appName, false))\n }\n })\n\n getRootContainer(app.container).dispatchEvent(event)\n }\n })\n }\n\n forceDispatch (data: Record<PropertyKey, unknown>, nextStep?: CallableFunction): void {\n this.dispatch(data, nextStep, true)\n }\n\n /**\n * clear data from child app\n * @param fromBaseApp whether clear data from base app, default is false\n */\n clearData (fromBaseApp = false): void {\n eventCenter.clearData(createEventName(this.appName, fromBaseApp))\n }\n\n /**\n * clear all listeners\n */\n clearDataListener (): void {\n eventCenter.off(createEventName(this.appName, true))\n }\n}\n\n/**\n * Record UMD function before exec umdHookMount\n * NOTE: record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * @param microAppEventCenter instance of EventCenterForMicroApp\n */\nexport function recordDataCenterSnapshot (microAppEventCenter: EventCenterForMicroApp): void {\n if (microAppEventCenter) {\n microAppEventCenter.umdDataListeners = {\n global: new Set(microAppEventCenter.umdDataListeners?.global),\n normal: new Set(microAppEventCenter.umdDataListeners?.normal),\n }\n\n const globalEventInfo = eventCenter.eventList.get('global')\n if (globalEventInfo) {\n for (const cb of globalEventInfo.callbacks) {\n if (microAppEventCenter.appName === cb.__APP_NAME__) {\n microAppEventCenter.umdDataListeners.global.add(cb)\n }\n }\n }\n\n const subAppEventInfo = eventCenter.eventList.get(createEventName(microAppEventCenter.appName, true))\n if (subAppEventInfo) {\n for (const cb of subAppEventInfo.callbacks) {\n microAppEventCenter.umdDataListeners.normal.add(cb)\n }\n }\n }\n}\n\n/**\n * Rebind the UMD function of the record before remount\n * @param microAppEventCenter instance of EventCenterForMicroApp\n */\nexport function rebuildDataCenterSnapshot (microAppEventCenter: EventCenterForMicroApp): void {\n // in withSandbox preRender mode with module script, umdDataListeners maybe undefined\n if (microAppEventCenter?.umdDataListeners) {\n for (const cb of microAppEventCenter.umdDataListeners.global) {\n microAppEventCenter.addGlobalDataListener(cb, cb.__AUTO_TRIGGER__)\n }\n\n for (const cb of microAppEventCenter.umdDataListeners.normal) {\n microAppEventCenter.addDataListener(cb, cb.__AUTO_TRIGGER__)\n }\n\n resetDataCenterSnapshot(microAppEventCenter)\n }\n}\n\n/**\n * delete umdDataListeners from microAppEventCenter\n * @param microAppEventCenter instance of EventCenterForMicroApp\n */\nexport function resetDataCenterSnapshot (microAppEventCenter: EventCenterForMicroApp): void {\n delete microAppEventCenter?.umdDataListeners\n}\n","/* eslint-disable no-cond-assign */\nimport { CallableFunctionForInteract, AppName } from '@micro-app/types'\nimport { logError, isFunction, isPlainObject, assign, defer } from '../libs/utils'\n\nexport default class EventCenter {\n public eventList = new Map<string, {\n data: Record<PropertyKey, unknown>,\n tempData?: Record<PropertyKey, unknown> | null,\n force?: boolean,\n callbacks: Set<CallableFunctionForInteract>,\n }>()\n\n // whether the name is legal\n private isLegalName (name: string): boolean {\n if (!name) {\n logError('event-center: Invalid name')\n return false\n }\n\n return true\n }\n\n private queue: string[] = []\n private recordStep: Record<string, {\n nextStepList: Array<CallableFunction>,\n dispatchDataEvent?: CallableFunction,\n } | null> = {}\n\n // add appName to queue\n private enqueue (\n name: AppName,\n nextStep: CallableFunction,\n dispatchDataEvent?: CallableFunction,\n ): void {\n // this.nextStepList.push(nextStep)\n if (this.recordStep[name]) {\n this.recordStep[name]!.nextStepList.push(nextStep)\n dispatchDataEvent && (this.recordStep[name]!.dispatchDataEvent = dispatchDataEvent)\n } else {\n this.recordStep[name] = {\n nextStepList: [nextStep],\n dispatchDataEvent,\n }\n }\n /**\n * The micro task is executed async when the second render of child.\n * We should ensure that the data changes are executed before binding the listening function\n */\n (!this.queue.includes(name) && this.queue.push(name) === 1) && defer(this.process)\n }\n\n // run task\n private process = (): void => {\n let name: string | void\n const temRecordStep = this.recordStep\n const queue = this.queue\n this.recordStep = {}\n this.queue = []\n while (name = queue.shift()) {\n const eventInfo = this.eventList.get(name)!\n // clear tempData, force before exec nextStep\n const tempData = eventInfo.tempData\n const force = eventInfo.force\n eventInfo.tempData = null\n eventInfo.force = false\n let resArr: unknown[]\n if (force || !this.isEqual(eventInfo.data, tempData)) {\n eventInfo.data = tempData || eventInfo.data\n for (const f of eventInfo.callbacks) {\n const res = f(eventInfo.data)\n res && (resArr ??= []).push(res)\n }\n\n temRecordStep[name]!.dispatchDataEvent?.()\n\n /**\n * WARING:\n * If data of other app is sent in nextStep, it may cause confusion of tempData and force\n */\n temRecordStep[name]!.nextStepList.forEach((nextStep) => nextStep(resArr))\n }\n }\n }\n\n /**\n * In react, each setState will trigger setData, so we need a filter operation to avoid repeated trigger\n */\n private isEqual (\n oldData: Record<PropertyKey, unknown>,\n newData: Record<PropertyKey, unknown> | null | void,\n ): boolean {\n if (!newData || Object.keys(oldData).length !== Object.keys(newData).length) return false\n\n for (const key in oldData) {\n if (Object.prototype.hasOwnProperty.call(oldData, key)) {\n if (oldData[key] !== newData[key]) return false\n }\n }\n\n return true\n }\n\n /**\n * add listener\n * @param name event name\n * @param f listener\n * @param autoTrigger If there is cached data when first bind listener, whether it needs to trigger, default is false\n */\n public on (name: string, f: CallableFunctionForInteract, autoTrigger = false): void {\n if (this.isLegalName(name)) {\n if (!isFunction(f)) {\n return logError('event-center: Invalid callback function')\n }\n\n let eventInfo = this.eventList.get(name)\n if (!eventInfo) {\n eventInfo = {\n data: {},\n callbacks: new Set(),\n }\n this.eventList.set(name, eventInfo)\n } else if (\n autoTrigger &&\n Object.keys(eventInfo.data).length &&\n (\n !this.queue.includes(name) ||\n this.isEqual(eventInfo.data, eventInfo.tempData)\n )\n ) {\n // auto trigger when data not null\n f(eventInfo.data)\n }\n\n eventInfo.callbacks.add(f)\n }\n }\n\n // remove listener, but the data is not cleared\n public off (\n name: string,\n f?: CallableFunctionForInteract,\n ): void {\n if (this.isLegalName(name)) {\n const eventInfo = this.eventList.get(name)\n if (eventInfo) {\n if (isFunction(f)) {\n eventInfo.callbacks.delete(f)\n } else {\n eventInfo.callbacks.clear()\n }\n }\n }\n }\n\n /**\n * clearData\n */\n public clearData (name: string): void {\n if (this.isLegalName(name)) {\n const eventInfo = this.eventList.get(name)\n if (eventInfo) {\n eventInfo.data = {}\n }\n }\n }\n\n // dispatch data\n public dispatch (\n name: string,\n data: Record<PropertyKey, unknown>,\n nextStep: CallableFunction,\n force?: boolean,\n dispatchDataEvent?: CallableFunction,\n ): void {\n if (this.isLegalName(name)) {\n if (!isPlainObject(data)) {\n return logError('event-center: data must be object')\n }\n\n let eventInfo = this.eventList.get(name)\n if (eventInfo) {\n eventInfo.tempData = assign({}, eventInfo.tempData || eventInfo.data, data)\n !eventInfo.force && (eventInfo.force = !!force)\n } else {\n eventInfo = {\n data: data,\n callbacks: new Set(),\n }\n this.eventList.set(name, eventInfo)\n /**\n * When sent data to parent, eventInfo probably does not exist, because parent may listen to datachange\n */\n eventInfo.force = true\n }\n // add to queue, event eventInfo is null\n this.enqueue(name, nextStep, dispatchDataEvent)\n }\n }\n\n // get data\n public getData (name: string): Record<PropertyKey, unknown> | null {\n const eventInfo = this.eventList.get(name)\n return eventInfo?.data ?? null\n }\n}\n","import { appInstanceMap } from './create_app'\nimport { AppInterface } from '@micro-app/types'\n\nexport interface IAppManager {\n get(appName: string): AppInterface | void\n set(appName: string, app: AppInterface): void\n getAll(): AppInterface[]\n clear(): void\n}\n\n// 管理 app 的单例\nexport class AppManager implements IAppManager {\n private static instance: AppManager;\n // TODO: appInstanceMap 由 AppManager 来创建,不再由 create_app 管理\n private appInstanceMap = appInstanceMap;\n\n public static getInstance (): AppManager {\n if (!this.instance) {\n this.instance = new AppManager()\n }\n return this.instance\n }\n\n public get (appName: string): AppInterface | void {\n return this.appInstanceMap.get(appName)\n }\n\n public set (appName: string, app: AppInterface): void {\n this.appInstanceMap.set(appName, app)\n }\n\n public getAll (): AppInterface[] {\n return Array.from(this.appInstanceMap.values())\n }\n\n public clear (): void {\n this.appInstanceMap.clear()\n }\n}\n","import { AppManager } from '../app_manager'\nimport { getRootContainer } from '../libs/utils'\n\nfunction unmountNestedApp (): void {\n releaseUnmountOfNestedApp()\n\n AppManager.getInstance().getAll().forEach(app => {\n // @ts-ignore\n app.container && getRootContainer(app.container).disconnectedCallback()\n })\n\n !window.__MICRO_APP_UMD_MODE__ && AppManager.getInstance().clear()\n}\n\n// release listener\nfunction releaseUnmountOfNestedApp (): void {\n if (window.__MICRO_APP_ENVIRONMENT__) {\n window.removeEventListener('unmount', unmountNestedApp, false)\n }\n}\n\n// if micro-app run in micro application, delete all next generation application when unmount event received\n// unmount event will auto release by sandbox\nexport function initEnvOfNestedApp (): void {\n if (window.__MICRO_APP_ENVIRONMENT__) {\n releaseUnmountOfNestedApp()\n window.addEventListener('unmount', unmountNestedApp, false)\n }\n}\n","/* eslint-disable no-return-assign */\nimport {\n isBoundFunction,\n isConstructor,\n rawDefineProperty,\n isBoolean,\n isFunction,\n} from '../libs/utils'\n\nfunction isBoundedFunction (value: CallableFunction & {__MICRO_APP_IS_BOUND_FUNCTION__: boolean}): boolean {\n if (isBoolean(value.__MICRO_APP_IS_BOUND_FUNCTION__)) return value.__MICRO_APP_IS_BOUND_FUNCTION__\n return value.__MICRO_APP_IS_BOUND_FUNCTION__ = isBoundFunction(value)\n}\n\nfunction isConstructorFunction (value: FunctionConstructor & {__MICRO_APP_IS_CONSTRUCTOR__: boolean}) {\n if (isBoolean(value.__MICRO_APP_IS_CONSTRUCTOR__)) return value.__MICRO_APP_IS_CONSTRUCTOR__\n return value.__MICRO_APP_IS_CONSTRUCTOR__ = isConstructor(value)\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport default function bindFunctionToRawTarget<T = Window, B = unknown> (value: any, rawTarget: T, key = 'WINDOW'): B {\n if (isFunction(value) && !isConstructorFunction(value) && !isBoundedFunction(value)) {\n const cacheKey = `__MICRO_APP_BOUND_${key}_FUNCTION__`\n if (value[cacheKey]) return value[cacheKey]\n\n const bindRawObjectValue = value.bind(rawTarget)\n\n for (const key in value) {\n bindRawObjectValue[key] = value[key]\n }\n\n if (value.hasOwnProperty('prototype')) {\n rawDefineProperty(bindRawObjectValue, 'prototype', {\n value: value.prototype,\n configurable: true,\n enumerable: false,\n writable: true,\n })\n }\n\n return value[cacheKey] = bindRawObjectValue\n }\n\n return value\n}\n","/* eslint-disable no-cond-assign */\nimport type {\n CommonEffectHook,\n MicroEventListener,\n WithSandBoxInterface,\n microAppWindowType,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n throttleDeferForSetAppName,\n isFunction,\n rawDefineProperties,\n} from '../../libs/utils'\nimport {\n appInstanceMap,\n} from '../../create_app'\nimport microApp from '../../micro_app'\n\n/**\n * create proxyDocument and MicroDocument, rewrite document of child app\n * @param appName app name\n * @param microAppWindow Proxy target\n * @returns EffectHook\n */\nexport function patchDocument (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: WithSandBoxInterface,\n): CommonEffectHook {\n const { proxyDocument, documentEffect } = createProxyDocument(appName, sandbox)\n const MicroDocument = createMicroDocument(appName, proxyDocument)\n rawDefineProperties(microAppWindow, {\n document: {\n configurable: false,\n enumerable: true,\n get () {\n // return globalEnv.rawDocument\n return proxyDocument\n },\n },\n Document: {\n configurable: false,\n enumerable: false,\n get () {\n // return globalEnv.rawRootDocument\n return MicroDocument\n },\n }\n })\n\n return documentEffect\n}\n\n/**\n * Create new document and Document\n */\nfunction createProxyDocument (\n appName: string,\n sandbox: WithSandBoxInterface,\n): {\n proxyDocument: Document,\n documentEffect: CommonEffectHook,\n } {\n const eventListenerMap = new Map<string, Set<MicroEventListener>>()\n const sstEventListenerMap = new Map<string, Set<MicroEventListener>>()\n let onClickHandler: unknown = null\n let sstOnClickHandler: unknown = null\n const {\n rawDocument,\n rawCreateElement,\n rawAddEventListener,\n rawRemoveEventListener,\n } = globalEnv\n\n function createElement (tagName: string, options?: ElementCreationOptions): HTMLElement {\n const element = rawCreateElement.call(rawDocument, tagName, options)\n element.__MICRO_APP_NAME__ = appName\n return element\n }\n\n /**\n * TODO:\n * 1. listener 是否需要绑定proxyDocument,否则函数中的this指向原生window\n * 2. 相似代码提取为公共方法(with, iframe)\n * 3. 如果this不指向proxyDocument 和 rawDocument,则需要特殊处理\n */\n function addEventListener (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList) {\n listenerList.add(listener)\n } else {\n eventListenerMap.set(type, new Set([listener]))\n }\n listener && (listener.__MICRO_APP_MARK_OPTIONS__ = options)\n rawAddEventListener.call(rawDocument, type, listener, options)\n }\n\n function removeEventListener (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList?.size && listenerList.has(listener)) {\n listenerList.delete(listener)\n }\n rawRemoveEventListener.call(rawDocument, type, listener, options)\n }\n\n // reset snapshot data\n const reset = (): void => {\n sstEventListenerMap.clear()\n sstOnClickHandler = null\n }\n\n /**\n * NOTE:\n * 1. about timer(events & properties should record & rebuild at all modes, exclude default mode)\n * 2. record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * 4 modes: default-mode、umd-mode、prerender、keep-alive\n * Solution:\n * 1. default-mode(normal): clear events & timers, not record & rebuild anything\n * 2. umd-mode(normal): not clear timers, record & rebuild events\n * 3. prerender/keep-alive(default, umd): not clear timers, record & rebuild events\n */\n const record = (): void => {\n /**\n * record onclick handler\n * onClickHandler maybe set again after prerender/keep-alive app hidden\n */\n sstOnClickHandler = onClickHandler || sstOnClickHandler\n\n // record document event\n eventListenerMap.forEach((listenerList, type) => {\n if (listenerList.size) {\n const cacheList = sstEventListenerMap.get(type) || []\n sstEventListenerMap.set(type, new Set([...cacheList, ...listenerList]))\n }\n })\n }\n\n // rebuild event and timer before remount app\n const rebuild = (): void => {\n // rebuild onclick event\n if (sstOnClickHandler && !onClickHandler) proxyDocument.onclick = sstOnClickHandler\n\n // rebuild document event\n sstEventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n proxyDocument.addEventListener(type, listener, listener?.__MICRO_APP_MARK_OPTIONS__)\n }\n })\n\n reset()\n }\n\n // release all event listener & interval & timeout when unmount app\n const release = (): void => {\n // Clear the function bound by micro app through document.onclick\n if (isFunction(onClickHandler)) {\n rawRemoveEventListener.call(rawDocument, 'click', onClickHandler)\n }\n onClickHandler = null\n\n // Clear document binding event\n if (eventListenerMap.size) {\n eventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n rawRemoveEventListener.call(rawDocument, type, listener)\n }\n })\n eventListenerMap.clear()\n }\n }\n\n const genProxyDocumentProps = () => {\n // microApp framework built-in Proxy\n const builtInProxyProps = new Map([\n ['onclick', (value: unknown) => {\n if (isFunction(onClickHandler)) {\n rawRemoveEventListener.call(rawDocument, 'click', onClickHandler, false)\n }\n // TODO: listener 是否需要绑定proxyDocument,否则函数中的this指向原生window\n if (isFunction(value)) {\n rawAddEventListener.call(rawDocument, 'click', value, false)\n }\n onClickHandler = value\n }]\n ])\n // external custom proxy\n const customProxyDocumentProps = microApp.options?.customProxyDocumentProps || new Map()\n // External has higher priority than built-in\n const mergedProxyDocumentProps = new Map([\n ...builtInProxyProps,\n ...customProxyDocumentProps,\n ])\n return mergedProxyDocumentProps\n }\n\n const mergedProxyDocumentProps = genProxyDocumentProps()\n\n const proxyDocument = new Proxy(rawDocument, {\n get: (target: Document, key: PropertyKey): unknown => {\n throttleDeferForSetAppName(appName)\n // TODO: 转换成数据形式,类似iframe的方式\n if (key === 'createElement') return createElement\n if (key === Symbol.toStringTag) return 'ProxyDocument'\n if (key === 'defaultView') return sandbox.proxyWindow\n if (key === 'onclick') return onClickHandler\n if (key === 'addEventListener') return addEventListener\n if (key === 'removeEventListener') return removeEventListener\n if (key === 'microAppElement') return appInstanceMap.get(appName)?.container\n if (key === '__MICRO_APP_NAME__') return appName\n return bindFunctionToRawTarget<Document>(Reflect.get(target, key), rawDocument, 'DOCUMENT')\n },\n set: (target: Document, key: PropertyKey, value: unknown): boolean => {\n if (mergedProxyDocumentProps.has(key)) {\n const proxyCallback = mergedProxyDocumentProps.get(key)\n proxyCallback(value)\n } else if (key !== 'microAppElement') {\n /**\n * 1. Fix TypeError: Illegal invocation when set document.title\n * 2. If the set method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown.\n */\n Reflect.set(target, key, value)\n }\n return true\n }\n })\n\n return {\n proxyDocument,\n documentEffect: {\n reset,\n record,\n rebuild,\n release,\n }\n }\n}\n\n/**\n * create proto Document\n * @param appName app name\n * @param proxyDocument proxy(document)\n * @returns Document\n */\nfunction createMicroDocument (appName: string, proxyDocument: Document): Function {\n const { rawDocument, rawRootDocument } = globalEnv\n\n class MicroDocument {\n static [Symbol.hasInstance] (target: unknown) {\n let proto = target\n while (proto) {\n proto = Object.getPrototypeOf(proto)\n if (proto === MicroDocument.prototype) {\n return true\n }\n }\n return (\n target === proxyDocument ||\n target instanceof rawRootDocument\n )\n }\n }\n\n /**\n * TIP:\n * 1. child class __proto__, which represents the inherit of the constructor, always points to the parent class\n * 2. child class prototype.__proto__, which represents the inherit of methods, always points to parent class prototype\n * e.g.\n * class B extends A {}\n * B.__proto__ === A // true\n * B.prototype.__proto__ === A.prototype // true\n */\n Object.setPrototypeOf(MicroDocument, rawRootDocument)\n // Object.create(rawRootDocument.prototype) will cause MicroDocument and proxyDocument methods not same when exec Document.prototype.xxx = xxx in child app\n Object.setPrototypeOf(MicroDocument.prototype, new Proxy(rawRootDocument.prototype, {\n get (target: Document, key: PropertyKey): unknown {\n throttleDeferForSetAppName(appName)\n return bindFunctionToRawTarget<Document>(Reflect.get(target, key), rawDocument, 'DOCUMENT')\n },\n set (target: Document, key: PropertyKey, value: unknown): boolean {\n Reflect.set(target, key, value)\n return true\n }\n }))\n\n return MicroDocument\n}\n","import type {\n microAppWindowType,\n CommonEffectHook,\n MicroEventListener,\n timeInfo,\n WithSandBoxInterface,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n SCOPE_WINDOW_EVENT,\n SCOPE_WINDOW_ON_EVENT,\n RAW_GLOBAL_TARGET,\n} from '../../constants'\nimport {\n isString,\n unique,\n throttleDeferForSetAppName,\n rawDefineProperty,\n rawHasOwnProperty,\n removeDomScope,\n} from '../../libs/utils'\n\n/**\n * patch window of child app\n * @param appName app name\n * @param microAppWindow microWindow of child app\n * @param sandbox WithSandBox\n * @returns EffectHook\n */\nexport function patchWindow (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: WithSandBoxInterface,\n): CommonEffectHook {\n patchWindowProperty(microAppWindow)\n createProxyWindow(appName, microAppWindow, sandbox)\n return patchWindowEffect(microAppWindow)\n}\n\n/**\n * rewrite special properties of window\n * @param appName app name\n * @param microAppWindow child app microWindow\n */\nfunction patchWindowProperty (\n microAppWindow: microAppWindowType,\n):void {\n const rawWindow = globalEnv.rawWindow\n Object.getOwnPropertyNames(rawWindow)\n .filter((key: string) => {\n return /^on/.test(key) && !SCOPE_WINDOW_ON_EVENT.includes(key)\n })\n .forEach((eventName: string) => {\n const { enumerable, writable, set } = Object.getOwnPropertyDescriptor(rawWindow, eventName) || {\n enumerable: true,\n writable: true,\n }\n rawDefineProperty(microAppWindow, eventName, {\n enumerable,\n configurable: true,\n get: () => rawWindow[eventName],\n set: writable ?? !!set\n ? (value) => { rawWindow[eventName] = value }\n : undefined,\n })\n })\n}\n\n/**\n * create proxyWindow with Proxy(microAppWindow)\n * @param appName app name\n * @param microAppWindow micro app window\n * @param sandbox WithSandBox\n */\nfunction createProxyWindow (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: WithSandBoxInterface,\n): void {\n const rawWindow = globalEnv.rawWindow\n const descriptorTargetMap = new Map<PropertyKey, 'target' | 'rawWindow'>()\n\n const proxyWindow = new Proxy(microAppWindow, {\n get: (target: microAppWindowType, key: PropertyKey): unknown => {\n throttleDeferForSetAppName(appName)\n if (\n Reflect.has(target, key) ||\n (isString(key) && /^__MICRO_APP_/.test(key)) ||\n sandbox.scopeProperties.includes(key)\n ) {\n if (RAW_GLOBAL_TARGET.includes(key)) removeDomScope()\n return Reflect.get(target, key)\n }\n\n return bindFunctionToRawTarget(Reflect.get(rawWindow, key), rawWindow)\n },\n set: (target: microAppWindowType, key: PropertyKey, value: unknown): boolean => {\n if (sandbox.adapter.escapeSetterKeyList.includes(key)) {\n Reflect.set(rawWindow, key, value)\n } else if (\n // target.hasOwnProperty has been rewritten\n !rawHasOwnProperty.call(target, key) &&\n rawHasOwnProperty.call(rawWindow, key) &&\n !sandbox.scopeProperties.includes(key)\n ) {\n const descriptor = Object.getOwnPropertyDescriptor(rawWindow, key)\n const { configurable, enumerable, writable, set } = descriptor!\n // set value because it can be set\n rawDefineProperty(target, key, {\n value,\n configurable,\n enumerable,\n writable: writable ?? !!set,\n })\n\n sandbox.injectedKeys.add(key)\n } else {\n !Reflect.has(target, key) && sandbox.injectedKeys.add(key)\n Reflect.set(target, key, value)\n }\n\n if (\n (\n sandbox.escapeProperties.includes(key) ||\n (\n sandbox.adapter.staticEscapeProperties.includes(key) &&\n !Reflect.has(rawWindow, key)\n )\n ) &&\n !sandbox.scopeProperties.includes(key)\n ) {\n !Reflect.has(rawWindow, key) && sandbox.escapeKeys.add(key)\n Reflect.set(rawWindow, key, value)\n }\n\n return true\n },\n has: (target: microAppWindowType, key: PropertyKey): boolean => {\n if (sandbox.scopeProperties.includes(key)) {\n /**\n * Some keywords, such as Vue, need to meet two conditions at the same time:\n * 1. 'Vue' in window --> false\n * 2. Vue (top level variable) // undefined\n * Issue https://github.com/micro-zoe/micro-app/issues/686\n */\n if (sandbox.adapter.staticScopeProperties.includes(key)) {\n return !!target[key]\n }\n return key in target\n }\n return key in target || key in rawWindow\n },\n // Object.getOwnPropertyDescriptor(window, key)\n getOwnPropertyDescriptor: (target: microAppWindowType, key: PropertyKey): PropertyDescriptor|undefined => {\n if (rawHasOwnProperty.call(target, key)) {\n descriptorTargetMap.set(key, 'target')\n return Object.getOwnPropertyDescriptor(target, key)\n }\n\n if (rawHasOwnProperty.call(rawWindow, key)) {\n descriptorTargetMap.set(key, 'rawWindow')\n const descriptor = Object.getOwnPropertyDescriptor(rawWindow, key)\n if (descriptor && !descriptor.configurable) {\n descriptor.configurable = true\n }\n return descriptor\n }\n\n return undefined\n },\n // Object.defineProperty(window, key, Descriptor)\n defineProperty: (target: microAppWindowType, key: PropertyKey, value: PropertyDescriptor): boolean => {\n const from = descriptorTargetMap.get(key)\n if (from === 'rawWindow') {\n return Reflect.defineProperty(rawWindow, key, value)\n }\n return Reflect.defineProperty(target, key, value)\n },\n // Object.getOwnPropertyNames(window)\n ownKeys: (target: microAppWindowType): Array<string | symbol> => {\n return unique(Reflect.ownKeys(rawWindow).concat(Reflect.ownKeys(target)))\n },\n deleteProperty: (target: microAppWindowType, key: PropertyKey): boolean => {\n if (rawHasOwnProperty.call(target, key)) {\n sandbox.injectedKeys.has(key) && sandbox.injectedKeys.delete(key)\n sandbox.escapeKeys.has(key) && Reflect.deleteProperty(rawWindow, key)\n return Reflect.deleteProperty(target, key)\n }\n return true\n },\n })\n\n sandbox.proxyWindow = proxyWindow\n}\n\n/**\n * Rewrite side-effect events\n * @param microAppWindow micro window\n */\nfunction patchWindowEffect (microAppWindow: microAppWindowType): CommonEffectHook {\n const eventListenerMap = new Map<string, Set<MicroEventListener>>()\n const sstEventListenerMap = new Map<string, Set<MicroEventListener>>()\n const intervalIdMap = new Map<number, timeInfo>()\n const timeoutIdMap = new Map<number, timeInfo>()\n const {\n rawWindow,\n rawAddEventListener,\n rawRemoveEventListener,\n rawDispatchEvent,\n rawSetInterval,\n rawSetTimeout,\n rawClearInterval,\n rawClearTimeout,\n } = globalEnv\n\n function getEventTarget (type: string): Window {\n return SCOPE_WINDOW_EVENT.includes(type) ? microAppWindow : rawWindow\n }\n\n /**\n * listener may be null, e.g test-passive\n * TODO:\n * 1. listener 是否需要绑定microAppWindow,否则函数中的this指向原生window\n * 2. 如果this不指向proxyWindow 或 microAppWindow,应该要做处理\n * window.addEventListener.call(非window, type, listener, options)\n */\n microAppWindow.addEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList) {\n listenerList.add(listener)\n } else {\n eventListenerMap.set(type, new Set([listener]))\n }\n listener && (listener.__MICRO_APP_MARK_OPTIONS__ = options)\n rawAddEventListener.call(getEventTarget(type), type, listener, options)\n }\n\n microAppWindow.removeEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList?.size && listenerList.has(listener)) {\n listenerList.delete(listener)\n }\n rawRemoveEventListener.call(getEventTarget(type), type, listener, options)\n }\n\n microAppWindow.dispatchEvent = function (event: Event): boolean {\n return rawDispatchEvent.call(getEventTarget(event?.type), event)\n }\n\n microAppWindow.setInterval = function (\n handler: TimerHandler,\n timeout?: number,\n ...args: any[]\n ): number {\n const intervalId = rawSetInterval.call(rawWindow, handler, timeout, ...args)\n intervalIdMap.set(intervalId, { handler, timeout, args })\n return intervalId\n }\n\n microAppWindow.setTimeout = function (\n handler: TimerHandler,\n timeout?: number,\n ...args: any[]\n ): number {\n const timeoutId = rawSetTimeout.call(rawWindow, handler, timeout, ...args)\n timeoutIdMap.set(timeoutId, { handler, timeout, args })\n return timeoutId\n }\n\n microAppWindow.clearInterval = function (intervalId: number) {\n intervalIdMap.delete(intervalId)\n rawClearInterval.call(rawWindow, intervalId)\n }\n\n microAppWindow.clearTimeout = function (timeoutId: number) {\n timeoutIdMap.delete(timeoutId)\n rawClearTimeout.call(rawWindow, timeoutId)\n }\n\n // reset snapshot data\n const reset = (): void => {\n sstEventListenerMap.clear()\n }\n\n /**\n * NOTE:\n * 1. about timer(events & properties should record & rebuild at all modes, exclude default mode)\n * 2. record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * 4 modes: default-mode、umd-mode、prerender、keep-alive\n * Solution:\n * 1. default-mode(normal): clear events & timers, not record & rebuild anything\n * 2. umd-mode(normal): not clear timers, record & rebuild events\n * 3. prerender/keep-alive(default, umd): not clear timers, record & rebuild events\n */\n const record = (): void => {\n // record window event\n eventListenerMap.forEach((listenerList, type) => {\n if (listenerList.size) {\n const cacheList = sstEventListenerMap.get(type) || []\n sstEventListenerMap.set(type, new Set([...cacheList, ...listenerList]))\n }\n })\n }\n\n // rebuild event and timer before remount app\n const rebuild = (): void => {\n // rebuild window event\n sstEventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n microAppWindow.addEventListener(type, listener, listener?.__MICRO_APP_MARK_OPTIONS__)\n }\n })\n\n reset()\n }\n\n // release all event listener & interval & timeout when unmount app\n const release = (clearTimer: boolean): void => {\n // Clear window binding events\n if (eventListenerMap.size) {\n eventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n rawRemoveEventListener.call(getEventTarget(type), type, listener)\n }\n })\n eventListenerMap.clear()\n }\n\n // default mode(not keep-alive or isPrerender)\n if (clearTimer) {\n intervalIdMap.forEach((_, intervalId: number) => {\n rawClearInterval.call(rawWindow, intervalId)\n })\n\n timeoutIdMap.forEach((_, timeoutId: number) => {\n rawClearTimeout.call(rawWindow, timeoutId)\n })\n\n intervalIdMap.clear()\n timeoutIdMap.clear()\n }\n }\n\n return {\n reset,\n record,\n rebuild,\n release,\n }\n}\n","import type {\n MicroLocation,\n MicroState,\n LocationQuery,\n HandleMicroPathResult,\n MicroAppElementType,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport {\n assign,\n parseQuery,\n stringifyQuery,\n isString,\n isUndefined,\n isPlainObject,\n createURL,\n} from '../../libs/utils'\nimport {\n appInstanceMap,\n} from '../../create_app'\nimport {\n ROUTER_MODE_LIST,\n DEFAULT_ROUTER_MODE,\n ROUTER_MODE_CUSTOM,\n ROUTER_MODE_HISTORY,\n} from '../../constants'\nimport microApp from '../../micro_app'\n\n// set micro app state to origin state\nexport function setMicroState (\n appName: string,\n microState: MicroState,\n): MicroState {\n if (!isRouterModeCustom(appName)) {\n const rawState = globalEnv.rawWindow.history.state\n const additionalState: Record<string, any> = {\n microAppState: assign({}, rawState?.microAppState, {\n [appName]: microState\n })\n }\n\n // create new state object\n return assign({}, rawState, additionalState)\n }\n\n return microState\n}\n\n// delete micro app state form origin state\nexport function removeMicroState (appName: string, rawState: MicroState): MicroState {\n if (!isRouterModeCustom(appName)) {\n if (isPlainObject(rawState?.microAppState)) {\n if (!isUndefined(rawState.microAppState[appName])) {\n delete rawState.microAppState[appName]\n }\n if (!Object.keys(rawState.microAppState).length) {\n delete rawState.microAppState\n }\n }\n\n return assign({}, rawState)\n }\n\n return rawState\n}\n\n// get micro app state form origin state\nexport function getMicroState (appName: string): MicroState {\n const rawState = globalEnv.rawWindow.history.state\n\n if (!isRouterModeCustom(appName)) {\n return rawState?.microAppState?.[appName] || null\n }\n\n return rawState\n}\n\nconst ENC_AD_RE = /&/g // %M1\nconst ENC_EQ_RE = /=/g // %M2\nconst DEC_AD_RE = /%M1/g // &\nconst DEC_EQ_RE = /%M2/g // =\n\n// encode path with special symbol\nexport function encodeMicroPath (path: string): string {\n return encodeURIComponent(commonDecode(path).replace(ENC_AD_RE, '%M1').replace(ENC_EQ_RE, '%M2'))\n}\n\n// decode path\nexport function decodeMicroPath (path: string): string {\n return commonDecode(path).replace(DEC_AD_RE, '&').replace(DEC_EQ_RE, '=')\n}\n\n// Recursively resolve address\nfunction commonDecode (path: string): string {\n try {\n const decPath = decodeURIComponent(path)\n if (path === decPath || DEC_AD_RE.test(decPath) || DEC_EQ_RE.test(decPath)) return decPath\n return commonDecode(decPath)\n } catch {\n return path\n }\n}\n\n// Format the query parameter key to prevent conflicts with the original parameters\nfunction formatQueryAppName (appName: string) {\n // return `app-${appName}`\n return appName\n}\n\n/**\n * Get app fullPath from browser url\n * @param appName app.name\n */\nexport function getMicroPathFromURL (appName: string): string | null {\n const rawLocation = globalEnv.rawWindow.location\n if (!isRouterModeCustom(appName)) {\n const queryObject = getQueryObjectFromURL(rawLocation.search, rawLocation.hash)\n const microPath = queryObject.hashQuery?.[formatQueryAppName(appName)] || queryObject.searchQuery?.[formatQueryAppName(appName)]\n return isString(microPath) ? decodeMicroPath(microPath) : null\n }\n return rawLocation.pathname + rawLocation.search + rawLocation.hash\n}\n\n/**\n * Attach child app fullPath to browser url\n * @param appName app.name\n * @param targetLocation location of child app or rawLocation of window\n */\nexport function setMicroPathToURL (appName: string, targetLocation: MicroLocation): HandleMicroPathResult {\n const targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n let isAttach2Hash = false\n if (!isRouterModeCustom(appName)) {\n let { pathname, search, hash } = globalEnv.rawWindow.location\n const queryObject = getQueryObjectFromURL(search, hash)\n const encodedMicroPath = encodeMicroPath(targetFullPath)\n\n /**\n * Is parent is hash router\n * In fact, this is not true. It just means that the parameter is added to the hash\n */\n // If hash exists and search does not exist, it is considered as a hash route\n if (hash && !search) {\n isAttach2Hash = true\n if (queryObject.hashQuery) {\n queryObject.hashQuery[formatQueryAppName(appName)] = encodedMicroPath\n } else {\n queryObject.hashQuery = {\n [formatQueryAppName(appName)]: encodedMicroPath\n }\n }\n const baseHash = hash.includes('?') ? hash.slice(0, hash.indexOf('?') + 1) : hash + '?'\n hash = baseHash + stringifyQuery(queryObject.hashQuery)\n } else {\n if (queryObject.searchQuery) {\n queryObject.searchQuery[formatQueryAppName(appName)] = encodedMicroPath\n } else {\n queryObject.searchQuery = {\n [formatQueryAppName(appName)]: encodedMicroPath\n }\n }\n search = '?' + stringifyQuery(queryObject.searchQuery)\n }\n\n return {\n fullPath: pathname + search + hash,\n isAttach2Hash,\n }\n }\n\n return {\n fullPath: targetFullPath,\n isAttach2Hash,\n }\n}\n\n/**\n * Delete child app fullPath from browser url\n * @param appName app.name\n * @param targetLocation target Location, default is rawLocation\n */\nexport function removeMicroPathFromURL (appName: string, targetLocation?: MicroLocation): HandleMicroPathResult {\n let { pathname, search, hash } = targetLocation || globalEnv.rawWindow.location\n let isAttach2Hash = false\n\n if (!isRouterModeCustom(appName)) {\n const queryObject = getQueryObjectFromURL(search, hash)\n if (queryObject.hashQuery?.[formatQueryAppName(appName)]) {\n isAttach2Hash = true\n delete queryObject.hashQuery?.[formatQueryAppName(appName)]\n const hashQueryStr = stringifyQuery(queryObject.hashQuery)\n hash = hash.slice(0, hash.indexOf('?') + Number(Boolean(hashQueryStr))) + hashQueryStr\n } else if (queryObject.searchQuery?.[formatQueryAppName(appName)]) {\n delete queryObject.searchQuery?.[formatQueryAppName(appName)]\n const searchQueryStr = stringifyQuery(queryObject.searchQuery)\n search = searchQueryStr ? '?' + searchQueryStr : ''\n }\n }\n\n return {\n fullPath: pathname + search + hash,\n isAttach2Hash,\n }\n}\n\n/**\n * Format search, hash to object\n */\nfunction getQueryObjectFromURL (search: string, hash: string): LocationQuery {\n const queryObject: LocationQuery = {}\n\n if (search !== '' && search !== '?') {\n queryObject.searchQuery = parseQuery(search.slice(1))\n }\n\n if (hash.includes('?')) {\n queryObject.hashQuery = parseQuery(hash.slice(hash.indexOf('?') + 1))\n }\n\n return queryObject\n}\n\n/**\n * get microApp path from browser URL without hash\n */\nexport function getNoHashMicroPathFromURL (appName: string, baseUrl: string): string {\n const microPath = getMicroPathFromURL(appName)\n if (!microPath) return ''\n const formatLocation = createURL(microPath, baseUrl)\n return formatLocation.origin + formatLocation.pathname + formatLocation.search\n}\n\n/**\n * Effect app is an app that can perform route navigation\n * NOTE: Invalid app action\n * 1. prevent update browser url, dispatch popStateEvent, reload browser\n * 2. It can update path with pushState/replaceState\n * 3. Can not update path outside (with router api)\n * 3. Can not update path by location\n */\nexport function isEffectiveApp (appName: string): boolean {\n const app = appInstanceMap.get(appName)\n /**\n * !!(app && !app.isPrefetch && !app.isHidden())\n * NOTE: 隐藏的keep-alive应用暂时不作为无效应用,原因如下\n * 1、隐藏后才执行去除浏览器上的微应用的路由信息的操作,导致微应用的路由信息无法去除\n * 2、如果保持隐藏应用内部正常跳转,阻止同步路由信息到浏览器,这样理论上是好的,但是对于location跳转改如何处理?location跳转是基于修改浏览器地址后发送popstate事件实现的,所以应该是在隐藏后不支持通过location进行跳转\n */\n return !!(app && !app.isPrefetch)\n}\n\n/**\n * router mode is custom\n * NOTE:\n * 1. if sandbox disabled, router mode defaults to custom\n * 2. if app not exist, router mode defaults to custom\n */\nexport function isRouterModeCustom (appName: string): boolean {\n const app = appInstanceMap.get(appName)\n return !app || !app.sandBox || app.routerMode === ROUTER_MODE_CUSTOM\n}\n\n// router mode is search\nexport function isRouterModeSearch (appName: string): boolean {\n const app = appInstanceMap.get(appName)\n return !!(app && app.sandBox && app.routerMode === DEFAULT_ROUTER_MODE)\n}\n\n// router mode is history\nexport function isRouterModeHistory (appName: string): boolean {\n const app = appInstanceMap.get(appName)\n return !!(app && app.sandBox && app.routerMode === ROUTER_MODE_HISTORY)\n}\n\n/**\n * get memory router mode of child app\n * NOTE:\n * 1. if microAppElement exists, it means the app render by the micro-app element\n * 2. if microAppElement not exists, it means it is prerender app\n * @param mode native config\n * @param microAppElement micro-app element\n * @returns mode\n */\nexport function getRouterMode (\n mode: string | null | void,\n microAppElement?: MicroAppElementType,\n): string {\n let routerMode: string\n /**\n * compatible with disable-memory-router in older versions\n * if disable-memory-router is true, router-mode will be custom\n */\n if (microAppElement) {\n routerMode = microAppElement.getDisposeResult('disable-memory-router') ? ROUTER_MODE_CUSTOM : mode || microApp.options['router-mode'] || ''\n } else {\n routerMode = microApp.options['disable-memory-router'] ? ROUTER_MODE_CUSTOM : mode || microApp.options['router-mode'] || ''\n }\n return ROUTER_MODE_LIST.includes(routerMode) ? routerMode : DEFAULT_ROUTER_MODE\n}\n","import type {\n MicroLocation,\n PopStateListener,\n MicroPopStateEvent,\n microAppWindowType,\n} from '@micro-app/types'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} from '../../create_app'\nimport {\n getActiveApps,\n} from '../../micro_app'\nimport {\n getMicroPathFromURL,\n getMicroState,\n isEffectiveApp,\n} from './core'\nimport {\n updateMicroLocation,\n} from './location'\nimport {\n removeDomScope,\n isFunction,\n} from '../../libs/utils'\nimport globalEnv from '../../libs/global_env'\n\n/**\n * dispatch PopStateEvent & HashChangeEvent to child app\n * each child app will listen for popstate event when sandbox start\n * and release it when sandbox stop\n * @param appName app name\n * @returns release callback\n */\nexport function addHistoryListener (appName: string): CallableFunction {\n const rawWindow = globalEnv.rawWindow\n // handle popstate event and distribute to child app\n const popStateHandler: PopStateListener = (e: MicroPopStateEvent): void => {\n /**\n * 1. unmount app & hidden keep-alive app will not receive popstate event\n * 2. filter out onlyForBrowser\n */\n if (\n getActiveApps({\n excludeHiddenApp: true,\n excludePreRender: true,\n }).includes(appName) &&\n !e.onlyForBrowser\n ) {\n updateMicroLocationWithEvent(appName, getMicroPathFromURL(appName))\n }\n }\n\n rawWindow.addEventListener('popstate', popStateHandler)\n\n return () => {\n rawWindow.removeEventListener('popstate', popStateHandler)\n }\n}\n\n/**\n * Effect: use to trigger child app jump\n * Actions:\n * 1. update microLocation with target path\n * 2. dispatch popStateEvent & hashChangeEvent\n * @param appName app name\n * @param targetFullPath target path of child app\n */\nexport function updateMicroLocationWithEvent (\n appName: string,\n targetFullPath: string | null,\n): void {\n const app = appInstanceMap.get(appName)!\n const proxyWindow = app.sandBox!.proxyWindow\n const microAppWindow = app.sandBox!.microAppWindow\n let isHashChange = false\n // for hashChangeEvent\n const oldHref = proxyWindow.location.href\n // Do not attach micro state to url when targetFullPath is empty\n if (targetFullPath) {\n const oldHash = proxyWindow.location.hash\n updateMicroLocation(appName, targetFullPath, microAppWindow.location as MicroLocation)\n isHashChange = proxyWindow.location.hash !== oldHash\n }\n\n // dispatch formatted popStateEvent to child\n dispatchPopStateEventToMicroApp(appName, proxyWindow, microAppWindow)\n\n // dispatch formatted hashChangeEvent to child when hash change\n if (isHashChange) dispatchHashChangeEventToMicroApp(appName, proxyWindow, microAppWindow, oldHref)\n\n // clear element scope before trigger event of next app\n removeDomScope()\n}\n\n/**\n * dispatch formatted popstate event to microApp\n * @param appName app name\n * @param proxyWindow sandbox window\n * @param eventState history.state\n */\nexport function dispatchPopStateEventToMicroApp (\n appName: string,\n proxyWindow: WindowProxy,\n microAppWindow: microAppWindowType,\n): void {\n /**\n * TODO: test\n * angular14 takes e.type as type judgment\n * when e.type is popstate-appName popstate event will be invalid\n */\n // Object.defineProperty(newPopStateEvent, 'type', {\n // value: 'popstate',\n // writable: true,\n // configurable: true,\n // enumerable: true,\n // })\n // create PopStateEvent named popstate-appName with sub app state\n const newPopStateEvent = new PopStateEvent(\n 'popstate',\n { state: getMicroState(appName) }\n )\n\n microAppWindow.dispatchEvent(newPopStateEvent)\n\n if (!isIframeSandbox(appName)) {\n // call function window.onpopstate if it exists\n isFunction(proxyWindow.onpopstate) && proxyWindow.onpopstate(newPopStateEvent)\n }\n}\n\n/**\n * dispatch formatted hashchange event to microApp\n * @param appName app name\n * @param proxyWindow sandbox window\n * @param oldHref old href\n */\nexport function dispatchHashChangeEventToMicroApp (\n appName: string,\n proxyWindow: WindowProxy,\n microAppWindow: microAppWindowType,\n oldHref: string,\n): void {\n const newHashChangeEvent = new HashChangeEvent(\n 'hashchange',\n {\n newURL: proxyWindow.location.href,\n oldURL: oldHref,\n }\n )\n\n microAppWindow.dispatchEvent(newHashChangeEvent)\n\n if (!isIframeSandbox(appName)) {\n // call function window.onhashchange if it exists\n isFunction(proxyWindow.onhashchange) && proxyWindow.onhashchange(newHashChangeEvent)\n }\n}\n\n/**\n * dispatch native PopStateEvent, simulate location behavior\n * @param onlyForBrowser only dispatch PopStateEvent to browser\n */\nfunction dispatchNativePopStateEvent (onlyForBrowser: boolean): void {\n const event = new PopStateEvent('popstate', { state: null }) as MicroPopStateEvent\n if (onlyForBrowser) event.onlyForBrowser = true\n globalEnv.rawWindow.dispatchEvent(event)\n}\n\n/**\n * dispatch hashchange event to browser\n * @param oldHref old href of rawWindow.location\n */\nfunction dispatchNativeHashChangeEvent (oldHref: string): void {\n const newHashChangeEvent = new HashChangeEvent(\n 'hashchange',\n {\n newURL: globalEnv.rawWindow.location.href,\n oldURL: oldHref,\n }\n )\n\n globalEnv.rawWindow.dispatchEvent(newHashChangeEvent)\n}\n\n/**\n * dispatch popstate & hashchange event to browser\n * @param appName app.name\n * @param onlyForBrowser only dispatch event to browser\n * @param oldHref old href of rawWindow.location\n */\nexport function dispatchNativeEvent (\n appName: string,\n onlyForBrowser: boolean,\n oldHref?: string,\n): void {\n // clear element scope before dispatch global event\n removeDomScope()\n if (isEffectiveApp(appName)) {\n dispatchNativePopStateEvent(onlyForBrowser)\n if (oldHref) {\n dispatchNativeHashChangeEvent(oldHref)\n }\n }\n}\n","/* eslint-disable no-void */\nimport type {\n MicroState,\n MicroLocation,\n MicroHistory,\n HistoryProxyValue,\n HandleMicroPathResult,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport {\n isString,\n createURL,\n isPlainObject,\n isURL,\n assign,\n removeDomScope,\n} from '../../libs/utils'\nimport {\n setMicroPathToURL,\n setMicroState,\n getMicroState,\n getMicroPathFromURL,\n isEffectiveApp,\n isRouterModeCustom,\n} from './core'\nimport { dispatchNativeEvent } from './event'\nimport { updateMicroLocation } from './location'\nimport bindFunctionToRawTarget from '../bind_function'\nimport { getActiveApps } from '../../micro_app'\nimport { appInstanceMap, isIframeSandbox } from '../../create_app'\n\n/**\n * create proxyHistory for microApp\n * MDN https://developer.mozilla.org/en-US/docs/Web/API/History\n * @param appName app name\n * @param microLocation microApp location\n */\nexport function createMicroHistory (appName: string, microLocation: MicroLocation): MicroHistory {\n const rawHistory = globalEnv.rawWindow.history\n function getMicroHistoryMethod (methodName: string): CallableFunction {\n return function (...rests: any[]): void {\n // TODO: 测试iframe的URL兼容isURL的情况\n if (isString(rests[2]) || isURL(rests[2])) {\n const targetLocation = createURL(rests[2], microLocation.href)\n const targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n navigateWithNativeEvent(\n appName,\n methodName,\n setMicroPathToURL(appName, targetLocation),\n true,\n setMicroState(appName, rests[0]),\n rests[1],\n )\n if (targetFullPath !== microLocation.fullPath) {\n updateMicroLocation(appName, targetFullPath, microLocation)\n }\n appInstanceMap.get(appName)?.sandBox.updateIframeBase?.()\n } else {\n nativeHistoryNavigate(appName, methodName, rests[2], rests[0], rests[1])\n }\n }\n }\n\n const pushState = getMicroHistoryMethod('pushState')\n const replaceState = getMicroHistoryMethod('replaceState')\n\n if (isIframeSandbox(appName)) return { pushState, replaceState } as MicroHistory\n\n return new Proxy(rawHistory, {\n get (target: History, key: PropertyKey): HistoryProxyValue {\n if (key === 'state') {\n return getMicroState(appName)\n } else if (key === 'pushState') {\n return pushState\n } else if (key === 'replaceState') {\n return replaceState\n }\n return bindFunctionToRawTarget<History, HistoryProxyValue>(Reflect.get(target, key), target, 'HISTORY')\n },\n set (target: History, key: PropertyKey, value: unknown): boolean {\n Reflect.set(target, key, value)\n /**\n * If the set() method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown.\n * e.g. history.state = {}\n * TypeError: 'set' on proxy: trap returned false for property 'state'\n */\n return true\n }\n })\n}\n\n/**\n * navigate to new path base on native method of history\n * @param appName app.name\n * @param methodName pushState/replaceState\n * @param fullPath full path\n * @param state history.state, default is null\n * @param title history.title, default is ''\n */\nexport function nativeHistoryNavigate (\n appName: string,\n methodName: string,\n fullPath: string,\n state: unknown = null,\n title: unknown = '',\n): void {\n if (isEffectiveApp(appName)) {\n const method = methodName === 'pushState' ? globalEnv.rawPushState : globalEnv.rawReplaceState\n method.call(globalEnv.rawWindow.history, state, title, fullPath)\n }\n}\n\n/**\n * Navigate to new path, and dispatch native popStateEvent/hashChangeEvent to browser\n * Use scenes:\n * 1. mount/unmount through attachRouteToBrowserURL with limited popstateEvent\n * 2. proxyHistory.pushState/replaceState with limited popstateEvent\n * 3. api microApp.router.push/replace\n * 4. proxyLocation.hash = xxx\n * NOTE:\n * 1. hidden keep-alive app can jump internally, but will not synchronize to browser\n * @param appName app.name\n * @param methodName pushState/replaceState\n * @param result result of add/remove microApp path on browser url\n * @param onlyForBrowser only dispatch event to browser\n * @param state history.state, not required\n * @param title history.title, not required\n */\nexport function navigateWithNativeEvent (\n appName: string,\n methodName: string,\n result: HandleMicroPathResult,\n onlyForBrowser: boolean,\n state?: unknown,\n title?: string,\n): void {\n if (isEffectiveApp(appName)) {\n const rawLocation = globalEnv.rawWindow.location\n const oldFullPath = rawLocation.pathname + rawLocation.search + rawLocation.hash\n // oldHref use for hashChangeEvent of base app\n const oldHref = result.isAttach2Hash && oldFullPath !== result.fullPath ? rawLocation.href : null\n // navigate with native history method\n nativeHistoryNavigate(appName, methodName, result.fullPath, state, title)\n /**\n * TODO:\n * 1. 如果所有模式统一发送popstate事件,则!isRouterModeCustom(appName)要去掉\n * 2. 如果发送事件,则会导致vue router-view :key='router.path'绑定,无限卸载应用,死循环\n */\n if (oldFullPath !== result.fullPath && !isRouterModeCustom(appName)) {\n dispatchNativeEvent(appName, onlyForBrowser, oldHref)\n }\n }\n}\n\n/**\n * update browser url when mount/unmount/hidden/show/attachToURL/attachAllToURL\n * just attach microRoute info to browser, dispatch event to base app(exclude child)\n * @param appName app.name\n * @param result result of add/remove microApp path on browser url\n * @param state history.state\n */\nexport function attachRouteToBrowserURL (\n appName: string,\n result: HandleMicroPathResult,\n state: MicroState,\n): void {\n navigateWithNativeEvent(appName, 'replaceState', result, true, state)\n}\n\n/**\n * When path is same, keep the microAppState in history.state\n * Fix bug of missing microAppState when base app is next.js or angular\n * @param method history.pushState/replaceState\n */\nfunction reWriteHistoryMethod (method: History['pushState' | 'replaceState']): CallableFunction {\n const rawWindow = globalEnv.rawWindow\n return function (...rests: [data: any, unused: string, url?: string]): void {\n if (\n rawWindow.history.state?.microAppState &&\n (!isPlainObject(rests[0]) || !rests[0].microAppState) &&\n (isString(rests[2]) || isURL(rests[2]))\n ) {\n const currentHref = rawWindow.location.href\n const targetLocation = createURL(rests[2], currentHref)\n if (targetLocation.href === currentHref) {\n rests[0] = assign({}, rests[0], {\n microAppState: rawWindow.history.state.microAppState,\n })\n }\n }\n\n method.apply(rawWindow.history, rests)\n /**\n * Attach child router info to browser url when base app navigate with pushState/replaceState\n * NOTE:\n * 1. Exec after apply pushState/replaceState\n * 2. Unable to catch when base app navigate with location\n * 3. When in nest app, rawPushState/rawReplaceState has been modified by parent\n */\n getActiveApps({\n excludeHiddenApp: true,\n excludePreRender: true,\n }).forEach(appName => {\n if (!isRouterModeCustom(appName) && !getMicroPathFromURL(appName)) {\n const app = appInstanceMap.get(appName)!\n attachRouteToBrowserURL(\n appName,\n setMicroPathToURL(appName, app.sandBox.proxyWindow.location as MicroLocation),\n setMicroState(appName, getMicroState(appName)),\n )\n }\n })\n // fix bug for nest app\n removeDomScope()\n }\n}\n\n/**\n * rewrite history.pushState/replaceState\n * used to fix the problem that the microAppState maybe missing when mainApp navigate to same path\n * e.g: when nextjs, angular receive popstate event, they will use history.replaceState to update browser url with a new state object\n */\nexport function patchHistory (): void {\n const rawWindow = globalEnv.rawWindow\n rawWindow.history.pushState = reWriteHistoryMethod(\n globalEnv.rawPushState,\n )\n rawWindow.history.replaceState = reWriteHistoryMethod(\n globalEnv.rawReplaceState,\n )\n}\n\nexport function releasePatchHistory (): void {\n const rawWindow = globalEnv.rawWindow\n rawWindow.history.pushState = globalEnv.rawPushState\n rawWindow.history.replaceState = globalEnv.rawReplaceState\n}\n","import type {\n Func,\n Router,\n RouterTarget,\n navigationMethod,\n MicroLocation,\n RouterGuard,\n GuardLocation,\n AccurateGuard,\n SetDefaultPageOptions,\n AttachAllToURLParam,\n AppInterface,\n} from '@micro-app/types'\nimport {\n encodeMicroPath,\n decodeMicroPath,\n setMicroPathToURL,\n setMicroState,\n getMicroState,\n getMicroPathFromURL,\n isRouterModeCustom,\n} from './core'\nimport {\n logError,\n logWarn,\n formatAppName,\n createURL,\n isFunction,\n isPlainObject,\n useSetRecord,\n useMapRecord,\n requestIdleCallback,\n isString,\n noopFalse,\n removeDomScope,\n isObject,\n} from '../../libs/utils'\nimport { appInstanceMap } from '../../create_app'\nimport { getActiveApps } from '../../micro_app'\nimport globalEnv from '../../libs/global_env'\nimport { navigateWithNativeEvent, attachRouteToBrowserURL } from './history'\nimport bindFunctionToRawTarget from '../bind_function'\nimport { updateMicroLocationWithEvent } from './event'\n\nexport interface RouterApi {\n router: Router,\n executeNavigationGuard: (appName: string, to: GuardLocation, from: GuardLocation) => void\n clearRouterWhenUnmount: (appName: string) => void\n}\n\nexport interface CreteBaseRouter {\n setBaseAppRouter (baseRouter: unknown): void\n getBaseAppRouter(): unknown\n}\n\nexport interface CreateDefaultPage {\n setDefaultPage(options: SetDefaultPageOptions): () => boolean\n removeDefaultPage(appName: string): boolean\n getDefaultPage(key: PropertyKey): string | void\n}\n\nfunction createRouterApi (): RouterApi {\n /**\n * common handler for router.push/router.replace method\n * @param appName app name\n * @param methodName replaceState/pushState\n * @param targetLocation target location\n * @param state to.state\n */\n function navigateWithRawHistory (\n appName: string,\n methodName: string,\n targetLocation: MicroLocation,\n state: unknown,\n ): void {\n navigateWithNativeEvent(\n appName,\n methodName,\n setMicroPathToURL(\n appName,\n targetLocation,\n ),\n false,\n setMicroState(\n appName,\n state ?? null,\n ),\n )\n // clear element scope after navigate\n removeDomScope()\n }\n\n /**\n * navigation handler\n * @param appName app.name\n * @param app app instance\n * @param to router target options\n * @param replace use router.replace?\n */\n function handleNavigate (\n appName: string,\n app: AppInterface,\n to: RouterTarget,\n replace: boolean,\n ): void {\n const microLocation = app.sandBox!.proxyWindow.location as MicroLocation\n const targetLocation = createURL(to.path, microLocation.href)\n // Only get path data, even if the origin is different from microApp\n const currentFullPath = microLocation.pathname + microLocation.search + microLocation.hash\n const targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n if (currentFullPath !== targetFullPath || getMicroPathFromURL(appName) !== targetFullPath) {\n const methodName = (replace && to.replace !== false) || to.replace === true ? 'replaceState' : 'pushState'\n navigateWithRawHistory(appName, methodName, targetLocation, to.state)\n /**\n * TODO:\n * 1. 关闭虚拟路由的跳转地址不同:baseRoute + 子应用地址,文档中要说明\n * 2. 关闭虚拟路由时跳转方式不同:1、基座跳转但不发送popstate事件 2、控制子应用更新location,内部发送popstate事件。\n * 核心思路:减小对基座的影响(子应用跳转不向基座发送popstate事件,其他操作一致),但这是必要的吗,只是多了一个触发popstate的操作\n * 路由优化方案有两种:\n * 1、减少对基座的影响,主要是解决vue循环刷新的问题\n * 2、全局发送popstate事件,解决主、子都是vue3的冲突问题\n * 两者选一个吧,如果选2,则下面这两行代码可以去掉\n * NOTE1: history和search模式采用2,这样可以解决vue3的问题,custom采用1,避免vue循环刷新的问题,这样在用户出现问题时各有解决方案。但反过来说,每种方案又分别导致另外的问题,不统一,导致复杂度增高\n * NOTE2: 关闭虚拟路由,同时发送popstate事件还是无法解决vue3的问题(毕竟history.state理论上还是会冲突),那么就没必要发送popstate事件了。\n */\n if (isRouterModeCustom(appName)) {\n updateMicroLocationWithEvent(appName, targetFullPath)\n }\n }\n }\n\n /**\n * create method of router.push/replace\n * NOTE:\n * 1. The same fullPath will be blocked\n * 2. name & path is required\n * 3. path is fullPath except for the domain (the domain can be taken, but not valid)\n * @param replace use router.replace?\n */\n function createNavigationMethod (replace: boolean): navigationMethod {\n return function (to: RouterTarget): Promise<void> {\n return new Promise((resolve, reject) => {\n const appName = formatAppName(to.name)\n if (appName && isString(to.path)) {\n /**\n * active apps, exclude prerender app or hidden keep-alive app\n * NOTE:\n * 1. prerender app or hidden keep-alive app clear and record popstate event, so we cannot control app jump through the API\n * 2. disable memory-router\n */\n /**\n * TODO: 子应用开始渲染但是还没渲染完成\n * 1、调用跳转改如何处理\n * 2、iframe的沙箱还没初始化时执行跳转报错,如何处理。。。\n * 3、hidden app 是否支持跳转\n */\n if (getActiveApps({ excludeHiddenApp: true, excludePreRender: true }).includes(appName)) {\n const app = appInstanceMap.get(appName)!\n resolve(app.sandBox.sandboxReady.then(() => handleNavigate(appName, app, to, replace)))\n } else {\n reject(logError('navigation failed, app does not exist or is inactive'))\n }\n\n // /**\n // * app not exit or unmounted, update browser URL with replaceState\n // * use base app location.origin as baseURL\n // * 应用不存在或已卸载,依然使用replaceState来更新浏览器地址 -- 不合理\n // */\n // /**\n // * TODO: 应用还没渲染或已经卸载最好不要支持跳转了,我知道这是因为解决一些特殊场景,但这么做是非常反直觉的\n // * 并且在新版本中有多种路由模式,如果应用不存在,我们根本无法知道是哪种模式,那么这里的操作就无意义了。\n // */\n // const rawLocation = globalEnv.rawWindow.location\n // const targetLocation = createURL(to.path, rawLocation.origin)\n // const targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n // if (getMicroPathFromURL(appName) !== targetFullPath) {\n // navigateWithRawHistory(\n // appName,\n // to.replace === false ? 'pushState' : 'replaceState',\n // targetLocation,\n // to.state,\n // )\n // }\n } else {\n reject(logError(`navigation failed, name & path are required when use router.${replace ? 'replace' : 'push'}`))\n }\n })\n }\n }\n\n // create method of router.go/back/forward\n function createRawHistoryMethod (methodName: string): Func {\n return function (...rests: unknown[]): void {\n return globalEnv.rawWindow.history[methodName](...rests)\n }\n }\n\n const beforeGuards = useSetRecord<RouterGuard>()\n const afterGuards = useSetRecord<RouterGuard>()\n\n /**\n * run all of beforeEach/afterEach guards\n * NOTE:\n * 1. Modify browser url first, and then run guards,\n * consistent with the browser forward & back button\n * 2. Prevent the element binding\n * @param appName app name\n * @param to target location\n * @param from old location\n * @param guards guards list\n */\n function runGuards (\n appName: string,\n to: GuardLocation,\n from: GuardLocation,\n guards: Set<RouterGuard>,\n ) {\n // clear element scope before execute function of parent\n removeDomScope()\n for (const guard of guards) {\n if (isFunction(guard)) {\n guard(to, from, appName)\n } else if (isPlainObject(guard) && isFunction((guard as AccurateGuard)[appName])) {\n guard[appName](to, from)\n }\n }\n }\n\n /**\n * global hook for router\n * update router information base on microLocation\n * @param appName app name\n * @param microLocation location of microApp\n */\n function executeNavigationGuard (\n appName: string,\n to: GuardLocation,\n from: GuardLocation,\n ): void {\n router.current.set(appName, to)\n\n runGuards(appName, to, from, beforeGuards.list())\n\n requestIdleCallback(() => {\n runGuards(appName, to, from, afterGuards.list())\n })\n }\n\n function clearRouterWhenUnmount (appName: string): void {\n router.current.delete(appName)\n }\n\n /**\n * NOTE:\n * 1. app not exits\n * 2. sandbox is disabled\n * 3. router mode is custom\n */\n function commonHandlerForAttachToURL (appName: string): void {\n if (!isRouterModeCustom(appName)) {\n const app = appInstanceMap.get(appName)!\n attachRouteToBrowserURL(\n appName,\n setMicroPathToURL(appName, app.sandBox.proxyWindow.location as MicroLocation),\n setMicroState(appName, getMicroState(appName)),\n )\n }\n }\n\n /**\n * Attach specified active app router info to browser url\n * @param appName app name\n */\n function attachToURL (appName: string): void {\n appName = formatAppName(appName)\n if (appName && getActiveApps().includes(appName)) {\n commonHandlerForAttachToURL(appName)\n }\n }\n\n /**\n * Attach all active app router info to browser url\n * @param includeHiddenApp include hidden keep-alive app\n * @param includePreRender include preRender app\n */\n function attachAllToURL ({\n includeHiddenApp = false,\n includePreRender = false,\n }: AttachAllToURLParam): void {\n getActiveApps({\n excludeHiddenApp: !includeHiddenApp,\n excludePreRender: !includePreRender,\n }).forEach(appName => commonHandlerForAttachToURL(appName))\n }\n\n function createDefaultPageApi (): CreateDefaultPage {\n // defaultPage data\n const defaultPageRecord = useMapRecord<string>()\n\n /**\n * defaultPage only effect when mount, and has lower priority than query on browser url\n * SetDefaultPageOptions {\n * @param name app name\n * @param path page path\n * }\n */\n function setDefaultPage (options: SetDefaultPageOptions): () => boolean {\n const appName = formatAppName(options.name)\n if (!appName || !options.path) {\n if (__DEV__) {\n if (!appName) {\n logWarn(`setDefaultPage: invalid appName \"${appName}\"`)\n } else {\n logWarn('setDefaultPage: path is required')\n }\n }\n return noopFalse\n }\n\n return defaultPageRecord.add(appName, options.path)\n }\n\n function removeDefaultPage (appName: string): boolean {\n appName = formatAppName(appName)\n if (!appName) return false\n\n return defaultPageRecord.delete(appName)\n }\n\n return {\n setDefaultPage,\n removeDefaultPage,\n getDefaultPage: defaultPageRecord.get,\n }\n }\n\n function createBaseRouterApi (): CreteBaseRouter {\n /**\n * Record base app router, let child app control base app navigation\n */\n let baseRouterProxy: unknown = null\n function setBaseAppRouter (baseRouter: unknown): void {\n if (isObject(baseRouter)) {\n baseRouterProxy = new Proxy(baseRouter, {\n get (target: History, key: PropertyKey): unknown {\n removeDomScope()\n return bindFunctionToRawTarget(Reflect.get(target, key), target, 'BASEROUTER')\n },\n set (target: History, key: PropertyKey, value: unknown): boolean {\n Reflect.set(target, key, value)\n return true\n }\n })\n } else if (__DEV__) {\n logWarn('setBaseAppRouter: Invalid base router')\n }\n }\n\n return {\n setBaseAppRouter,\n getBaseAppRouter: () => baseRouterProxy,\n }\n }\n\n // Router API for developer\n const router: Router = {\n current: new Map<string, MicroLocation>(),\n encode: encodeMicroPath,\n decode: decodeMicroPath,\n push: createNavigationMethod(false),\n replace: createNavigationMethod(true),\n go: createRawHistoryMethod('go'),\n back: createRawHistoryMethod('back'),\n forward: createRawHistoryMethod('forward'),\n beforeEach: beforeGuards.add,\n afterEach: afterGuards.add,\n attachToURL,\n attachAllToURL,\n ...createDefaultPageApi(),\n ...createBaseRouterApi(),\n }\n\n return {\n router,\n executeNavigationGuard,\n clearRouterWhenUnmount,\n }\n}\n\nexport const {\n router,\n executeNavigationGuard,\n clearRouterWhenUnmount,\n} = createRouterApi()\n","export const escape2RawWindowKeys = [\n 'getComputedStyle',\n 'visualViewport',\n 'matchMedia',\n // 'DOMParser',\n 'ResizeObserver',\n 'IntersectionObserver',\n // 'dispatchEvent',\n]\n\nexport const escape2RawWindowRegExpKeys = [\n /animationFrame$/i,\n /mutationObserver$/i,\n /height$|width$/i,\n /offset$/i,\n // /event$/i,\n /selection$/i,\n /^range/i,\n /^screen/i,\n /^scroll/i,\n /X$|Y$/,\n // /^(?:HTML\\w*)?Element$/,\n]\n\nexport const uniqueDocumentElement = [\n 'body',\n 'head',\n 'html',\n 'title',\n]\n\nexport const hijackMicroLocationKeys = [\n 'host',\n 'hostname',\n 'port',\n 'protocol',\n 'origin',\n]\n\n// 有shadowRoot则代理到shadowRoot否则代理到原生document上 (属性)\nexport const proxy2RawDocOrShadowKeys = [\n 'childElementCount',\n 'children',\n 'firstElementChild',\n 'firstChild',\n 'lastElementChild',\n 'activeElement', // Element not has, document or shadowRoot has\n 'fullscreenElement', // Element not has, document or shadowRoot has\n 'pictureInPictureElement', // Element not has, document or shadowRoot has\n 'pointerLockElement', // Element not has, document or shadowRoot has\n 'styleSheets', // Element not has, document or shadowRoot has\n]\n\n// 有shadowRoot则代理到shadowRoot否则代理到原生document上 (方法)\nexport const proxy2RawDocOrShadowMethods = [\n 'append',\n 'contains',\n 'replaceChildren',\n 'createRange', // Element not has, document or shadowRoot has\n 'getSelection', // Element not has, document or shadowRoot has\n 'elementFromPoint', // Element not has, document or shadowRoot has\n 'elementsFromPoint', // Element not has, document or shadowRoot has\n 'getAnimations', // Element not has, document or shadowRoot has\n]\n\n// 直接代理到原生document上 (属性)\nexport const proxy2RawDocumentKeys = [\n 'characterSet',\n 'compatMode',\n 'contentType',\n 'designMode',\n 'dir',\n 'doctype',\n 'embeds',\n 'fullscreenEnabled',\n 'hidden',\n 'implementation',\n 'lastModified',\n 'pictureInPictureEnabled',\n 'plugins',\n 'readyState',\n 'referrer',\n 'visibilityState',\n 'fonts',\n]\n\n// 直接代理到原生document上 (方法)\nexport const proxy2RawDocumentMethods = [\n 'execCommand',\n 'createRange',\n 'exitFullscreen',\n 'exitPictureInPicture',\n 'getElementsByTagNameNS',\n 'hasFocus',\n 'prepend',\n // 'dispatchEvent',\n]\n","/* eslint-disable no-void */\nimport type {\n MicroLocation,\n GuardLocation,\n microAppWindowType,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n assign as oAssign,\n createURL,\n rawDefineProperty,\n} from '../../libs/utils'\nimport {\n setMicroPathToURL,\n isEffectiveApp,\n getMicroState,\n isRouterModeCustom,\n} from './core'\nimport {\n dispatchNativeEvent,\n} from './event'\nimport {\n executeNavigationGuard,\n} from './api'\nimport {\n nativeHistoryNavigate,\n navigateWithNativeEvent,\n} from './history'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} from '../../create_app'\nimport {\n hijackMicroLocationKeys,\n} from '../iframe/special_key'\n\n// origin is readonly, so we ignore when updateMicroLocation\nconst locationKeys: ReadonlyArray<keyof MicroLocation> = ['href', 'pathname', 'search', 'hash', 'host', 'hostname', 'port', 'protocol', 'search']\n// origin, fullPath is necessary for guardLocation\nconst guardLocationKeys: ReadonlyArray<keyof MicroLocation> = [...locationKeys, 'origin', 'fullPath']\n\n/**\n * Create location for microApp, each microApp has only one location object, it is a reference type\n * MDN https://developer.mozilla.org/en-US/docs/Web/API/Location\n * @param appName app name\n * @param url app url\n * @param microAppWindow iframeWindow, iframe only\n * @param childStaticLocation real child location info, iframe only\n * @param browserHost host of browser, iframe only\n * @param childHost host of child app, iframe only\n */\nexport function createMicroLocation (\n appName: string,\n url: string,\n microAppWindow?: microAppWindowType,\n childStaticLocation?: MicroLocation,\n browserHost?: string,\n childHost?: string,\n): MicroLocation {\n const rawWindow = globalEnv.rawWindow\n const rawLocation = rawWindow.location\n const isIframe = !!microAppWindow\n /**\n * withLocation is microLocation for with sandbox\n * it is globally unique for child app\n */\n const withLocation = createURL(url)\n\n /**\n * In iframe, jump through raw iframeLocation will cause microAppWindow.location reset\n * So we get location dynamically\n */\n function getTarget (): MicroLocation {\n return isIframe ? microAppWindow.location : withLocation\n }\n\n /**\n * Common handler for href, assign, replace\n * It is mainly used to deal with special scenes about hash\n * @param value target path\n * @param methodName pushState/replaceState\n * @returns origin value or formatted value\n */\n function commonHandler (value: string | URL, methodName: string): string | URL | void {\n const targetLocation = createURL(value, proxyLocation.href)\n // Even if the origin is the same, developers still have the possibility of want to jump to a new page\n if (targetLocation.origin === proxyLocation.origin) {\n const setMicroPathResult = setMicroPathToURL(appName, targetLocation)\n // if disable memory-router, navigate directly through rawLocation\n if (!isRouterModeCustom(appName)) {\n /**\n * change hash with location.href will not trigger the browser reload\n * so we use pushState & reload to imitate href behavior\n * NOTE:\n * 1. if child app only change hash, it should not trigger browser reload\n * 2. if address is same and has hash, it should not add route stack\n */\n if (\n targetLocation.pathname === proxyLocation.pathname &&\n targetLocation.search === proxyLocation.search\n ) {\n let oldHref = null\n if (targetLocation.hash !== proxyLocation.hash) {\n if (setMicroPathResult.isAttach2Hash) oldHref = rawLocation.href\n nativeHistoryNavigate(appName, methodName, setMicroPathResult.fullPath)\n }\n\n if (targetLocation.hash) {\n dispatchNativeEvent(appName, false, oldHref)\n } else {\n reload()\n }\n return void 0\n /**\n * when baseApp is hash router, address change of child can not reload browser\n * so we imitate behavior of browser (reload) manually\n */\n } else if (setMicroPathResult.isAttach2Hash) {\n nativeHistoryNavigate(appName, methodName, setMicroPathResult.fullPath)\n reload()\n return void 0\n }\n }\n\n return setMicroPathResult.fullPath\n }\n\n return value\n }\n\n /**\n * common handler for location.pathname & location.search\n * @param targetPath target fullPath\n * @param key pathname/search\n */\n function handleForPathNameAndSearch (targetPath: string, key: keyof Location): void {\n const targetLocation = createURL(targetPath, url)\n // When the browser url has a hash value, the same pathname/search will not refresh browser\n if (targetLocation[key] === proxyLocation[key] && proxyLocation.hash) {\n // The href has not changed, not need to dispatch hashchange event\n dispatchNativeEvent(appName, false)\n } else {\n /**\n * When the value is the same, no new route stack will be added\n * Special scenes such as:\n * pathname: /path ==> /path#hash, /path ==> /path?query\n * search: ?query ==> ?query#hash\n */\n nativeHistoryNavigate(\n appName,\n targetLocation[key] === proxyLocation[key] ? 'replaceState' : 'pushState',\n setMicroPathToURL(appName, targetLocation).fullPath,\n )\n reload()\n }\n }\n\n const createLocationMethod = (locationMethodName: string) => {\n return function (value: string | URL) {\n if (isEffectiveApp(appName)) {\n const targetPath = commonHandler(value, locationMethodName === 'assign' ? 'pushState' : 'replaceState')\n if (targetPath) {\n // Same as href, complete targetPath with browser origin in vite env\n rawLocation[locationMethodName](createURL(targetPath, rawLocation.origin).href)\n }\n }\n }\n }\n\n const assign = createLocationMethod('assign')\n const replace = createLocationMethod('replace')\n const reload = (forcedReload?: boolean): void => rawLocation.reload(forcedReload)\n\n rawDefineProperty(getTarget(), 'fullPath', {\n enumerable: true,\n configurable: true,\n get: () => proxyLocation.pathname + proxyLocation.search + proxyLocation.hash,\n })\n\n /**\n * location.assign/replace is readonly, cannot be proxy, so we use empty object as proxy target\n */\n const proxyLocation = new Proxy({} as Location, {\n get: (_: Location, key: string): unknown => {\n const target = getTarget()\n if (isIframe) {\n // host hostname port protocol\n if (hijackMicroLocationKeys.includes(key)) {\n return childStaticLocation![key]\n }\n\n if (key === 'href') {\n // do not use target, because target may be deleted\n return target[key].replace(browserHost!, childHost!)\n }\n }\n\n if (key === 'assign') return assign\n if (key === 'replace') return replace\n if (key === 'reload') return reload\n if (key === 'self') return target\n\n return bindFunctionToRawTarget<Location>(Reflect.get(target, key), target, 'LOCATION')\n },\n set: (_: Location, key: string, value: string): boolean => {\n if (isEffectiveApp(appName)) {\n const target = getTarget()\n if (key === 'href') {\n const targetPath = commonHandler(value, 'pushState')\n /**\n * In vite, targetPath without origin will be completed with child origin\n * So we use browser origin to complete targetPath to avoid this problem\n * But, why child app can affect browser jump?\n * Guess(need check):\n * 1. vite records the origin when init\n * 2. listen for browser jump and automatically complete the address\n */\n if (targetPath) {\n rawLocation.href = createURL(targetPath, rawLocation.origin).href\n }\n } else if (key === 'pathname') {\n if (isRouterModeCustom(appName)) {\n rawLocation.pathname = value\n } else {\n const targetPath = ('/' + value).replace(/^\\/+/, '/') + proxyLocation.search + proxyLocation.hash\n handleForPathNameAndSearch(targetPath, 'pathname')\n }\n } else if (key === 'search') {\n if (isRouterModeCustom(appName)) {\n rawLocation.search = value\n } else {\n const targetPath = proxyLocation.pathname + ('?' + value).replace(/^\\?+/, '?') + proxyLocation.hash\n handleForPathNameAndSearch(targetPath, 'search')\n }\n } else if (key === 'hash') {\n if (isRouterModeCustom(appName)) {\n rawLocation.hash = value\n } else {\n const targetPath = proxyLocation.pathname + proxyLocation.search + ('#' + value).replace(/^#+/, '#')\n const targetLocation = createURL(targetPath, url)\n // The same hash will not trigger popStateEvent\n if (targetLocation.hash !== proxyLocation.hash) {\n navigateWithNativeEvent(\n appName,\n 'pushState',\n setMicroPathToURL(appName, targetLocation),\n false,\n )\n }\n }\n } else {\n Reflect.set(target, key, value)\n }\n }\n return true\n },\n })\n\n return proxyLocation as MicroLocation\n}\n\n/**\n * create guardLocation by microLocation, used for router guard\n */\nexport function createGuardLocation (appName: string, microLocation: MicroLocation): GuardLocation {\n const guardLocation = oAssign({ name: appName }, microLocation) as GuardLocation\n // The prototype values on the URL needs to be manually transferred\n for (const key of guardLocationKeys) guardLocation[key] = microLocation[key]\n return guardLocation\n}\n\n// for updateBrowserURLWithLocation when initial\nexport function autoTriggerNavigationGuard (appName: string, microLocation: MicroLocation): void {\n executeNavigationGuard(appName, createGuardLocation(appName, microLocation), createGuardLocation(appName, microLocation))\n}\n\n/**\n * The following scenes will trigger location update:\n * 1. pushState/replaceState\n * 2. popStateEvent\n * 3. query on browser url when init sub app\n * 4. set defaultPage when when init sub app\n * NOTE:\n * 1. update browser URL first, and then update microLocation\n * 2. the same fullPath will not trigger router guards\n * @param appName app name\n * @param path target path\n * @param base base url\n * @param microLocation micro app location\n * @param type auto prevent\n */\nexport function updateMicroLocation (\n appName: string,\n path: string,\n microLocation: MicroLocation,\n type?: string,\n): void {\n // record old values of microLocation to `from`\n const from = createGuardLocation(appName, microLocation)\n // if is iframeSandbox, microLocation muse be rawLocation of iframe, not proxyLocation\n const newLocation = createURL(path, microLocation.href)\n if (isIframeSandbox(appName)) {\n const microAppWindow = appInstanceMap.get(appName)!.sandBox.microAppWindow\n microAppWindow.rawReplaceState?.call(microAppWindow.history, getMicroState(appName), '', newLocation.href)\n } else {\n for (const key of locationKeys) {\n microLocation.self[key] = newLocation[key]\n }\n }\n // update latest values of microLocation to `to`\n const to = createGuardLocation(appName, microLocation)\n\n // The hook called only when fullPath changed\n if (type === 'auto' || (from.fullPath !== to.fullPath && type !== 'prevent')) {\n executeNavigationGuard(appName, to, from)\n }\n}\n","import type {\n MicroRouter,\n MicroLocation,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport {\n getMicroPathFromURL,\n setMicroPathToURL,\n removeMicroPathFromURL,\n removeMicroState,\n setMicroState,\n isRouterModeCustom,\n} from './core'\nimport {\n createMicroLocation,\n updateMicroLocation,\n autoTriggerNavigationGuard,\n} from './location'\nimport {\n createMicroHistory,\n attachRouteToBrowserURL,\n} from './history'\nimport {\n createURL,\n} from '../../libs/utils'\nimport {\n clearRouterWhenUnmount,\n} from './api'\nexport {\n router,\n} from './api'\nexport {\n addHistoryListener,\n} from './event'\nexport {\n getNoHashMicroPathFromURL,\n getRouterMode,\n isRouterModeCustom,\n} from './core'\nexport {\n patchHistory,\n releasePatchHistory,\n} from './history'\n\n/**\n * TODO: 关于关闭虚拟路由系统的临时笔记 - 即custom模式,虚拟路由不支持关闭\n * 1. with沙箱关闭虚拟路由最好和iframe保持一致\n * 2. default-page无法使用,但是用基座的地址可以实现一样的效果\n * 3. keep-router-state功能失效,因为始终为true\n * 4. 基座控制子应用跳转地址改变,正确的值为:baseRoute + 子应用地址,这要在文档中说明,否则很容易出错,确实也很难理解\n * 5. 是否需要发送popstate事件,为了减小对基座的影响,现在不发送\n * 6. 关闭后导致的vue3路由冲突问题需要在文档中明确指出(2处:在关闭虚拟路由系统的配置那里着重说明,在vue常见问题中说明)\n */\n/**\n * The router system has two operations: read and write\n * Read through location and write through history & location\n * @param appName app name\n * @param url app url\n * @returns MicroRouter\n */\nexport function createMicroRouter (appName: string, url: string): MicroRouter {\n const microLocation = createMicroLocation(appName, url)\n return {\n microLocation,\n microHistory: createMicroHistory(appName, microLocation),\n }\n}\n\n/**\n * When the sandbox executes start, or the hidden keep-alive application is re-rendered, the location is updated according to the browser url or attach router info to browser url\n * @param appName app.name\n * @param microLocation MicroLocation for sandbox\n * @param defaultPage default page\n */\nexport function initRouteStateWithURL (\n appName: string,\n microLocation: MicroLocation,\n defaultPage?: string,\n): void {\n const microPath = getMicroPathFromURL(appName)\n if (microPath) {\n updateMicroLocation(appName, microPath, microLocation, 'auto')\n } else {\n updateBrowserURLWithLocation(appName, microLocation, defaultPage)\n }\n}\n\n/**\n * initialize browser information according to microLocation\n * Scenes:\n * 1. sandbox.start\n * 2. reshow of keep-alive app\n */\nexport function updateBrowserURLWithLocation (\n appName: string,\n microLocation: MicroLocation,\n defaultPage?: string,\n): void {\n // update microLocation with defaultPage\n if (defaultPage) updateMicroLocation(appName, defaultPage, microLocation, 'prevent')\n // attach microApp route info to browser URL\n attachRouteToBrowserURL(\n appName,\n setMicroPathToURL(appName, microLocation),\n setMicroState(\n appName,\n null,\n ),\n )\n // trigger guards after change browser URL\n autoTriggerNavigationGuard(appName, microLocation)\n}\n\n/**\n * In any case, microPath & microState will be removed from browser, but location will be initialized only when keep-router-state is false\n * @param appName app name\n * @param url app url\n * @param microLocation location of microApp\n * @param keepRouteState keep-router-state is only used to control whether to clear the location of microApp, default is false\n */\nexport function clearRouteStateFromURL (\n appName: string,\n url: string,\n microLocation: MicroLocation,\n keepRouteState: boolean,\n): void {\n if (!isRouterModeCustom(appName)) {\n if (!keepRouteState) {\n const { pathname, search, hash } = createURL(url)\n updateMicroLocation(appName, pathname + search + hash, microLocation, 'prevent')\n }\n removePathFromBrowser(appName)\n }\n\n clearRouterWhenUnmount(appName)\n}\n\n/**\n * remove microState from history.state and remove microPath from browserURL\n * called on sandbox.stop or hidden of keep-alive app\n */\nexport function removePathFromBrowser (appName: string): void {\n attachRouteToBrowserURL(\n appName,\n removeMicroPathFromURL(appName),\n removeMicroState(appName, globalEnv.rawWindow.history.state),\n )\n}\n","import type {\n SandBoxAdapter,\n AppInterface,\n} from '@micro-app/types'\nimport globalEnv from '../libs/global_env'\nimport {\n defer,\n isNode,\n rawDefineProperties,\n rawDefineProperty,\n throttleDeferForSetAppName,\n isMicroAppBody,\n} from '../libs/utils'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} from '../create_app'\nimport microApp from '../micro_app'\n\nexport default class Adapter implements SandBoxAdapter {\n constructor () {\n this.injectReactHMRProperty()\n }\n\n // keys that can only assigned to rawWindow\n public escapeSetterKeyList: PropertyKey[] = [\n 'location',\n ]\n\n // keys that can escape to rawWindow\n public staticEscapeProperties: PropertyKey[] = [\n 'System',\n '__cjsWrapper',\n ]\n\n // keys that scoped in child app\n public staticScopeProperties: PropertyKey[] = [\n 'webpackJsonp',\n 'webpackHotUpdate',\n 'Vue',\n ]\n\n // adapter for react\n private injectReactHMRProperty (): void {\n if (__DEV__) {\n // react child in non-react env\n this.staticEscapeProperties.push('__REACT_ERROR_OVERLAY_GLOBAL_HOOK__')\n // in react parent\n if (globalEnv.rawWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__) {\n this.staticScopeProperties = this.staticScopeProperties.concat([\n '__REACT_ERROR_OVERLAY_GLOBAL_HOOK__',\n '__reactRefreshInjected',\n ])\n }\n }\n }\n}\n\n// Fix conflict of babel-polyfill@6.x\nexport function fixBabelPolyfill6 (): void {\n if (globalEnv.rawWindow._babelPolyfill) globalEnv.rawWindow._babelPolyfill = false\n}\n\n/**\n * Fix error of hot reload when parent&child created by create-react-app in development environment\n * Issue: https://github.com/micro-zoe/micro-app/issues/382\n */\nexport function fixReactHMRConflict (app: AppInterface): void {\n if (__DEV__) {\n const rawReactErrorHook = globalEnv.rawWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__\n const childReactErrorHook = app.sandBox?.proxyWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__\n if (rawReactErrorHook && childReactErrorHook) {\n globalEnv.rawWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__ = childReactErrorHook\n defer(() => {\n globalEnv.rawWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__ = rawReactErrorHook\n })\n }\n }\n}\n\n/**\n * update dom tree of target dom\n * @param container target dom\n * @param appName app name\n */\nexport function patchElementTree (container: Element | ShadowRoot, appName: string): void {\n const children = Array.from(container.children)\n\n children.length && children.forEach((child) => {\n patchElementTree(child, appName)\n })\n\n for (const child of children) {\n updateElementInfo(child, appName)\n }\n}\n\n/**\n * rewrite baseURI, ownerDocument, __MICRO_APP_NAME__ of target node\n * @param node target node\n * @param appName app name\n * @returns target node\n */\nexport function updateElementInfo <T> (node: T, appName: string): T {\n const proxyWindow = appInstanceMap.get(appName)?.sandBox?.proxyWindow\n if (\n isNode(node) &&\n !node.__MICRO_APP_NAME__ &&\n !node.__PURE_ELEMENT__ &&\n proxyWindow\n ) {\n /**\n * TODO:\n * 1. 测试baseURI和ownerDocument在with沙箱中是否正确\n * 经过验证with沙箱不能重写ownerDocument,否则react点击事件会触发两次\n * 2. with沙箱所有node设置__MICRO_APP_NAME__都使用updateElementInfo\n */\n rawDefineProperties(node, {\n baseURI: {\n configurable: true,\n get: () => proxyWindow.location.href,\n },\n __MICRO_APP_NAME__: {\n configurable: true,\n writable: true,\n value: appName,\n },\n })\n\n if (isIframeSandbox(appName)) {\n /**\n * If HTML built-in node belongs to base app, it needs to be handled separately for parentNode\n * Fix error for nuxt@2.x + ElementUI@2.x\n */\n if (node instanceof globalEnv.rawRootNode) {\n rawDefineProperty(node, 'parentNode', {\n configurable: true,\n get: createGetterForIframeParentNode(\n appName,\n globalEnv.rawParentNodeDesc,\n true,\n )\n })\n }\n }\n }\n\n return node\n}\n\n/**\n * patch iframe node parentNode\n * Scenes:\n * 1. iframe common node: patch Node.prototype.parentNode to hijack parentNode\n * 2. iframe HTML built-in node: belongs to base app, we should rewrite parentNode for every built-in node\n * NOTE:\n * 1. HTML built-in node parentNode cannot point to raw body, otherwise Vue2 will render failed\n * @param appName app name\n * @param parentNode parentNode Descriptor of iframe or browser\n * @param HTMLBuildInNode is HTML built-in node\n */\nexport function createGetterForIframeParentNode (\n appName: string,\n parentNodeDesc: PropertyDescriptor,\n HTMLBuildInNode?: boolean,\n): () => ParentNode {\n return function (this: Node) {\n /**\n * set current appName for hijack parentNode of html\n * NOTE:\n * 1. Is there a problem with setting the current appName in iframe mode\n */\n throttleDeferForSetAppName(appName)\n const result: ParentNode = parentNodeDesc.get!.call(this)\n /**\n * If parentNode is <micro-app-body>, return rawDocument.body\n * Scenes:\n * 1. element-ui@2/lib/utils/vue-popper.js\n * if (this.popperElm.parentNode === document.body) ...\n * WARNING:\n * Will it cause other problems ?\n * e.g. target.parentNode.remove(target)\n */\n if (\n !HTMLBuildInNode &&\n isMicroAppBody(result) &&\n appInstanceMap.get(appName)?.container\n ) {\n return microApp.options.getRootElementParentNode?.(this, appName) || globalEnv.rawDocument.body\n }\n return result\n }\n}\n","import globalEnv from '../libs/global_env'\nimport {\n isFunction,\n isUndefined,\n isString,\n createURL,\n isURL,\n removeDomScope,\n isConstructor,\n} from '../libs/utils'\n\n/**\n * https://developer.mozilla.org/en-US/docs/Web/API/fetch\n * Promise<Response> fetch(input[, init])\n * input: string/Request\n * init?: object\n * @param url app url\n * @param target proxy target\n */\nexport function createMicroFetch (url: string, target?: Window['fetch']): Window['fetch'] {\n const rawFetch = !isUndefined(target) ? target : globalEnv.rawWindow.fetch\n if (!isFunction(rawFetch)) return rawFetch\n return function microFetch (\n input: RequestInfo | URL | string,\n init?: RequestInit,\n ...rests: unknown[]\n ): Promise<Response> {\n if (isString(input) || isURL(input)) {\n input = createURL(input, url).toString()\n }\n /**\n * When fetch rewrite by baseApp, domScope still active when exec rawWindow.fetch\n * If baseApp operate dom in fetch, it will cause error\n * The same for XMLHttpRequest, EventSource\n */\n removeDomScope()\n return rawFetch.call(globalEnv.rawWindow, input, init, ...rests)\n }\n}\n\n/**\n * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest\n * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest\n * @param url app url\n * @param target proxy target\n */\nexport function createMicroXMLHttpRequest (url: string, target?: XMLHttpRequest): any {\n const rawXMLHttpRequest = !isUndefined(target) ? target : globalEnv.rawWindow.XMLHttpRequest\n if (!isConstructor(rawXMLHttpRequest)) return rawXMLHttpRequest\n return class MicroXMLHttpRequest extends rawXMLHttpRequest {\n open (method: string, reqUrl: string, ...rests: unknown[]): void {\n if ((isString(reqUrl) && !/^f(ile|tp):\\/\\//.test(reqUrl)) || isURL(reqUrl)) {\n reqUrl = createURL(reqUrl, url).toString()\n }\n removeDomScope()\n super.open(method, reqUrl, ...rests)\n }\n }\n}\n\nexport interface EventSourceInstance {\n close(): void;\n}\n\nexport interface EventSourceApi {\n createMicroEventSource(appName: string, url: string, target?: EventSource): any\n clearMicroEventSource (appName: string): void\n}\n\nexport function useMicroEventSource (): EventSourceApi {\n let eventSourceMap: Map<string, Set<EventSourceInstance>>\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/API/EventSource\n * pc = new EventSource(url[, configuration])\n * url: string/Request\n * configuration?: object\n * @param url app url\n * @param target proxy target\n */\n function createMicroEventSource (appName: string, url: string, target?: EventSource): any {\n const rawEventSource = !isUndefined(target) ? target : globalEnv.rawWindow.EventSource\n if (!isConstructor(rawEventSource)) return rawEventSource\n return class MicroEventSource extends rawEventSource {\n constructor (\n eventSourceUrl: string | URL,\n eventSourceInitDict?: EventSourceInit,\n ...rests: unknown[]\n ) {\n if (isString(eventSourceUrl) || isURL(eventSourceUrl)) {\n eventSourceUrl = createURL(eventSourceUrl, url).toString()\n }\n removeDomScope()\n super(eventSourceUrl, eventSourceInitDict, ...rests)\n\n if (eventSourceMap) {\n const eventSourceList = eventSourceMap.get(appName)\n if (eventSourceList) {\n eventSourceList.add(this)\n } else {\n eventSourceMap.set(appName, new Set([this]))\n }\n } else {\n eventSourceMap = new Map([[appName, new Set([this])]])\n }\n }\n\n close (): void {\n super.close()\n eventSourceMap.get(appName)?.delete(this)\n }\n }\n }\n\n function clearMicroEventSource (appName: string): void {\n const eventSourceList = eventSourceMap?.get(appName)\n if (eventSourceList?.size) {\n eventSourceList.forEach(item => {\n item.close()\n })\n eventSourceList.clear()\n }\n }\n\n return {\n createMicroEventSource,\n clearMicroEventSource,\n }\n}\n","import type {\n microAppWindowType,\n WithSandBoxInterface,\n plugins,\n MicroLocation,\n SandBoxAdapter,\n SandBoxStartParams,\n SandBoxStopParams,\n CommonEffectHook,\n releaseGlobalEffectParams,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport microApp from '../../micro_app'\nimport {\n EventCenterForMicroApp,\n rebuildDataCenterSnapshot,\n recordDataCenterSnapshot,\n resetDataCenterSnapshot,\n} from '../../interact'\nimport {\n initEnvOfNestedApp,\n} from '../../libs/nest_app'\nimport {\n GLOBAL_KEY_TO_WINDOW\n} from '../../constants'\nimport {\n getEffectivePath,\n isArray,\n isPlainObject,\n removeDomScope,\n throttleDeferForSetAppName,\n rawDefineProperty,\n rawDefineProperties,\n rawHasOwnProperty,\n pureCreateElement,\n assign,\n} from '../../libs/utils'\nimport {\n patchDocument,\n} from './document'\nimport {\n patchWindow,\n} from './window'\nimport {\n patchElementAndDocument,\n releasePatchElementAndDocument,\n} from '../../source/patch'\nimport {\n router,\n createMicroRouter,\n initRouteStateWithURL,\n clearRouteStateFromURL,\n addHistoryListener,\n removePathFromBrowser,\n updateBrowserURLWithLocation,\n patchHistory,\n releasePatchHistory,\n isRouterModeCustom,\n} from '../router'\nimport Adapter, {\n fixBabelPolyfill6,\n patchElementTree,\n} from '../adapter'\nimport {\n createMicroFetch,\n useMicroEventSource,\n createMicroXMLHttpRequest,\n} from '../request'\n\n// TODO: 放到global.d.ts\nexport type MicroAppWindowDataType = {\n __MICRO_APP_ENVIRONMENT__: boolean,\n __MICRO_APP_NAME__: string,\n __MICRO_APP_URL__: string,\n __MICRO_APP_PUBLIC_PATH__: string,\n __MICRO_APP_BASE_URL__: string,\n __MICRO_APP_BASE_ROUTE__: string,\n __MICRO_APP_UMD_MODE__: boolean,\n __MICRO_APP_PRE_RENDER__: boolean\n __MICRO_APP_STATE__: string\n microApp: EventCenterForMicroApp,\n rawWindow: Window,\n rawDocument: Document,\n removeDomScope: () => void,\n}\n\nexport type MicroAppWindowType = Window & MicroAppWindowDataType\nexport type proxyWindow = WindowProxy & MicroAppWindowDataType\n\nconst { createMicroEventSource, clearMicroEventSource } = useMicroEventSource()\n\nexport default class WithSandBox implements WithSandBoxInterface {\n static activeCount = 0 // number of active sandbox\n private active = false\n private windowEffect!: CommonEffectHook\n private documentEffect!: CommonEffectHook\n private removeHistoryListener!: CallableFunction\n public adapter!: SandBoxAdapter\n /**\n * Scoped global Properties(Properties that can only get and set in microAppWindow, will not escape to rawWindow)\n * Fix https://github.com/micro-zoe/micro-app/issues/234\n */\n public scopeProperties: PropertyKey[] = []\n // Properties that can be escape to rawWindow\n public escapeProperties: PropertyKey[] = []\n // Properties escape to rawWindow, cleared when unmount\n public escapeKeys = new Set<PropertyKey>()\n // Properties newly added to microAppWindow\n public injectedKeys = new Set<PropertyKey>()\n public sandboxReady!: Promise<void>\n public proxyWindow!: proxyWindow // Proxy\n public microAppWindow = new EventTarget() as MicroAppWindowType // Proxy target\n\n constructor (appName: string, url: string) {\n this.patchWith((resolve: CallableFunction) => {\n this.adapter = new Adapter()\n // get scopeProperties and escapeProperties from plugins\n this.getSpecialProperties(appName)\n // create location, history for child app\n this.patchRouter(appName, url, this.microAppWindow)\n // patch window of child app\n this.windowEffect = patchWindow(appName, this.microAppWindow, this)\n // patch document of child app\n this.documentEffect = patchDocument(appName, this.microAppWindow, this)\n // inject global properties\n this.initStaticGlobalKeys(appName, url, this.microAppWindow)\n resolve()\n })\n }\n\n /**\n * open sandbox and perform some initial actions\n * @param umdMode is umd mode\n * @param baseroute base route for child\n * @param defaultPage default page when mount child base on virtual router\n * @param disablePatchRequest prevent patchRequestApi\n */\n public start ({\n umdMode,\n baseroute,\n defaultPage,\n disablePatchRequest,\n }: SandBoxStartParams): void {\n if (this.active) return\n this.active = true\n\n /* --- memory router part --- start */\n // update microLocation, attach route info to browser url\n this.initRouteState(defaultPage)\n\n // unique listener of popstate event for sub app\n this.removeHistoryListener = addHistoryListener(\n this.microAppWindow.__MICRO_APP_NAME__,\n )\n\n if (isRouterModeCustom(this.microAppWindow.__MICRO_APP_NAME__)) {\n this.microAppWindow.__MICRO_APP_BASE_ROUTE__ = this.microAppWindow.__MICRO_APP_BASE_URL__ = baseroute\n }\n /* --- memory router part --- end */\n\n /**\n * Target: Ensure default mode action exactly same to first time when render again\n * 1. The following globalKey maybe modified when render, reset them when render again in default mode\n * 2. Umd mode will not delete any keys during sandBox.stop, ignore umd mode\n * 3. When sandbox.start called for the first time, it must be the default mode\n */\n if (!umdMode) {\n this.initGlobalKeysWhenStart(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.__MICRO_APP_URL__,\n this.microAppWindow,\n disablePatchRequest,\n )\n }\n\n if (++globalEnv.activeSandbox === 1) {\n patchElementAndDocument()\n patchHistory()\n }\n\n if (++WithSandBox.activeCount === 1) {\n // effectDocumentEvent()\n initEnvOfNestedApp()\n }\n\n fixBabelPolyfill6()\n }\n\n /**\n * close sandbox and perform some clean up actions\n * @param umdMode is umd mode\n * @param keepRouteState prevent reset route\n * @param destroy completely destroy, delete cache resources\n * @param clearData clear data from base app\n */\n public stop ({\n umdMode,\n keepRouteState,\n destroy,\n clearData,\n }: SandBoxStopParams): void {\n if (!this.active) return\n this.recordAndReleaseEffect({ umdMode, clearData, destroy }, !umdMode || destroy)\n\n /* --- memory router part --- start */\n // rest url and state of browser\n this.clearRouteState(keepRouteState)\n\n // release listener of popstate for child app\n this.removeHistoryListener?.()\n /* --- memory router part --- end */\n\n /**\n * NOTE:\n * 1. injectedKeys and escapeKeys must be placed at the back\n * 2. if key in initial microAppWindow, and then rewrite, this key will be delete from microAppWindow when stop, and lost when restart\n * 3. umd mode will not delete global keys\n */\n if (!umdMode || destroy) {\n clearMicroEventSource(this.microAppWindow.__MICRO_APP_NAME__)\n\n this.injectedKeys.forEach((key: PropertyKey) => {\n Reflect.deleteProperty(this.microAppWindow, key)\n })\n this.injectedKeys.clear()\n\n this.escapeKeys.forEach((key: PropertyKey) => {\n Reflect.deleteProperty(globalEnv.rawWindow, key)\n })\n this.escapeKeys.clear()\n }\n\n if (--globalEnv.activeSandbox === 0) {\n releasePatchElementAndDocument()\n releasePatchHistory()\n }\n\n if (--WithSandBox.activeCount === 0) {\n // releaseEffectDocumentEvent()\n }\n\n this.active = false\n }\n\n /**\n * inject global properties to microAppWindow\n * @param appName app name\n * @param url app url\n * @param microAppWindow micro window\n */\n private initStaticGlobalKeys (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n ): void {\n microAppWindow.__MICRO_APP_ENVIRONMENT__ = true\n microAppWindow.__MICRO_APP_NAME__ = appName\n microAppWindow.__MICRO_APP_URL__ = url\n microAppWindow.__MICRO_APP_PUBLIC_PATH__ = getEffectivePath(url)\n microAppWindow.__MICRO_APP_BASE_ROUTE__ = ''\n microAppWindow.__MICRO_APP_WINDOW__ = microAppWindow\n microAppWindow.__MICRO_APP_PRE_RENDER__ = false\n microAppWindow.__MICRO_APP_UMD_MODE__ = false\n microAppWindow.__MICRO_APP_SANDBOX__ = this\n microAppWindow.__MICRO_APP_SANDBOX_TYPE__ = 'with'\n microAppWindow.rawWindow = globalEnv.rawWindow\n microAppWindow.rawDocument = globalEnv.rawDocument\n microAppWindow.microApp = assign(new EventCenterForMicroApp(appName), {\n removeDomScope,\n pureCreateElement,\n router,\n })\n this.setMappingPropertiesWithRawDescriptor(microAppWindow)\n }\n\n /**\n * Record global effect and then release (effect: global event, timeout, data listener)\n * Scenes:\n * 1. unmount of default/umd app\n * 2. hidden keep-alive app\n * 3. after init prerender app\n * @param options {\n * @param clearData clear data from base app\n * @param isPrerender is prerender app\n * @param keepAlive is keep-alive app\n * }\n * @param preventRecord prevent record effect events\n */\n public recordAndReleaseEffect (\n options: releaseGlobalEffectParams,\n preventRecord = false,\n ): void {\n if (preventRecord) {\n this.resetEffectSnapshot()\n } else {\n this.recordEffectSnapshot()\n }\n this.releaseGlobalEffect(options)\n }\n\n /**\n * reset effect snapshot data in default mode or destroy\n * Scenes:\n * 1. unmount hidden keep-alive app manually\n * 2. unmount prerender app manually\n */\n public resetEffectSnapshot (): void {\n this.windowEffect.reset()\n this.documentEffect.reset()\n resetDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n /**\n * record umd snapshot before the first execution of umdHookMount\n * Scenes:\n * 1. exec umdMountHook in umd mode\n * 2. hidden keep-alive app\n * 3. after init prerender app\n */\n public recordEffectSnapshot (): void {\n this.windowEffect.record()\n this.documentEffect.record()\n recordDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n // rebuild umd snapshot before remount umd app\n public rebuildEffectSnapshot (): void {\n this.windowEffect.rebuild()\n this.documentEffect.rebuild()\n rebuildDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n /**\n * clear global event, timeout, data listener\n * Scenes:\n * 1. unmount of default/umd app\n * 2. hidden keep-alive app\n * 3. after init prerender app\n * @param umdMode is umd mode\n * @param clearData clear data from base app\n * @param isPrerender is prerender app\n * @param keepAlive is keep-alive app\n * @param destroy completely destroy\n */\n public releaseGlobalEffect ({\n umdMode = false,\n clearData = false,\n isPrerender = false,\n keepAlive = false,\n destroy = false,\n }: releaseGlobalEffectParams): void {\n // default mode(not keep-alive or isPrerender)\n this.windowEffect.release((!umdMode && !keepAlive && !isPrerender) || destroy)\n this.documentEffect.release()\n this.microAppWindow.microApp?.clearDataListener()\n this.microAppWindow.microApp?.clearGlobalDataListener()\n if (clearData) {\n microApp.clearData(this.microAppWindow.__MICRO_APP_NAME__)\n this.microAppWindow.microApp?.clearData()\n }\n }\n\n /**\n * get scopeProperties and escapeProperties from plugins & adapter\n * @param appName app name\n */\n private getSpecialProperties (appName: string): void {\n this.scopeProperties = this.scopeProperties.concat(this.adapter.staticScopeProperties)\n if (isPlainObject(microApp.options.plugins)) {\n this.commonActionForSpecialProperties(microApp.options.plugins.global)\n this.commonActionForSpecialProperties(microApp.options.plugins.modules?.[appName])\n }\n }\n\n // common action for global plugins and module plugins\n private commonActionForSpecialProperties (plugins: plugins['global']) {\n if (isArray(plugins)) {\n for (const plugin of plugins) {\n if (isPlainObject(plugin)) {\n if (isArray(plugin.scopeProperties)) {\n this.scopeProperties = this.scopeProperties.concat(plugin.scopeProperties)\n }\n if (isArray(plugin.escapeProperties)) {\n this.escapeProperties = this.escapeProperties.concat(plugin.escapeProperties)\n }\n }\n }\n }\n }\n\n // set __MICRO_APP_PRE_RENDER__ state\n public setPreRenderState (state: boolean): void {\n this.microAppWindow.__MICRO_APP_PRE_RENDER__ = state\n }\n\n public markUmdMode (state: boolean): void {\n this.microAppWindow.__MICRO_APP_UMD_MODE__ = state\n }\n\n private patchWith (cb: CallableFunction): void {\n this.sandboxReady = new Promise<void>((resolve) => cb(resolve))\n }\n\n // properties associated with the native window\n private setMappingPropertiesWithRawDescriptor (microAppWindow: microAppWindowType): void {\n let topValue: Window, parentValue: Window\n const rawWindow = globalEnv.rawWindow\n if (rawWindow === rawWindow.parent) { // not in iframe\n topValue = parentValue = this.proxyWindow\n } else { // in iframe\n topValue = rawWindow.top\n parentValue = rawWindow.parent\n }\n\n // TODO: 用rawDefineProperties\n rawDefineProperty(\n microAppWindow,\n 'top',\n this.createDescriptorForMicroAppWindow('top', topValue)\n )\n\n rawDefineProperty(\n microAppWindow,\n 'parent',\n this.createDescriptorForMicroAppWindow('parent', parentValue)\n )\n\n GLOBAL_KEY_TO_WINDOW.forEach((key: PropertyKey) => {\n rawDefineProperty(\n microAppWindow,\n key,\n this.createDescriptorForMicroAppWindow(key, this.proxyWindow)\n )\n })\n }\n\n private createDescriptorForMicroAppWindow (key: PropertyKey, value: unknown): PropertyDescriptor {\n const { configurable = true, enumerable = true, writable, set } = Object.getOwnPropertyDescriptor(globalEnv.rawWindow, key) || { writable: true }\n const descriptor: PropertyDescriptor = {\n value,\n configurable,\n enumerable,\n writable: writable ?? !!set\n }\n\n return descriptor\n }\n\n /**\n * init global properties of microAppWindow when exec sandBox.start\n * @param microAppWindow micro window\n * @param appName app name\n * @param url app url\n * @param disablePatchRequest prevent rewrite request method of child app\n */\n private initGlobalKeysWhenStart (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n disablePatchRequest: boolean,\n ): void {\n microAppWindow.hasOwnProperty = (key: PropertyKey) => rawHasOwnProperty.call(microAppWindow, key) || rawHasOwnProperty.call(globalEnv.rawWindow, key)\n this.setHijackProperty(appName, microAppWindow)\n if (!disablePatchRequest) this.patchRequestApi(appName, url, microAppWindow)\n this.setScopeProperties(microAppWindow)\n }\n\n // set hijack Properties to microAppWindow\n private setHijackProperty (appName: string, microAppWindow: microAppWindowType): void {\n let modifiedEval: unknown, modifiedImage: unknown\n rawDefineProperties(microAppWindow, {\n eval: {\n configurable: true,\n enumerable: false,\n get () {\n throttleDeferForSetAppName(appName)\n return modifiedEval || globalEnv.rawWindow.eval\n },\n set: (value) => {\n modifiedEval = value\n },\n },\n Image: {\n configurable: true,\n enumerable: false,\n get () {\n throttleDeferForSetAppName(appName)\n return modifiedImage || globalEnv.ImageProxy\n },\n set: (value) => {\n modifiedImage = value\n },\n },\n })\n }\n\n // rewrite fetch, XMLHttpRequest, EventSource\n private patchRequestApi (appName: string, url: string, microAppWindow: microAppWindowType): void {\n let microFetch = createMicroFetch(url)\n let microXMLHttpRequest = createMicroXMLHttpRequest(url)\n let microEventSource = createMicroEventSource(appName, url)\n\n rawDefineProperties(microAppWindow, {\n fetch: {\n configurable: true,\n enumerable: true,\n get () {\n return microFetch\n },\n set (value) {\n microFetch = createMicroFetch(url, value)\n },\n },\n XMLHttpRequest: {\n configurable: true,\n enumerable: true,\n get () {\n return microXMLHttpRequest\n },\n set (value) {\n microXMLHttpRequest = createMicroXMLHttpRequest(url, value)\n },\n },\n EventSource: {\n configurable: true,\n enumerable: true,\n get () {\n return microEventSource\n },\n set (value) {\n microEventSource = createMicroEventSource(appName, url, value)\n },\n },\n })\n }\n\n /**\n * Init scope keys to microAppWindow, prevent fall to rawWindow from with(microAppWindow)\n * like: if (!xxx) {}\n * NOTE:\n * 1. Symbol.unscopables cannot affect undefined keys\n * 2. Doesn't use for window.xxx because it fall to proxyWindow\n */\n setScopeProperties (microAppWindow: microAppWindowType): void {\n this.scopeProperties.forEach((key: PropertyKey) => {\n Reflect.set(microAppWindow, key, microAppWindow[key])\n })\n }\n\n // set location & history for memory router\n private patchRouter (appName: string, url: string, microAppWindow: microAppWindowType): void {\n const { microLocation, microHistory } = createMicroRouter(appName, url)\n rawDefineProperties(microAppWindow, {\n location: {\n configurable: false,\n enumerable: true,\n get () {\n return microLocation\n },\n set: (value) => {\n globalEnv.rawWindow.location = value\n },\n },\n history: {\n configurable: true,\n enumerable: true,\n get () {\n return microHistory\n },\n },\n })\n }\n\n private initRouteState (defaultPage: string): void {\n initRouteStateWithURL(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.location as MicroLocation,\n defaultPage,\n )\n }\n\n private clearRouteState (keepRouteState: boolean): void {\n clearRouteStateFromURL(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.__MICRO_APP_URL__,\n this.microAppWindow.location as MicroLocation,\n keepRouteState,\n )\n }\n\n public setRouteInfoForKeepAliveApp (): void {\n updateBrowserURLWithLocation(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.location as MicroLocation,\n )\n }\n\n public removeRouteInfoForKeepAliveApp (): void {\n removePathFromBrowser(this.microAppWindow.__MICRO_APP_NAME__)\n }\n\n /**\n * Format all html elements when init\n * @param container micro app container\n */\n public patchStaticElement (container: Element | ShadowRoot): void {\n patchElementTree(container, this.microAppWindow.__MICRO_APP_NAME__)\n }\n\n /**\n * action before exec scripts when mount\n * Actions:\n * 1. patch static elements from html\n * @param container micro app container\n */\n public actionBeforeExecScripts (container: Element | ShadowRoot): void {\n this.patchStaticElement(container)\n }\n\n public setStaticAppState (state: string): void {\n this.microAppWindow.__MICRO_APP_STATE__ = state\n }\n}\n","import type {\n microAppWindowType,\n MicroEventListener,\n CommonEffectHook,\n} from '@micro-app/types'\nimport type IframeSandbox from './index'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n rawDefineProperty,\n isFunction,\n logWarn,\n} from '../../libs/utils'\nimport {\n GLOBAL_KEY_TO_WINDOW,\n SCOPE_WINDOW_EVENT,\n SCOPE_WINDOW_ON_EVENT,\n} from '../../constants'\nimport {\n escape2RawWindowKeys,\n escape2RawWindowRegExpKeys,\n} from './special_key'\n\n/**\n * patch window of child app\n * @param appName app name\n * @param microAppWindow microWindow of child app\n * @param sandbox WithSandBox\n * @returns EffectHook\n */\nexport function patchWindow (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): CommonEffectHook {\n patchWindowProperty(appName, microAppWindow)\n createProxyWindow(microAppWindow, sandbox)\n return patchWindowEffect(microAppWindow)\n}\n/**\n * rewrite special properties of window\n * @param appName app name\n * @param microAppWindow child app microWindow\n */\nfunction patchWindowProperty (\n appName: string,\n microAppWindow: microAppWindowType,\n):void {\n const rawWindow = globalEnv.rawWindow\n\n escape2RawWindowKeys.forEach((key: string) => {\n microAppWindow[key] = bindFunctionToRawTarget(rawWindow[key], rawWindow)\n })\n\n Object.getOwnPropertyNames(microAppWindow)\n .filter((key: string) => {\n escape2RawWindowRegExpKeys.some((reg: RegExp) => {\n if (reg.test(key) && key in microAppWindow.parent) {\n if (isFunction(rawWindow[key])) {\n microAppWindow[key] = bindFunctionToRawTarget(rawWindow[key], rawWindow)\n } else {\n const { configurable, enumerable } = Object.getOwnPropertyDescriptor(microAppWindow, key) || {\n configurable: true,\n enumerable: true,\n }\n if (configurable) {\n rawDefineProperty(microAppWindow, key, {\n configurable,\n enumerable,\n get: () => rawWindow[key],\n set: (value) => { rawWindow[key] = value },\n })\n }\n }\n return true\n }\n return false\n })\n\n return /^on/.test(key) && !SCOPE_WINDOW_ON_EVENT.includes(key)\n })\n .forEach((eventName: string) => {\n const { enumerable, writable, set } = Object.getOwnPropertyDescriptor(microAppWindow, eventName) || {\n enumerable: true,\n writable: true,\n }\n try {\n rawDefineProperty(microAppWindow, eventName, {\n enumerable,\n configurable: true,\n get: () => rawWindow[eventName],\n set: writable ?? !!set\n ? (value) => { rawWindow[eventName] = isFunction(value) ? value.bind(microAppWindow) : value }\n : undefined,\n })\n } catch (e) {\n logWarn(e, appName)\n }\n })\n}\n\n/**\n * create proxyWindow with Proxy(microAppWindow)\n * @param microAppWindow micro app window\n * @param sandbox IframeSandbox\n */\nfunction createProxyWindow (\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): void {\n const rawWindow = globalEnv.rawWindow\n const customProperties: PropertyKey[] = []\n\n const proxyWindow = new Proxy(microAppWindow, {\n get: (target: microAppWindowType, key: PropertyKey): unknown => {\n if (key === 'location') {\n return sandbox.proxyLocation\n }\n\n if (GLOBAL_KEY_TO_WINDOW.includes(key.toString())) {\n return proxyWindow\n }\n\n if (customProperties.includes(key)) {\n return Reflect.get(target, key)\n }\n\n return bindFunctionToRawTarget(Reflect.get(target, key), target)\n },\n set: (target: microAppWindowType, key: PropertyKey, value: unknown): boolean => {\n if (key === 'location') {\n return Reflect.set(rawWindow, key, value)\n }\n\n if (!Reflect.has(target, key)) {\n customProperties.push(key)\n }\n\n Reflect.set(target, key, value)\n\n if (sandbox.escapeProperties.includes(key)) {\n !Reflect.has(rawWindow, key) && sandbox.escapeKeys.add(key)\n Reflect.set(rawWindow, key, value)\n }\n\n return true\n },\n has: (target: microAppWindowType, key: PropertyKey) => key in target,\n deleteProperty: (target: microAppWindowType, key: PropertyKey): boolean => {\n if (Reflect.has(target, key)) {\n sandbox.escapeKeys.has(key) && Reflect.deleteProperty(rawWindow, key)\n return Reflect.deleteProperty(target, key)\n }\n return true\n },\n })\n\n sandbox.proxyWindow = proxyWindow\n}\n\nfunction patchWindowEffect (microAppWindow: microAppWindowType): CommonEffectHook {\n const { rawWindow, rawAddEventListener, rawRemoveEventListener } = globalEnv\n const eventListenerMap = new Map<string, Set<MicroEventListener>>()\n const sstEventListenerMap = new Map<string, Set<MicroEventListener>>()\n\n function getEventTarget (type: string): Window {\n return SCOPE_WINDOW_EVENT.includes(type) ? microAppWindow : rawWindow\n }\n\n // TODO: listener 是否需要绑定microAppWindow,否则函数中的this指向原生window\n microAppWindow.addEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList) {\n listenerList.add(listener)\n } else {\n eventListenerMap.set(type, new Set([listener]))\n }\n listener && (listener.__MICRO_APP_MARK_OPTIONS__ = options)\n rawAddEventListener.call(getEventTarget(type), type, listener, options)\n }\n\n microAppWindow.removeEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList?.size && listenerList.has(listener)) {\n listenerList.delete(listener)\n }\n rawRemoveEventListener.call(getEventTarget(type), type, listener, options)\n }\n\n const reset = (): void => {\n sstEventListenerMap.clear()\n }\n\n /**\n * NOTE:\n * 1. about timer(events & properties should record & rebuild at all modes, exclude default mode)\n * 2. record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * 4 modes: default-mode、umd-mode、prerender、keep-alive\n * Solution:\n * 1. default-mode(normal): clear events & timers, not record & rebuild anything\n * 2. umd-mode(normal): not clear timers, record & rebuild events\n * 3. prerender/keep-alive(default, umd): not clear timers, record & rebuild events\n *\n * TODO: 现在的 清除、记录和恢复操作分散的太零散,sandbox、create_app中都有分散,将代码再优化一下,集中处理\n */\n const record = (): void => {\n // record window event\n eventListenerMap.forEach((listenerList, type) => {\n if (listenerList.size) {\n const cacheList = sstEventListenerMap.get(type) || []\n sstEventListenerMap.set(type, new Set([...cacheList, ...listenerList]))\n }\n })\n }\n\n // rebuild event and timer before remount app\n const rebuild = (): void => {\n // rebuild window event\n sstEventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n microAppWindow.addEventListener(type, listener, listener?.__MICRO_APP_MARK_OPTIONS__)\n }\n })\n\n reset()\n }\n\n const release = (): void => {\n // Clear window binding events\n if (eventListenerMap.size) {\n eventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n rawRemoveEventListener.call(getEventTarget(type), type, listener)\n }\n })\n eventListenerMap.clear()\n }\n }\n\n return {\n reset,\n record,\n rebuild,\n release,\n }\n}\n","import type {\n microAppWindowType,\n MicroEventListener,\n CommonEffectHook,\n} from '@micro-app/types'\nimport type IframeSandbox from './index'\nimport {\n rawDefineProperty,\n rawDefineProperties,\n isFunction,\n logWarn,\n isUniqueElement,\n isInvalidQuerySelectorKey,\n throttleDeferForSetAppName,\n} from '../../libs/utils'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n uniqueDocumentElement,\n proxy2RawDocOrShadowKeys,\n proxy2RawDocOrShadowMethods,\n proxy2RawDocumentKeys,\n proxy2RawDocumentMethods,\n} from './special_key'\nimport {\n SCOPE_DOCUMENT_EVENT,\n SCOPE_DOCUMENT_ON_EVENT,\n} from '../../constants'\nimport {\n updateElementInfo,\n} from '../adapter'\nimport {\n appInstanceMap,\n} from '../../create_app'\n\n/**\n * TODO: 1、shadowDOM 2、结构优化\n *\n * patch document of child app\n * @param appName app name\n * @param microAppWindow microWindow of child app\n * @param sandbox IframeSandbox\n * @returns EffectHook\n */\nexport function patchDocument (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): CommonEffectHook {\n patchDocumentPrototype(appName, microAppWindow)\n patchDocumentProperty(appName, microAppWindow, sandbox)\n\n return patchDocumentEffect(appName, microAppWindow)\n}\n\nfunction patchDocumentPrototype (appName: string, microAppWindow: microAppWindowType): void {\n const rawDocument = globalEnv.rawDocument\n const microRootDocument = microAppWindow.Document\n const microDocument = microAppWindow.document\n const rawMicroCreateElement = microRootDocument.prototype.createElement\n const rawMicroCreateTextNode = microRootDocument.prototype.createTextNode\n const rawMicroCreateComment = microRootDocument.prototype.createComment\n const rawMicroQuerySelector = microRootDocument.prototype.querySelector\n const rawMicroQuerySelectorAll = microRootDocument.prototype.querySelectorAll\n const rawMicroGetElementById = microRootDocument.prototype.getElementById\n const rawMicroGetElementsByClassName = microRootDocument.prototype.getElementsByClassName\n const rawMicroGetElementsByTagName = microRootDocument.prototype.getElementsByTagName\n const rawMicroGetElementsByName = microRootDocument.prototype.getElementsByName\n const rawMicroElementFromPoint = microRootDocument.prototype.elementFromPoint\n const rawMicroCaretRangeFromPoint = microRootDocument.prototype.caretRangeFromPoint\n\n microRootDocument.prototype.caretRangeFromPoint = function caretRangeFromPoint (\n x: number,\n y: number,\n ): Range {\n // 这里this指向document才可以获取到子应用的document实例,range才可以被成功生成\n const element = rawMicroElementFromPoint.call(rawDocument, x, y)\n const range = rawMicroCaretRangeFromPoint.call(rawDocument, x, y)\n updateElementInfo(element, appName)\n return range\n }\n\n microRootDocument.prototype.createElement = function createElement (\n tagName: string,\n options?: ElementCreationOptions,\n ): HTMLElement {\n const element = rawMicroCreateElement.call(this, tagName, options)\n return updateElementInfo(element, appName)\n }\n\n microRootDocument.prototype.createTextNode = function createTextNode (data: string): Text {\n const element = rawMicroCreateTextNode.call(this, data)\n return updateElementInfo<Text>(element, appName)\n }\n\n microRootDocument.prototype.createComment = function createComment (data: string): Comment {\n const element = rawMicroCreateComment.call(this, data)\n return updateElementInfo<Comment>(element, appName)\n }\n\n function getDefaultRawTarget (target: Document): Document {\n return microDocument !== target ? target : rawDocument\n }\n\n // query element👇\n function querySelector (this: Document, selectors: string): any {\n if (\n !selectors ||\n isUniqueElement(selectors) ||\n microDocument !== this\n ) {\n const _this = getDefaultRawTarget(this)\n return rawMicroQuerySelector.call(_this, selectors)\n }\n\n return appInstanceMap.get(appName)?.querySelector(selectors) ?? null\n }\n\n function querySelectorAll (this: Document, selectors: string): any {\n if (\n !selectors ||\n isUniqueElement(selectors) ||\n microDocument !== this\n ) {\n const _this = getDefaultRawTarget(this)\n return rawMicroQuerySelectorAll.call(_this, selectors)\n }\n\n return appInstanceMap.get(appName)?.querySelectorAll(selectors) ?? []\n }\n\n microRootDocument.prototype.querySelector = querySelector\n microRootDocument.prototype.querySelectorAll = querySelectorAll\n\n microRootDocument.prototype.getElementById = function getElementById (key: string): HTMLElement | null {\n const _this = getDefaultRawTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementById.call(_this, key)\n }\n\n try {\n return querySelector.call(this, `#${key}`)\n } catch {\n return rawMicroGetElementById.call(_this, key)\n }\n }\n\n microRootDocument.prototype.getElementsByClassName = function getElementsByClassName (key: string): HTMLCollectionOf<Element> {\n const _this = getDefaultRawTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementsByClassName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(this, `.${key}`)\n } catch {\n return rawMicroGetElementsByClassName.call(_this, key)\n }\n }\n\n microRootDocument.prototype.getElementsByTagName = function getElementsByTagName (key: string): HTMLCollectionOf<Element> {\n const _this = getDefaultRawTarget(this)\n if (\n isUniqueElement(key) ||\n isInvalidQuerySelectorKey(key)\n ) {\n return rawMicroGetElementsByTagName.call(_this, key)\n } else if (/^script|base$/i.test(key)) {\n return rawMicroGetElementsByTagName.call(microDocument, key)\n }\n\n try {\n return querySelectorAll.call(this, key)\n } catch {\n return rawMicroGetElementsByTagName.call(_this, key)\n }\n }\n\n microRootDocument.prototype.getElementsByName = function getElementsByName (key: string): NodeListOf<HTMLElement> {\n const _this = getDefaultRawTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementsByName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(this, `[name=${key}]`)\n } catch {\n return rawMicroGetElementsByName.call(_this, key)\n }\n }\n}\n\nfunction patchDocumentProperty (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): void {\n const rawDocument = globalEnv.rawDocument\n const microRootDocument = microAppWindow.Document\n const microDocument = microAppWindow.document\n\n const getCommonDescriptor = (key: PropertyKey, getter: () => unknown): PropertyDescriptor => {\n const { enumerable } = Object.getOwnPropertyDescriptor(microRootDocument.prototype, key) || {\n enumerable: true,\n }\n return {\n configurable: true,\n enumerable,\n get: getter,\n }\n }\n\n const createDescriptors = (): PropertyDescriptorMap => {\n const result: PropertyDescriptorMap = {}\n const descList: Array<[string, () => unknown]> = [\n ['documentURI', () => sandbox.proxyLocation.href],\n ['URL', () => sandbox.proxyLocation.href],\n ['documentElement', () => rawDocument.documentElement],\n ['scrollingElement', () => rawDocument.scrollingElement],\n ['forms', () => microRootDocument.prototype.querySelectorAll.call(microDocument, 'form')],\n ['images', () => microRootDocument.prototype.querySelectorAll.call(microDocument, 'img')],\n ['links', () => microRootDocument.prototype.querySelectorAll.call(microDocument, 'a')],\n // unique keys of micro-app\n ['microAppElement', () => appInstanceMap.get(appName)?.container],\n ['__MICRO_APP_NAME__', () => appName],\n ]\n\n descList.forEach((desc) => {\n result[desc[0]] = getCommonDescriptor(desc[0], desc[1])\n })\n\n // TODO: shadowDOM\n proxy2RawDocOrShadowKeys.forEach((key) => {\n result[key] = getCommonDescriptor(key, () => rawDocument[key])\n })\n\n // TODO: shadowDOM\n proxy2RawDocOrShadowMethods.forEach((key) => {\n result[key] = getCommonDescriptor(key, () => bindFunctionToRawTarget<Document>(rawDocument[key], rawDocument, 'DOCUMENT'))\n })\n\n proxy2RawDocumentKeys.forEach((key) => {\n result[key] = getCommonDescriptor(key, () => rawDocument[key])\n })\n\n proxy2RawDocumentMethods.forEach((key) => {\n result[key] = getCommonDescriptor(key, () => bindFunctionToRawTarget<Document>(rawDocument[key], rawDocument, 'DOCUMENT'))\n })\n\n return result\n }\n\n rawDefineProperties(microRootDocument.prototype, createDescriptors())\n\n // head, body, html, title\n uniqueDocumentElement.forEach((tagName: string) => {\n rawDefineProperty(microDocument, tagName, {\n enumerable: true,\n configurable: true,\n get: () => {\n throttleDeferForSetAppName(appName)\n return rawDocument[tagName]\n },\n set: (value: unknown) => { rawDocument[tagName] = value },\n })\n })\n}\n\nfunction patchDocumentEffect (appName: string, microAppWindow: microAppWindowType): CommonEffectHook {\n const { rawDocument, rawAddEventListener, rawRemoveEventListener } = globalEnv\n const eventListenerMap = new Map<string, Set<MicroEventListener>>()\n const sstEventListenerMap = new Map<string, Set<MicroEventListener>>()\n let onClickHandler: unknown = null\n let sstOnClickHandler: unknown = null\n const microRootDocument = microAppWindow.Document\n const microDocument = microAppWindow.document\n\n function getEventTarget (type: string, bindTarget: Document): Document {\n return SCOPE_DOCUMENT_EVENT.includes(type) ? bindTarget : rawDocument\n }\n\n microRootDocument.prototype.addEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const handler = isFunction(listener) ? (listener.__MICRO_APP_BOUND_FUNCTION__ = listener.__MICRO_APP_BOUND_FUNCTION__ || listener.bind(this)) : listener\n const listenerList = eventListenerMap.get(type)\n if (listenerList) {\n listenerList.add(listener)\n } else {\n eventListenerMap.set(type, new Set([listener]))\n }\n listener && (listener.__MICRO_APP_MARK_OPTIONS__ = options)\n rawAddEventListener.call(getEventTarget(type, this), type, handler, options)\n }\n\n microRootDocument.prototype.removeEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList?.size && listenerList.has(listener)) {\n listenerList.delete(listener)\n }\n const handler = listener?.__MICRO_APP_BOUND_FUNCTION__ || listener\n rawRemoveEventListener.call(getEventTarget(type, this), type, handler, options)\n }\n\n // 重新定义microRootDocument.prototype 上的on开头方法\n function createSetterHandler (eventName: string): (value: unknown) => void {\n if (eventName === 'onclick') {\n return (value: unknown): void => {\n if (isFunction(onClickHandler)) {\n rawRemoveEventListener.call(rawDocument, 'click', onClickHandler, false)\n }\n if (isFunction(value)) {\n onClickHandler = value.bind(microDocument)\n rawAddEventListener.call(rawDocument, 'click', onClickHandler, false)\n } else {\n onClickHandler = value\n }\n }\n }\n return (value: unknown) => { rawDocument[eventName] = isFunction(value) ? value.bind(microDocument) : value }\n }\n\n /**\n * TODO:\n * 1、直接代理到原生document是否正确\n * 2、shadowDOM\n */\n Object.getOwnPropertyNames(microRootDocument.prototype)\n .filter((key: string) => /^on/.test(key) && !SCOPE_DOCUMENT_ON_EVENT.includes(key))\n .forEach((eventName: string) => {\n const { enumerable, writable, set } = Object.getOwnPropertyDescriptor(microRootDocument.prototype, eventName) || {\n enumerable: true,\n writable: true,\n }\n\n try {\n rawDefineProperty(microRootDocument.prototype, eventName, {\n enumerable,\n configurable: true,\n get: () => {\n if (eventName === 'onclick') return onClickHandler\n return rawDocument[eventName]\n },\n set: writable ?? !!set ? createSetterHandler(eventName) : undefined,\n })\n } catch (e) {\n logWarn(e, appName)\n }\n })\n\n const reset = (): void => {\n sstEventListenerMap.clear()\n sstOnClickHandler = null\n }\n\n /**\n * record event\n * NOTE:\n * 1.record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * Scenes:\n * 1. exec umdMountHook in umd mode\n * 2. hidden keep-alive app\n * 3. after init prerender app\n */\n const record = (): void => {\n /**\n * record onclick handler\n * onClickHandler maybe set again after prerender/keep-alive app hidden\n */\n sstOnClickHandler = onClickHandler || sstOnClickHandler\n\n // record document event\n eventListenerMap.forEach((listenerList, type) => {\n if (listenerList.size) {\n const cacheList = sstEventListenerMap.get(type) || []\n sstEventListenerMap.set(type, new Set([...cacheList, ...listenerList]))\n }\n })\n }\n\n // rebuild event and timer before remount app\n const rebuild = (): void => {\n // rebuild onclick event\n if (sstOnClickHandler && !onClickHandler) microDocument.onclick = sstOnClickHandler\n\n sstEventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n microDocument.addEventListener(type, listener, listener?.__MICRO_APP_MARK_OPTIONS__)\n }\n })\n\n reset()\n }\n\n const release = (): void => {\n // Clear the function bound by micro app through document.onclick\n if (isFunction(onClickHandler)) {\n rawRemoveEventListener.call(rawDocument, 'click', onClickHandler)\n }\n onClickHandler = null\n\n // Clear document binding event\n if (eventListenerMap.size) {\n eventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n rawRemoveEventListener.call(\n getEventTarget(type, microDocument),\n type,\n listener?.__MICRO_APP_BOUND_FUNCTION__ || listener,\n )\n }\n })\n eventListenerMap.clear()\n }\n }\n\n return {\n reset,\n record,\n rebuild,\n release,\n }\n}\n","import type {\n microAppWindowType,\n} from '@micro-app/types'\nimport type IframeSandbox from './index'\nimport globalEnv from '../../libs/global_env'\nimport {\n rawDefineProperty,\n CompletionPath,\n isScriptElement,\n isBaseElement,\n isElement,\n isNode,\n} from '../../libs/utils'\nimport {\n updateElementInfo,\n createGetterForIframeParentNode,\n} from '../adapter'\n\n/**\n * patch Element & Node of child app\n * @param appName app name\n * @param url app url\n * @param microAppWindow microWindow of child app\n * @param sandbox IframeSandbox\n */\nexport function patchElement (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): void {\n patchIframeNode(appName, microAppWindow, sandbox)\n patchIframeAttribute(url, microAppWindow)\n}\n\nfunction patchIframeNode (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): void {\n const rawRootElement = globalEnv.rawRootElement // native root Element\n const rawDocument = globalEnv.rawDocument\n const microDocument = microAppWindow.document\n const microRootNode = microAppWindow.Node\n const microRootElement = microAppWindow.Element\n // const rawMicroGetRootNode = microRootNode.prototype.getRootNode\n const rawMicroAppendChild = microRootNode.prototype.appendChild\n const rawMicroInsertBefore = microRootNode.prototype.insertBefore\n const rawMicroReplaceChild = microRootNode.prototype.replaceChild\n const rawMicroRemoveChild = microRootNode.prototype.removeChild\n const rawMicroAppend = microRootElement.prototype.append\n const rawMicroPrepend = microRootElement.prototype.prepend\n const rawMicroInsertAdjacentElement = microRootElement.prototype.insertAdjacentElement\n const rawMicroCloneNode = microRootNode.prototype.cloneNode\n const rawInnerHTMLDesc = Object.getOwnPropertyDescriptor(microRootElement.prototype, 'innerHTML') as PropertyDescriptor\n const rawParentNodeDesc = Object.getOwnPropertyDescriptor(microRootNode.prototype, 'parentNode') as PropertyDescriptor\n const rawOwnerDocumentDesc = Object.getOwnPropertyDescriptor(microRootNode.prototype, 'ownerDocument') as PropertyDescriptor\n\n const isPureNode = (target: unknown): boolean | void => {\n return (isScriptElement(target) || isBaseElement(target)) && target.__PURE_ELEMENT__\n }\n\n const getRawTarget = (parent: Node): Node => {\n if (parent === sandbox.microHead) {\n return rawDocument.head\n } else if (parent === sandbox.microBody) {\n return rawDocument.body\n }\n\n return parent\n }\n\n microRootNode.prototype.getRootNode = function getRootNode (): Node {\n return microDocument\n // TODO: 什么情况下返回原生document?\n // const rootNode = rawMicroGetRootNode.call(this, options)\n // if (rootNode === appInstanceMap.get(appName)?.container) return microDocument\n // return rootNode\n }\n\n microRootNode.prototype.appendChild = function appendChild <T extends Node> (node: T): T {\n updateElementInfo(node, appName)\n if (isPureNode(node)) {\n return rawMicroAppendChild.call(this, node)\n }\n return rawRootElement.prototype.appendChild.call(getRawTarget(this), node)\n }\n\n microRootNode.prototype.insertBefore = function insertBefore <T extends Node> (node: T, child: Node | null): T {\n updateElementInfo(node, appName)\n if (isPureNode(node)) {\n return rawMicroInsertBefore.call(this, node, child)\n }\n return rawRootElement.prototype.insertBefore.call(getRawTarget(this), node, child)\n }\n\n microRootNode.prototype.replaceChild = function replaceChild <T extends Node> (node: Node, child: T): T {\n updateElementInfo(node, appName)\n if (isPureNode(node)) {\n return rawMicroReplaceChild.call(this, node, child)\n }\n return rawRootElement.prototype.replaceChild.call(getRawTarget(this), node, child)\n }\n\n microRootNode.prototype.removeChild = function removeChild<T extends Node> (oldChild: T): T {\n if (isPureNode(oldChild) || this.contains(oldChild)) {\n return rawMicroRemoveChild.call(this, oldChild)\n }\n return rawRootElement.prototype.removeChild.call(getRawTarget(this), oldChild)\n }\n\n microRootElement.prototype.append = function append (...nodes: (Node | string)[]): void {\n let i = 0; let hasPureNode = false\n while (i < nodes.length) {\n nodes[i] = isNode(nodes[i]) ? nodes[i] : microDocument.createTextNode(nodes[i])\n if (isPureNode(nodes[i])) hasPureNode = true\n i++\n }\n if (hasPureNode) {\n return rawMicroAppend.call(this, ...nodes)\n }\n return rawRootElement.prototype.append.call(getRawTarget(this), ...nodes)\n }\n\n microRootElement.prototype.prepend = function prepend (...nodes: (Node | string)[]): void {\n let i = 0; let hasPureNode = false\n while (i < nodes.length) {\n nodes[i] = isNode(nodes[i]) ? nodes[i] : microDocument.createTextNode(nodes[i])\n if (isPureNode(nodes[i])) hasPureNode = true\n i++\n }\n if (hasPureNode) {\n return rawMicroPrepend.call(this, ...nodes)\n }\n return rawRootElement.prototype.prepend.call(getRawTarget(this), ...nodes)\n }\n\n /**\n * The insertAdjacentElement method of the Element interface inserts a given element node at a given position relative to the element it is invoked upon.\n * Scenes:\n * 1. vite4 development env for style\n */\n microRootElement.prototype.insertAdjacentElement = function insertAdjacentElement (where: InsertPosition, element: Element): Element | null {\n updateElementInfo(element, appName)\n if (isPureNode(element)) {\n return rawMicroInsertAdjacentElement.call(this, where, element)\n }\n return rawRootElement.prototype.insertAdjacentElement.call(getRawTarget(this), where, element)\n }\n\n // patch cloneNode\n microRootNode.prototype.cloneNode = function cloneNode (deep?: boolean): Node {\n const clonedNode = rawMicroCloneNode.call(this, deep)\n return updateElementInfo(clonedNode, appName)\n }\n\n rawDefineProperty(microRootNode.prototype, 'ownerDocument', {\n configurable: true,\n enumerable: true,\n get () {\n return this.__PURE_ELEMENT__\n ? rawOwnerDocumentDesc.get!.call(this)\n : microDocument\n },\n })\n\n rawDefineProperty(microRootElement.prototype, 'innerHTML', {\n configurable: true,\n enumerable: true,\n get () {\n return rawInnerHTMLDesc.get!.call(this)\n },\n set (code: string) {\n rawInnerHTMLDesc.set!.call(this, code)\n Array.from(this.children).forEach((child) => {\n if (isElement(child)) {\n updateElementInfo(child, appName)\n }\n })\n }\n })\n\n // patch parentNode\n rawDefineProperty(microRootNode.prototype, 'parentNode', {\n configurable: true,\n enumerable: true,\n get: createGetterForIframeParentNode(\n appName,\n rawParentNodeDesc,\n ),\n })\n\n // Adapt to new image(...) scene\n const ImageProxy = new Proxy(microAppWindow.Image, {\n construct (Target, args): HTMLImageElement {\n const elementImage = new Target(...args)\n updateElementInfo(elementImage, appName)\n return elementImage\n },\n })\n\n rawDefineProperty(microAppWindow, 'Image', {\n configurable: true,\n writable: true,\n value: ImageProxy,\n })\n}\n\nfunction patchIframeAttribute (url: string, microAppWindow: microAppWindowType): void {\n const microRootElement = microAppWindow.Element\n const rawMicroSetAttribute = microRootElement.prototype.setAttribute\n\n microRootElement.prototype.setAttribute = function setAttribute (key: string, value: any): void {\n if (\n ((key === 'src' || key === 'srcset') && /^(img|script)$/i.test(this.tagName)) ||\n (key === 'href' && /^link$/i.test(this.tagName))\n ) {\n value = CompletionPath(value, url)\n }\n\n rawMicroSetAttribute.call(this, key, value)\n }\n\n const protoAttrList: Array<[HTMLElement, string]> = [\n [microAppWindow.HTMLImageElement.prototype, 'src'],\n [microAppWindow.HTMLScriptElement.prototype, 'src'],\n [microAppWindow.HTMLLinkElement.prototype, 'href'],\n ]\n\n /**\n * element.setAttribute does not trigger this actions:\n * 1. img.src = xxx\n * 2. script.src = xxx\n * 3. link.href = xxx\n */\n protoAttrList.forEach(([target, attr]) => {\n const { enumerable, configurable, get, set } = Object.getOwnPropertyDescriptor(target, attr) || {\n enumerable: true,\n configurable: true,\n }\n\n rawDefineProperty(target, attr, {\n enumerable,\n configurable,\n get: function () {\n return get?.call(this)\n },\n set: function (value) {\n set?.call(this, CompletionPath(value, url))\n },\n })\n })\n}\n","import type {\n microAppWindowType,\n MicroLocation,\n SandBoxStartParams,\n CommonEffectHook,\n SandBoxStopParams,\n releaseGlobalEffectParams,\n plugins,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport microApp from '../../micro_app'\nimport {\n getEffectivePath,\n removeDomScope,\n pureCreateElement,\n assign,\n clearDOM,\n isPlainObject,\n isArray,\n defer,\n} from '../../libs/utils'\nimport {\n EventCenterForMicroApp,\n rebuildDataCenterSnapshot,\n recordDataCenterSnapshot,\n resetDataCenterSnapshot,\n} from '../../interact'\nimport {\n patchRouter,\n} from './router'\nimport {\n router,\n initRouteStateWithURL,\n clearRouteStateFromURL,\n addHistoryListener,\n removePathFromBrowser,\n updateBrowserURLWithLocation,\n patchHistory,\n releasePatchHistory,\n isRouterModeCustom,\n} from '../router'\nimport {\n patchElementAndDocument,\n releasePatchElementAndDocument,\n} from '../../source/patch'\nimport {\n patchWindow,\n} from './window'\nimport {\n patchDocument,\n} from './document'\nimport {\n patchElement,\n} from './element'\nimport {\n patchElementTree\n} from '../adapter'\n\nexport default class IframeSandbox {\n static activeCount = 0 // number of active sandbox\n private active = false\n private windowEffect!: CommonEffectHook\n private documentEffect!: CommonEffectHook\n private removeHistoryListener!: CallableFunction\n // Properties that can be escape to rawWindow\n public escapeProperties: PropertyKey[] = []\n // Properties escape to rawWindow, cleared when unmount\n public escapeKeys = new Set<PropertyKey>()\n public deleteIframeElement: () => void\n public iframe!: HTMLIFrameElement | null\n public sandboxReady!: Promise<void>\n public microAppWindow: microAppWindowType\n public proxyLocation!: MicroLocation\n public proxyWindow: WindowProxy & microAppWindowType\n public baseElement!: HTMLBaseElement\n public microHead!: HTMLHeadElement\n public microBody!: HTMLBodyElement\n\n constructor (appName: string, url: string) {\n const rawLocation = globalEnv.rawWindow.location\n const browserHost = rawLocation.protocol + '//' + rawLocation.host\n\n this.deleteIframeElement = this.createIframeElement(appName, browserHost)\n this.microAppWindow = this.iframe!.contentWindow\n\n this.patchIframe(this.microAppWindow, (resolve: CallableFunction) => {\n // create new html to iframe\n this.createIframeTemplate(this.microAppWindow)\n // get escapeProperties from plugins\n this.getSpecialProperties(appName)\n // patch location & history of child app\n this.proxyLocation = patchRouter(appName, url, this.microAppWindow, browserHost)\n // patch window of child app\n this.windowEffect = patchWindow(appName, this.microAppWindow, this)\n // patch document of child app\n this.documentEffect = patchDocument(appName, this.microAppWindow, this)\n // patch Node & Element of child app\n patchElement(appName, url, this.microAppWindow, this)\n /**\n * create static properties\n * NOTE:\n * 1. execute as early as possible\n * 2. run after patchRouter & createProxyWindow\n */\n this.initStaticGlobalKeys(appName, url, this.microAppWindow)\n resolve()\n })\n }\n\n /**\n * create iframe for sandbox\n * @param appName app name\n * @param browserHost browser origin\n * @returns release callback\n */\n createIframeElement (\n appName: string,\n browserHost: string,\n ): () => void {\n this.iframe = pureCreateElement('iframe')\n\n const iframeAttrs: Record<string, string> = {\n src: browserHost,\n style: 'display: none',\n id: appName,\n }\n\n Object.keys(iframeAttrs).forEach((key) => this.iframe!.setAttribute(key, iframeAttrs[key]))\n\n // effect action during construct\n globalEnv.rawDocument.body.appendChild(this.iframe)\n\n /**\n * If dom operated async when unmount, premature deletion of iframe will cause unexpected problems\n * e.g.\n * 1. antd: notification.destroy()\n * WARNING:\n * If async operation time is too long, defer cannot avoid the problem\n * TODO: more test\n */\n return () => defer(() => {\n // default mode or destroy, iframe will be deleted when unmount\n this.iframe?.parentNode?.removeChild(this.iframe)\n this.iframe = null\n })\n }\n\n public start ({\n baseroute,\n defaultPage,\n disablePatchRequest,\n }: SandBoxStartParams): void {\n if (this.active) return\n this.active = true\n /* --- memory router part --- start */\n /**\n * Sync router info to iframe when exec sandbox.start with disable or enable memory-router\n * e.g.:\n * vue-router@4.x get target path by remove the base section from rawLocation.pathname\n * code: window.location.pathname.slice(base.length) || '/'; (base is baseroute)\n * NOTE:\n * 1. iframe router and browser router are separated, we should update iframe router manually\n * 2. withSandbox location is browser location when disable memory-router, so no need to do anything\n */\n /**\n * TODO:\n * 1. iframe关闭虚拟路由系统后,default-page无法使用,推荐用户直接使用浏览器地址控制首页渲染\n * 补充:keep-router-state 也无法配置,因为keep-router-state一定为true。\n * 2. 导航拦截、current.route 可以正常使用\n * 3. 可以正常控制子应用跳转,方式还是自上而下(也可以是子应用内部跳转,这种方式更好一点,减小对基座的影响,不会导致vue的循环刷新)\n * 4. 关闭虚拟路由以后会对应 route-mode='custom' 模式,包括with沙箱也会这么做\n * 5. 关闭虚拟路由是指尽可能模拟没有虚拟路由的情况,子应用直接获取浏览器location和history,控制浏览器跳转\n */\n this.initRouteState(defaultPage)\n\n // unique listener of popstate event for child app\n this.removeHistoryListener = addHistoryListener(\n this.microAppWindow.__MICRO_APP_NAME__,\n )\n\n if (isRouterModeCustom(this.microAppWindow.__MICRO_APP_NAME__)) {\n this.microAppWindow.__MICRO_APP_BASE_ROUTE__ = this.microAppWindow.__MICRO_APP_BASE_URL__ = baseroute\n }\n /* --- memory router part --- end */\n\n /**\n * create base element to iframe\n * WARNING: This will also affect a, image, link and script\n */\n if (!disablePatchRequest) {\n this.createIframeBase()\n }\n\n if (++globalEnv.activeSandbox === 1) {\n patchElementAndDocument()\n patchHistory()\n }\n\n if (++IframeSandbox.activeCount === 1) {\n // TODO: 多层嵌套兼容\n }\n }\n\n public stop ({\n umdMode,\n keepRouteState,\n destroy,\n clearData,\n }: SandBoxStopParams): void {\n if (!this.active) return\n this.recordAndReleaseEffect({ clearData }, !umdMode || destroy)\n\n /* --- memory router part --- start */\n // if keep-route-state is true, preserve microLocation state\n this.clearRouteState(keepRouteState)\n\n // release listener of popstate for child app\n this.removeHistoryListener?.()\n /* --- memory router part --- end */\n\n if (!umdMode || destroy) {\n this.deleteIframeElement()\n\n this.escapeKeys.forEach((key: PropertyKey) => {\n Reflect.deleteProperty(globalEnv.rawWindow, key)\n })\n this.escapeKeys.clear()\n }\n\n if (--globalEnv.activeSandbox === 0) {\n releasePatchElementAndDocument()\n releasePatchHistory()\n }\n\n if (--IframeSandbox.activeCount === 0) {\n // TODO: Is there anything to put here?\n }\n\n this.active = false\n }\n\n /**\n * create static properties\n * NOTE:\n * 1. execute as early as possible\n * 2. run after patchRouter & createProxyWindow\n */\n private initStaticGlobalKeys (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n ): void {\n microAppWindow.__MICRO_APP_ENVIRONMENT__ = true\n microAppWindow.__MICRO_APP_NAME__ = appName\n microAppWindow.__MICRO_APP_URL__ = url\n microAppWindow.__MICRO_APP_PUBLIC_PATH__ = getEffectivePath(url)\n microAppWindow.__MICRO_APP_BASE_ROUTE__ = ''\n microAppWindow.__MICRO_APP_WINDOW__ = microAppWindow\n microAppWindow.__MICRO_APP_PRE_RENDER__ = false\n microAppWindow.__MICRO_APP_UMD_MODE__ = false\n microAppWindow.__MICRO_APP_PROXY_WINDOW__ = this.proxyWindow\n microAppWindow.__MICRO_APP_SANDBOX__ = this\n microAppWindow.__MICRO_APP_SANDBOX_TYPE__ = 'iframe'\n microAppWindow.rawWindow = globalEnv.rawWindow\n microAppWindow.rawDocument = globalEnv.rawDocument\n microAppWindow.microApp = assign(new EventCenterForMicroApp(appName), {\n removeDomScope,\n pureCreateElement,\n location: this.proxyLocation,\n router,\n })\n }\n\n /**\n * Record global effect and then release (effect: global event, timeout, data listener)\n * Scenes:\n * 1. unmount of default/umd app\n * 2. hidden keep-alive app\n * 3. after init prerender app\n * @param options {\n * @param clearData clear data from base app\n * @param isPrerender is prerender app\n * @param keepAlive is keep-alive app\n * }\n * @param preventRecord prevent record effect events (default or destroy)\n */\n public recordAndReleaseEffect (\n options: releaseGlobalEffectParams,\n preventRecord = false,\n ): void {\n if (preventRecord) {\n this.resetEffectSnapshot()\n } else {\n this.recordEffectSnapshot()\n }\n this.releaseGlobalEffect(options)\n }\n\n /**\n * reset effect snapshot data in default mode or destroy\n * Scenes:\n * 1. unmount hidden keep-alive app manually\n * 2. unmount prerender app manually\n */\n public resetEffectSnapshot (): void {\n this.windowEffect?.reset()\n this.documentEffect?.reset()\n resetDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n /**\n * record umd snapshot before the first execution of umdHookMount\n * Scenes:\n * 1. exec umdMountHook in umd mode\n * 2. hidden keep-alive app\n * 3. after init prerender app\n */\n public recordEffectSnapshot (): void {\n this.windowEffect?.record()\n this.documentEffect?.record()\n recordDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n // rebuild umd snapshot before remount umd app\n public rebuildEffectSnapshot (): void {\n this.windowEffect?.rebuild()\n this.documentEffect?.rebuild()\n rebuildDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n /**\n * clear global event, timeout, data listener\n * Scenes:\n * 1. unmount of normal/umd app\n * 2. hidden keep-alive app\n * 3. after init prerender app\n * @param clearData clear data from base app\n * @param isPrerender is prerender app\n * @param keepAlive is keep-alive app\n */\n public releaseGlobalEffect ({ clearData = false }: releaseGlobalEffectParams): void {\n this.windowEffect?.release()\n this.documentEffect?.release()\n this.microAppWindow.microApp?.clearDataListener()\n this.microAppWindow.microApp?.clearGlobalDataListener()\n if (clearData) {\n microApp.clearData(this.microAppWindow.__MICRO_APP_NAME__)\n this.microAppWindow.microApp?.clearData()\n }\n }\n\n // set __MICRO_APP_PRE_RENDER__ state\n public setPreRenderState (state: boolean): void {\n this.microAppWindow.__MICRO_APP_PRE_RENDER__ = state\n }\n\n // record umdMode\n public markUmdMode (state: boolean): void {\n this.microAppWindow.__MICRO_APP_UMD_MODE__ = state\n }\n\n // TODO: RESTRUCTURE\n private patchIframe (microAppWindow: microAppWindowType, cb: CallableFunction): void {\n const oldMicroDocument = microAppWindow.document\n this.sandboxReady = new Promise<void>((resolve) => {\n (function iframeLocationReady () {\n setTimeout(() => {\n try {\n /**\n * NOTE:\n * 1. In browser, iframe document will be recreated after iframe initial\n * 2. In jest, iframe document is always the same\n */\n if (microAppWindow.document === oldMicroDocument && !__TEST__) {\n iframeLocationReady()\n } else {\n /**\n * NOTE:\n * 1. microAppWindow will not be recreated\n * 2. the properties of microAppWindow may be recreated, such as document\n * 3. the variables added to microAppWindow may be cleared\n */\n microAppWindow.stop()\n cb(resolve)\n }\n } catch (e) {\n iframeLocationReady()\n }\n }, 0)\n })()\n })\n }\n\n // TODO: RESTRUCTURE\n private createIframeTemplate (microAppWindow: microAppWindowType): void {\n const microDocument = microAppWindow.document\n clearDOM(microDocument)\n const html = microDocument.createElement('html')\n html.innerHTML = '<head></head><body></body>'\n microDocument.appendChild(html)\n\n // 记录iframe原生body\n this.microBody = microDocument.body\n this.microHead = microDocument.head\n }\n\n /**\n * baseElement will complete the relative address of element according to the URL\n * e.g: a image link script fetch ajax EventSource\n */\n private createIframeBase (): void {\n this.baseElement = pureCreateElement('base')\n this.updateIframeBase()\n this.microHead.appendChild(this.baseElement)\n }\n\n // TODO: 初始化和每次跳转时都要更新base的href\n public updateIframeBase = (): void => {\n this.baseElement?.setAttribute('href', this.proxyLocation.protocol + '//' + this.proxyLocation.host + this.proxyLocation.pathname)\n }\n\n /**\n * get escapeProperties from plugins & adapter\n * @param appName app name\n */\n private getSpecialProperties (appName: string): void {\n if (isPlainObject(microApp.options.plugins)) {\n this.commonActionForSpecialProperties(microApp.options.plugins.global)\n this.commonActionForSpecialProperties(microApp.options.plugins.modules?.[appName])\n }\n }\n\n // common action for global plugins and module plugins\n private commonActionForSpecialProperties (plugins: plugins['global']) {\n if (isArray(plugins)) {\n for (const plugin of plugins) {\n if (isPlainObject(plugin)) {\n if (isArray(plugin.escapeProperties)) {\n this.escapeProperties = this.escapeProperties.concat(plugin.escapeProperties)\n }\n }\n }\n }\n }\n\n private initRouteState (defaultPage: string): void {\n initRouteStateWithURL(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.location as MicroLocation,\n defaultPage,\n )\n }\n\n private clearRouteState (keepRouteState: boolean): void {\n clearRouteStateFromURL(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.__MICRO_APP_URL__,\n this.microAppWindow.location as MicroLocation,\n keepRouteState,\n )\n }\n\n public setRouteInfoForKeepAliveApp (): void {\n updateBrowserURLWithLocation(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.location as MicroLocation,\n )\n }\n\n public removeRouteInfoForKeepAliveApp (): void {\n removePathFromBrowser(this.microAppWindow.__MICRO_APP_NAME__)\n }\n\n /**\n * Format all html elements when init\n * @param container micro app container\n */\n public patchStaticElement (container: Element | ShadowRoot): void {\n patchElementTree(container, this.microAppWindow.__MICRO_APP_NAME__)\n }\n\n /**\n * Actions:\n * 1. patch static elements from html\n * @param container micro app container\n */\n public actionBeforeExecScripts (container: Element | ShadowRoot): void {\n this.patchStaticElement(container)\n }\n\n public setStaticAppState (state: string): void {\n this.microAppWindow.__MICRO_APP_STATE__ = state\n }\n}\n","import type {\n microAppWindowType,\n MicroLocation,\n} from '@micro-app/types'\nimport {\n createMicroLocation,\n updateMicroLocation,\n} from '../router/location'\nimport {\n createMicroHistory,\n} from '../router/history'\nimport {\n assign,\n} from '../../libs/utils'\n\nexport function patchRouter (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n browserHost: string,\n): MicroLocation {\n const childStaticLocation = new URL(url) as MicroLocation\n const childHost = childStaticLocation.protocol + '//' + childStaticLocation.host\n const childFullPath = childStaticLocation.pathname + childStaticLocation.search + childStaticLocation.hash\n\n // rewrite microAppWindow.history\n const microHistory = microAppWindow.history\n microAppWindow.rawReplaceState = microHistory.replaceState\n assign(microHistory, createMicroHistory(appName, microAppWindow.location))\n\n /**\n * Init microLocation before exec sandbox.start\n * NOTE:\n * 1. exec updateMicroLocation after patch microHistory\n * 2. sandbox.start will sync microLocation info to browser url\n */\n updateMicroLocation(\n appName,\n childFullPath,\n microAppWindow.location,\n 'prevent'\n )\n\n // create proxyLocation\n return createMicroLocation(\n appName,\n url,\n microAppWindow,\n childStaticLocation,\n browserHost,\n childHost,\n )\n}\n","import type {\n Func,\n AppInterface,\n sourceType,\n WithSandBoxInterface,\n MountParam,\n UnmountParam,\n} from '@micro-app/types'\nimport { HTMLLoader } from './source/loader/html'\nimport { extractSourceDom } from './source/index'\nimport { execScripts } from './source/scripts'\nimport WithSandBox from './sandbox/with'\nimport IframeSandbox from './sandbox/iframe'\nimport { router } from './sandbox/router'\nimport {\n appStates,\n lifeCycles,\n keepAliveStates,\n microGlobalEvent,\n DEFAULT_ROUTER_MODE,\n ROUTER_MODE_CUSTOM,\n} from './constants'\nimport {\n isFunction,\n cloneContainer,\n isPromise,\n logError,\n getRootContainer,\n isObject,\n execMicroAppGlobalHook,\n pureCreateElement,\n isDivElement,\n removeDomScope,\n} from './libs/utils'\nimport dispatchLifecyclesEvent, {\n dispatchCustomEventToMicroApp,\n} from './interact/lifecycles_event'\nimport globalEnv from './libs/global_env'\nimport microApp from './micro_app'\nimport sourceCenter from './source/source_center'\n\n// micro app instances\nexport const appInstanceMap = new Map<string, AppInterface>()\n\n// params of CreateApp\nexport interface CreateAppParam {\n name: string\n url: string\n scopecss: boolean\n useSandbox: boolean\n inline?: boolean\n iframe?: boolean\n container?: HTMLElement | ShadowRoot\n ssrUrl?: string\n isPrefetch?: boolean\n prefetchLevel?: number\n routerMode?: string\n}\n\nexport default class CreateApp implements AppInterface {\n private state: string = appStates.CREATED\n private keepAliveState: string | null = null\n private loadSourceLevel: -1|0|1|2 = 0\n private umdHookMount: Func | null = null\n private umdHookUnmount: Func | null = null\n private preRenderEvents?: CallableFunction[] | null\n private lifeCycleState: string | null = null\n public umdMode = false\n public source: sourceType\n // TODO: 类型优化,加上iframe沙箱\n public sandBox: WithSandBoxInterface | IframeSandbox | null = null\n public name: string\n public url: string\n public container: HTMLElement | ShadowRoot | null\n public scopecss: boolean\n public useSandbox: boolean\n public inline: boolean\n public iframe: boolean\n public ssrUrl: string\n public isPrefetch: boolean\n public isPrerender: boolean\n public prefetchLevel?: number\n public fiber = false\n public routerMode: string\n\n constructor ({\n name,\n url,\n container,\n scopecss,\n useSandbox,\n inline,\n iframe,\n ssrUrl,\n isPrefetch,\n prefetchLevel,\n routerMode,\n }: CreateAppParam) {\n appInstanceMap.set(name, this)\n // init actions\n this.name = name\n this.url = url\n this.useSandbox = useSandbox\n this.scopecss = this.useSandbox && scopecss\n // exec before getInlineModeState\n this.iframe = iframe ?? false\n this.inline = this.getInlineModeState(inline)\n /**\n * NOTE:\n * 1. Navigate after micro-app created, before mount\n */\n this.routerMode = routerMode || DEFAULT_ROUTER_MODE\n\n // not exist when prefetch 👇\n this.container = container ?? null\n this.ssrUrl = ssrUrl ?? ''\n\n // exist only prefetch 👇\n this.isPrefetch = isPrefetch ?? false\n this.isPrerender = prefetchLevel === 3\n this.prefetchLevel = prefetchLevel\n\n this.source = { html: null, links: new Set(), scripts: new Set() }\n this.loadSourceCode()\n this.createSandbox()\n }\n\n // Load resources\n public loadSourceCode (): void {\n this.setAppState(appStates.LOADING)\n HTMLLoader.getInstance().run(this, extractSourceDom)\n }\n\n /**\n * When resource is loaded, mount app if it is not prefetch or unmount\n */\n public onLoad (\n html: HTMLElement,\n defaultPage?: string,\n disablePatchRequest?: boolean,\n routerMode?: string,\n baseroute?: string,\n ): void {\n if (++this.loadSourceLevel === 2) {\n this.source.html = html\n\n if (!this.isPrefetch && !this.isUnmounted()) {\n getRootContainer(this.container!).mount(this)\n } else if (this.isPrerender) {\n /**\n * PreRender is an option of prefetch, it will render app during prefetch\n * Limit:\n * 1. fiber forced on\n * 2. only virtual router support\n *\n * NOTE: (Don't update browser url, dispatch popstateEvent, reload window, dispatch lifecycle event)\n * 1. pushState/replaceState in child can update microLocation, but will not attach router info to browser url\n * 2. prevent dispatch popstate/hashchange event to browser\n * 3. all navigation actions of location are invalid (In the future, we can consider update microLocation without trigger browser reload)\n * 4. lifecycle event will not trigger when prerender\n *\n * Special scenes\n * 1. unmount prerender app when loading\n * 2. unmount prerender app when exec js\n * 2. unmount prerender app after exec js\n */\n const container = pureCreateElement('div')\n container.setAttribute('prerender', 'true')\n this.sandBox?.setPreRenderState(true)\n this.mount({\n container,\n inline: this.inline,\n routerMode: routerMode!,\n baseroute: baseroute || '',\n fiber: true,\n defaultPage: defaultPage || '',\n disablePatchRequest: disablePatchRequest ?? false,\n })\n }\n }\n }\n\n /**\n * Error loading HTML\n * @param e Error\n */\n public onLoadError (e: Error): void {\n this.loadSourceLevel = -1\n\n if (!this.isUnmounted()) {\n this.onerror(e)\n this.setAppState(appStates.LOAD_FAILED)\n }\n }\n\n /**\n * mount app\n * @param container app container\n * @param inline run js in inline mode\n * @param routerMode virtual router mode\n * @param defaultPage default page of virtual router\n * @param baseroute route prefix, default is ''\n * @param disablePatchRequest prevent rewrite request method of child app\n * @param fiber run js in fiber mode\n */\n public mount ({\n container,\n inline,\n routerMode,\n defaultPage,\n baseroute,\n disablePatchRequest,\n fiber,\n }: MountParam): void {\n if (this.loadSourceLevel !== 2) {\n /**\n * container cannot be null when load end\n * NOTE:\n * 1. render prefetch app before load end\n * 2. unmount prefetch app and mount again before load end\n */\n this.container = container\n // mount before prerender exec mount (loading source), set isPrerender to false\n this.isPrerender = false\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.LOADING\n })\n\n // reset app state to LOADING\n return this.setAppState(appStates.LOADING)\n }\n\n this.createSandbox()\n\n // place outside of nextAction, as nextAction may execute async\n this.setAppState(appStates.BEFORE_MOUNT)\n\n const nextAction = () => {\n /**\n * Special scenes:\n * 1. mount before prerender exec mount (loading source)\n * 2. mount when prerender js executing\n * 3. mount after prerender js exec end\n * 4. mount after prerender unmounted\n *\n * TODO: test shadowDOM\n */\n if (\n this.isPrerender &&\n isDivElement(this.container) &&\n this.container.hasAttribute('prerender')\n ) {\n /**\n * rebuild effect event of window, document, data center\n * explain:\n * 1. rebuild before exec mount, do nothing\n * 2. rebuild when js executing, recovery recorded effect event, because prerender fiber mode\n * 3. rebuild after js exec end, normal recovery effect event\n */\n this.sandBox?.rebuildEffectSnapshot()\n // current this.container is <div prerender='true'></div>\n cloneContainer(container as Element, this.container as Element, false)\n /**\n * set this.container to <micro-app></micro-app>\n * NOTE:\n * must exec before this.preRenderEvents?.forEach((cb) => cb())\n */\n this.container = container\n this.preRenderEvents?.forEach((cb) => cb())\n // reset isPrerender config\n this.isPrerender = false\n this.preRenderEvents = null\n // attach router info to browser url\n router.attachToURL(this.name)\n this.sandBox?.setPreRenderState(false)\n } else {\n this.container = container\n this.inline = this.getInlineModeState(inline)\n this.fiber = fiber\n this.routerMode = routerMode\n\n const dispatchBeforeMount = () => {\n this.setLifeCycleState(lifeCycles.BEFOREMOUNT)\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.BEFOREMOUNT,\n )\n }\n\n if (this.isPrerender) {\n (this.preRenderEvents ??= []).push(dispatchBeforeMount)\n } else {\n dispatchBeforeMount()\n }\n\n this.setAppState(appStates.MOUNTING)\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.MOUNTING\n })\n\n // TODO: 将所有cloneContainer中的'as Element'去掉,兼容shadowRoot的场景\n cloneContainer(this.container as Element, this.source.html as Element, !this.umdMode)\n\n this.sandBox?.start({\n umdMode: this.umdMode,\n baseroute,\n defaultPage,\n disablePatchRequest,\n })\n\n if (!this.umdMode) {\n // update element info of html\n this.sandBox?.actionBeforeExecScripts(this.container)\n // if all js are executed, param isFinished will be true\n execScripts(this, (isFinished: boolean) => {\n if (!this.umdMode) {\n const { mount, unmount } = this.getUmdLibraryHooks()\n /**\n * umdHookUnmount can works in default mode\n * register through window.unmount\n */\n this.umdHookUnmount = unmount as Func\n // if mount & unmount is function, the sub app is umd mode\n if (isFunction(mount) && isFunction(unmount)) {\n this.umdHookMount = mount as Func\n // sandbox must exist\n this.sandBox!.markUmdMode(this.umdMode = true)\n try {\n this.handleMounted(this.umdHookMount(microApp.getData(this.name, true)))\n } catch (e) {\n /**\n * TODO:\n * 1. 是否应该直接抛出错误\n * 2. 是否应该触发error生命周期\n */\n logError('An error occurred in window.mount \\n', this.name, e)\n }\n } else if (isFinished === true) {\n this.handleMounted()\n }\n }\n })\n } else {\n this.sandBox?.rebuildEffectSnapshot()\n try {\n this.handleMounted(this.umdHookMount!(microApp.getData(this.name, true)))\n } catch (e) {\n logError('An error occurred in window.mount \\n', this.name, e)\n }\n }\n }\n }\n\n // TODO: 可优化?\n this.sandBox ? this.sandBox.sandboxReady.then(nextAction) : nextAction()\n }\n\n /**\n * handle for promise umdHookMount\n * @param umdHookMountResult result of umdHookMount\n */\n private handleMounted (umdHookMountResult?: unknown): void {\n const dispatchAction = () => {\n if (isPromise(umdHookMountResult)) {\n umdHookMountResult\n .then(() => this.dispatchMountedEvent())\n .catch((e) => {\n logError('An error occurred in window.mount \\n', this.name, e)\n this.dispatchMountedEvent()\n })\n } else {\n this.dispatchMountedEvent()\n }\n }\n\n if (this.isPrerender) {\n this.preRenderEvents?.push(dispatchAction)\n this.sandBox?.recordAndReleaseEffect({ isPrerender: true })\n } else {\n dispatchAction()\n }\n }\n\n /**\n * dispatch mounted event when app run finished\n */\n private dispatchMountedEvent (): void {\n if (!this.isUnmounted()) {\n this.setAppState(appStates.MOUNTED)\n // call window.onmount of child app\n execMicroAppGlobalHook(\n this.getMicroAppGlobalHook(microGlobalEvent.ONMOUNT),\n this.name,\n microGlobalEvent.ONMOUNT,\n microApp.getData(this.name, true)\n )\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.MOUNTED\n })\n\n // dispatch mounted event to micro app\n dispatchCustomEventToMicroApp(this, 'mounted')\n\n this.setLifeCycleState(lifeCycles.MOUNTED)\n\n // dispatch event mounted to parent\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.MOUNTED,\n )\n\n /**\n * Hidden Keep-alive app during resource loading, render normally to ensure their liveliness (running in the background) characteristics.\n * Actions:\n * 1. Record & release all global events after mount\n */\n if (this.isHidden()) {\n this.sandBox?.recordAndReleaseEffect({ keepAlive: true })\n }\n }\n /**\n * TODO: 这里增加一个处理,如果渲染完成时已经卸载,则进行一些操作\n * 如果是默认模式:删除所有事件和定时器\n * 如果是umd模式:重新记录和清空事件\n * 补充:非必需,优先级低\n */\n }\n\n /**\n * unmount app\n * NOTE:\n * 1. do not add any params on account of unmountApp\n * @param destroy completely destroy, delete cache resources\n * @param clearData clear data of dateCenter\n * @param keepRouteState keep route state when unmount, default is false\n * @param unmountcb callback of unmount\n */\n public unmount ({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n }: UnmountParam): void {\n destroy = destroy || this.state === appStates.LOAD_FAILED\n\n this.setAppState(appStates.UNMOUNT)\n\n let umdHookUnmountResult: unknown = null\n try {\n // call umd unmount hook before the sandbox is cleared\n umdHookUnmountResult = this.umdHookUnmount?.(microApp.getData(this.name, true))\n } catch (e) {\n logError('An error occurred in window.unmount \\n', this.name, e)\n }\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.UNMOUNT\n })\n\n // dispatch unmount event to micro app\n dispatchCustomEventToMicroApp(this, 'unmount')\n\n // call window.onunmount of child app\n execMicroAppGlobalHook(\n this.getMicroAppGlobalHook(microGlobalEvent.ONUNMOUNT),\n this.name,\n microGlobalEvent.ONUNMOUNT,\n )\n\n this.handleUnmounted({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n umdHookUnmountResult,\n })\n }\n\n /**\n * handle for promise umdHookUnmount\n * @param destroy completely destroy, delete cache resources\n * @param clearData clear data of dateCenter\n * @param keepRouteState keep route state when unmount, default is false\n * @param unmountcb callback of unmount\n * @param umdHookUnmountResult result of umdHookUnmount\n */\n private handleUnmounted ({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n umdHookUnmountResult,\n }: UnmountParam & {\n umdHookUnmountResult: unknown,\n }): void {\n const nextAction = () => this.actionsForUnmount({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n })\n\n if (isPromise(umdHookUnmountResult)) {\n // async window.unmount will cause appName bind error in nest app\n removeDomScope()\n umdHookUnmountResult.then(nextAction).catch(nextAction)\n } else {\n nextAction()\n }\n }\n\n /**\n * actions for unmount app\n * @param destroy completely destroy, delete cache resources\n * @param clearData clear data of dateCenter\n * @param keepRouteState keep route state when unmount, default is false\n * @param unmountcb callback of unmount\n */\n private actionsForUnmount ({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n }: UnmountParam): void {\n if (this.umdMode && this.container && !destroy) {\n cloneContainer(this.source.html as Element, this.container, false)\n }\n\n /**\n * this.container maybe contains micro-app element, stop sandbox should exec after cloneContainer\n * NOTE:\n * 1. if destroy is true, clear route state\n * 2. umd mode and keep-alive will not clear EventSource\n */\n this.sandBox?.stop({\n umdMode: this.umdMode,\n keepRouteState: keepRouteState && !destroy,\n destroy,\n clearData: clearData || destroy,\n })\n\n this.setLifeCycleState(lifeCycles.UNMOUNT)\n\n // dispatch unmount event to base app\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.UNMOUNT,\n )\n\n this.clearOptions(destroy)\n\n unmountcb?.()\n }\n\n private clearOptions (destroy: boolean): void {\n this.container!.innerHTML = ''\n this.container = null\n this.isPrerender = false\n this.preRenderEvents = null\n this.setKeepAliveState(null)\n // in iframe sandbox & default mode, delete the sandbox & iframeElement\n if (this.iframe && !this.umdMode) this.sandBox = null\n if (destroy) this.actionsForCompletelyDestroy()\n removeDomScope()\n }\n\n // actions for completely destroy\n public actionsForCompletelyDestroy (): void {\n this.sandBox?.deleteIframeElement?.()\n sourceCenter.script.deleteInlineInfo(this.source.scripts)\n appInstanceMap.delete(this.name)\n }\n\n // hidden app when disconnectedCallback called with keep-alive\n public hiddenKeepAliveApp (callback?: CallableFunction): void {\n this.setKeepAliveState(keepAliveStates.KEEP_ALIVE_HIDDEN)\n /**\n * afterhidden事件需要提前发送,原因如下:\n * 1. 此时发送this.container还指向micro-app元素,而不是临时div元素\n * 2. 沙箱执行recordAndReleaseEffect后会将appstate-change方法也清空,之后再发送子应用也接受不到了\n * 3. 对于this.loadSourceLevel !== 2的情况,unmount是同步执行的,所以也会出现2的问题\n * TODO: 有可能导致的问题\n * 1. 在基座接受到afterhidden方法后立即执行unmount,彻底destroy应用时,因为unmount时同步执行,所以this.container为null后才执行cloneContainer\n */\n dispatchCustomEventToMicroApp(this, 'appstate-change', {\n appState: 'afterhidden',\n })\n\n this.setLifeCycleState(lifeCycles.AFTERHIDDEN)\n // dispatch afterHidden event to base app\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.AFTERHIDDEN,\n )\n\n if (this.routerMode !== ROUTER_MODE_CUSTOM) {\n // called after lifeCyclesEvent\n this.sandBox?.removeRouteInfoForKeepAliveApp()\n }\n\n /**\n * Hidden app before the resources are loaded, then unmount the app\n */\n if (this.loadSourceLevel !== 2) {\n getRootContainer(this.container!).unmount()\n } else {\n this.container = cloneContainer(\n pureCreateElement('div'),\n this.container as Element,\n false,\n )\n\n this.sandBox?.recordAndReleaseEffect({ keepAlive: true })\n }\n\n callback?.()\n }\n\n // show app when connectedCallback called with keep-alive\n public showKeepAliveApp (container: HTMLElement | ShadowRoot): void {\n this.sandBox?.rebuildEffectSnapshot()\n\n // dispatch beforeShow event to micro-app\n dispatchCustomEventToMicroApp(this, 'appstate-change', {\n appState: 'beforeshow',\n })\n\n // dispatch beforeShow event to base app\n dispatchLifecyclesEvent(\n container,\n this.name,\n lifeCycles.BEFORESHOW,\n )\n\n this.setKeepAliveState(keepAliveStates.KEEP_ALIVE_SHOW)\n\n this.container = cloneContainer(\n container,\n this.container as Element,\n false,\n )\n\n /**\n * TODO:\n * 问题:当路由模式为custom时,keep-alive应用在重新展示,是否需要根据子应用location信息更新浏览器地址?\n * 暂时不这么做吧,因为无法确定二次展示时新旧地址是否相同,是否带有特殊信息\n */\n if (this.routerMode !== ROUTER_MODE_CUSTOM) {\n // called before lifeCyclesEvent\n this.sandBox?.setRouteInfoForKeepAliveApp()\n }\n\n // dispatch afterShow event to micro-app\n dispatchCustomEventToMicroApp(this, 'appstate-change', {\n appState: 'aftershow',\n })\n\n this.setLifeCycleState(lifeCycles.AFTERSHOW)\n\n // dispatch afterShow event to base app\n dispatchLifecyclesEvent(\n this.container,\n this.name,\n lifeCycles.AFTERSHOW,\n )\n }\n\n /**\n * app rendering error\n * @param e Error\n */\n public onerror (e: Error): void {\n this.setLifeCycleState(lifeCycles.ERROR)\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.LOAD_FAILED\n })\n\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.ERROR,\n e,\n )\n }\n\n /**\n * Scene:\n * 1. create app\n * 2. remount of default mode with iframe sandbox\n * In default mode with iframe sandbox, unmount app will delete iframeElement & sandBox, and create sandBox when mount again, used to solve the problem that module script cannot be execute when append it again\n */\n private createSandbox (): void {\n if (this.useSandbox && !this.sandBox) {\n if (this.iframe) {\n this.sandBox = new IframeSandbox(this.name, this.url)\n } else {\n this.sandBox = new WithSandBox(this.name, this.url)\n }\n }\n }\n\n // set app state\n public setAppState (state: string): void {\n this.state = state\n\n // set window.__MICRO_APP_STATE__\n this.sandBox?.setStaticAppState(state)\n }\n\n // get app state\n public getAppState (): string {\n return this.state\n }\n\n // set app lifeCycleState\n private setLifeCycleState (state: string): void {\n this.lifeCycleState = state\n }\n\n // get app lifeCycleState\n public getLifeCycleState (): string {\n return this.lifeCycleState || ''\n }\n\n // set keep-alive state\n private setKeepAliveState (state: string | null): void {\n this.keepAliveState = state\n }\n\n // get keep-alive state\n public getKeepAliveState (): string | null {\n return this.keepAliveState\n }\n\n // is app unmounted\n public isUnmounted (): boolean {\n return appStates.UNMOUNT === this.state\n }\n\n // is app already hidden\n public isHidden (): boolean {\n return keepAliveStates.KEEP_ALIVE_HIDDEN === this.keepAliveState\n }\n\n // get umd library, if it not exist, return empty object\n private getUmdLibraryHooks (): Record<string, unknown> {\n // after execScripts, the app maybe unmounted\n if (!this.isUnmounted() && this.sandBox) {\n const libraryName = getRootContainer(this.container!).getAttribute('library') || `micro-app-${this.name}`\n\n const proxyWindow = this.sandBox.proxyWindow as Record<string, any>\n\n // compatible with pre versions\n if (isObject(proxyWindow[libraryName])) {\n return proxyWindow[libraryName]\n }\n\n return {\n mount: proxyWindow.mount,\n unmount: proxyWindow.unmount,\n }\n }\n\n return {}\n }\n\n private getMicroAppGlobalHook (eventName: string): Func | null {\n const listener = (this.sandBox?.proxyWindow as Record<string, any>)?.[eventName]\n return isFunction(listener) ? listener : null\n }\n\n public querySelector (selectors: string): Node | null {\n return this.container ? globalEnv.rawElementQuerySelector.call(this.container, selectors) : null\n }\n\n public querySelectorAll (selectors: string): NodeListOf<Node> {\n return this.container ? globalEnv.rawElementQuerySelectorAll.call(this.container, selectors) : []\n }\n\n /**\n * NOTE:\n * 1. If the iframe sandbox no longer enforces the use of inline mode in the future, the way getElementsByTagName retrieves the script from the iframe by default needs to be changed, because in non inline mode, the script in the iframe may be empty\n * @param inline inline mode config\n */\n private getInlineModeState (inline?: boolean): boolean {\n return (this.iframe || inline) ?? false\n }\n}\n\n// iframe route mode\nexport function isIframeSandbox (appName: string): boolean {\n return appInstanceMap.get(appName)?.iframe ?? false\n}\n","import type {\n Func,\n AppInterface,\n} from '@micro-app/types'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} from '../create_app'\nimport {\n CompletionPath,\n getCurrentAppName,\n pureCreateElement,\n removeDomScope,\n isInvalidQuerySelectorKey,\n isUniqueElement,\n isProxyDocument,\n isFunction,\n isElement,\n isNode,\n rawDefineProperty,\n rawDefineProperties,\n isLinkElement,\n isStyleElement,\n isScriptElement,\n isIFrameElement,\n isMicroAppBody,\n} from '../libs/utils'\nimport scopedCSS from '../sandbox/scoped_css'\nimport {\n extractLinkFromHtml,\n formatDynamicLink,\n} from './links'\nimport {\n extractScriptElement,\n runDynamicInlineScript,\n runDynamicRemoteScript,\n checkExcludeUrl,\n checkIgnoreUrl,\n} from './scripts'\nimport {\n fixReactHMRConflict,\n} from '../sandbox/adapter'\nimport microApp from '../micro_app'\nimport globalEnv from '../libs/global_env'\n\n// Record element and map element\nconst dynamicElementInMicroAppMap = new WeakMap<Node, Element | Comment>()\n\n// Get the map element\nfunction getMappingNode (node: Node): Node {\n return dynamicElementInMicroAppMap.get(node) ?? node\n}\n\n/**\n * Process the new node and format the style, link and script element\n * @param child new node\n * @param app app\n */\nfunction handleNewNode (child: Node, app: AppInterface): Node {\n if (dynamicElementInMicroAppMap.has(child)) {\n return dynamicElementInMicroAppMap.get(child)!\n } else if (isStyleElement(child)) {\n if (child.hasAttribute('exclude')) {\n const replaceComment = document.createComment('style element with exclude attribute ignored by micro-app')\n dynamicElementInMicroAppMap.set(child, replaceComment)\n return replaceComment\n } else if (app.scopecss && !child.hasAttribute('ignore')) {\n return scopedCSS(child, app)\n }\n return child\n } else if (isLinkElement(child)) {\n if (child.hasAttribute('exclude') || checkExcludeUrl(child.getAttribute('href'), app.name)) {\n const linkReplaceComment = document.createComment('link element with exclude attribute ignored by micro-app')\n dynamicElementInMicroAppMap.set(child, linkReplaceComment)\n return linkReplaceComment\n } else if (\n child.hasAttribute('ignore') ||\n checkIgnoreUrl(child.getAttribute('href'), app.name) ||\n (\n child.href &&\n isFunction(microApp.options.excludeAssetFilter) &&\n microApp.options.excludeAssetFilter(child.href)\n )\n ) {\n return child\n }\n\n const { address, linkInfo, replaceComment } = extractLinkFromHtml(\n child,\n null,\n app,\n true,\n )\n\n if (address && linkInfo) {\n const replaceStyle = formatDynamicLink(address, app, linkInfo, child)\n dynamicElementInMicroAppMap.set(child, replaceStyle)\n return replaceStyle\n } else if (replaceComment) {\n dynamicElementInMicroAppMap.set(child, replaceComment)\n return replaceComment\n }\n\n return child\n } else if (isScriptElement(child)) {\n if (\n child.src &&\n isFunction(microApp.options.excludeAssetFilter) &&\n microApp.options.excludeAssetFilter(child.src)\n ) {\n return child\n }\n\n const { replaceComment, address, scriptInfo } = extractScriptElement(\n child,\n null,\n app,\n true,\n ) || {}\n\n if (address && scriptInfo) {\n // remote script or inline script\n const replaceElement: HTMLScriptElement | Comment = scriptInfo.isExternal ? runDynamicRemoteScript(address, app, scriptInfo, child) : runDynamicInlineScript(address, app, scriptInfo)\n dynamicElementInMicroAppMap.set(child, replaceElement)\n return replaceElement\n } else if (replaceComment) {\n dynamicElementInMicroAppMap.set(child, replaceComment)\n return replaceComment\n }\n\n return child\n }\n\n return child\n}\n\n/**\n * Handle the elements inserted into head and body, and execute normally in other cases\n * @param app app\n * @param method raw method\n * @param parent parent node\n * @param targetChild target node\n * @param passiveChild second param of insertBefore and replaceChild\n */\nfunction invokePrototypeMethod (\n app: AppInterface,\n rawMethod: Func,\n parent: Node,\n targetChild: Node,\n passiveChild?: Node | null,\n): any {\n const hijackParent = getHijackParent(parent, targetChild, app)\n /**\n * If passiveChild is not the child node, insertBefore replaceChild will have a problem, at this time, it will be degraded to appendChild\n * E.g: document.head.insertBefore(targetChild, document.head.childNodes[0])\n */\n if (hijackParent) {\n /**\n * If parentNode is <micro-app-body>, return rawDocument.body\n * Scenes:\n * 1. element-ui@2/lib/utils/vue-popper.js\n * if (this.popperElm.parentNode === document.body) ...\n * WARNING:\n * 1. When operate child from parentNode async, may have been unmount\n * e.g. target.parentNode.remove(target)\n * ISSUE:\n * 1. https://github.com/micro-zoe/micro-app/issues/739\n * Solution: Return the true value when node not in document\n */\n if (\n !isIframeSandbox(app.name) &&\n isMicroAppBody(hijackParent) &&\n rawMethod !== globalEnv.rawRemoveChild\n ) {\n const descriptor = Object.getOwnPropertyDescriptor(targetChild, 'parentNode')\n if ((!descriptor || descriptor.configurable) && !targetChild.__MICRO_APP_HAS_DPN__) {\n rawDefineProperties(targetChild, {\n parentNode: {\n configurable: true,\n get () {\n const result: ParentNode = globalEnv.rawParentNodeDesc.get.call(this)\n if (isMicroAppBody(result) && app.container) {\n // TODO: remove getRootElementParentNode\n return microApp.options.getRootElementParentNode?.(this, app.name) || document.body\n }\n return result\n },\n },\n __MICRO_APP_HAS_DPN__: {\n configurable: true,\n get: () => true,\n }\n })\n }\n }\n\n /**\n * 1. If passiveChild exists, it must be insertBefore or replaceChild\n * 2. When removeChild, targetChild may not be in microAppHead or head\n */\n if (passiveChild && !hijackParent.contains(passiveChild)) {\n return globalEnv.rawAppendChild.call(hijackParent, targetChild)\n } else if (rawMethod === globalEnv.rawRemoveChild && !hijackParent.contains(targetChild)) {\n if (parent.contains(targetChild)) {\n return rawMethod.call(parent, targetChild)\n }\n return targetChild\n }\n\n if (\n __DEV__ &&\n isIFrameElement(targetChild) &&\n rawMethod === globalEnv.rawAppendChild\n ) {\n fixReactHMRConflict(app)\n }\n\n return invokeRawMethod(rawMethod, hijackParent, targetChild, passiveChild)\n }\n\n return invokeRawMethod(rawMethod, parent, targetChild, passiveChild)\n}\n\n// head/body map to micro-app-head/micro-app-body\nfunction getHijackParent (\n parent: Node,\n targetChild: Node,\n app: AppInterface,\n): HTMLElement | null | undefined {\n if (app) {\n if (parent === document.head) {\n if (app.iframe && isScriptElement(targetChild)) {\n return app.sandBox.microHead\n }\n return app.querySelector<HTMLElement>('micro-app-head')\n }\n if (parent === document.body || parent === document.body.parentNode) {\n if (app.iframe && isScriptElement(targetChild)) {\n return app.sandBox.microBody\n }\n return app.querySelector<HTMLElement>('micro-app-body')\n }\n if (app.iframe && isScriptElement(targetChild)) {\n return app.sandBox.microBody\n }\n }\n return null\n}\n\nfunction invokeRawMethod (\n rawMethod: Func,\n parent: Node,\n targetChild: Node,\n passiveChild?: Node | null\n) {\n if (isPendMethod(rawMethod)) {\n return rawMethod.call(parent, targetChild)\n }\n\n return rawMethod.call(parent, targetChild, passiveChild)\n}\n\nfunction isPendMethod (method: CallableFunction) {\n return method === globalEnv.rawAppend || method === globalEnv.rawPrepend\n}\n\n/**\n * Attempt to complete the static resource address again before insert the node\n * @param app app instance\n * @param newChild target node\n */\nfunction completePathDynamic (app: AppInterface, newChild: Node): void {\n if (isElement(newChild)) {\n if (/^(img|script)$/i.test(newChild.tagName)) {\n if (newChild.hasAttribute('src')) {\n globalEnv.rawSetAttribute.call(newChild, 'src', CompletionPath(newChild.getAttribute('src')!, app.url))\n }\n if (newChild.hasAttribute('srcset')) {\n globalEnv.rawSetAttribute.call(newChild, 'srcset', CompletionPath(newChild.getAttribute('srcset')!, app.url))\n }\n } else if (/^link$/i.test(newChild.tagName) && newChild.hasAttribute('href')) {\n globalEnv.rawSetAttribute.call(newChild, 'href', CompletionPath(newChild.getAttribute('href')!, app.url))\n }\n }\n}\n\n/**\n * method of handle new node\n * @param parent parent node\n * @param newChild new node\n * @param passiveChild passive node\n * @param rawMethod method\n */\nfunction commonElementHandler (\n parent: Node,\n newChild: Node,\n passiveChild: Node | null,\n rawMethod: Func,\n) {\n const currentAppName = getCurrentAppName()\n if (\n isNode(newChild) &&\n !newChild.__PURE_ELEMENT__ &&\n (\n newChild.__MICRO_APP_NAME__ ||\n currentAppName\n )\n ) {\n newChild.__MICRO_APP_NAME__ = newChild.__MICRO_APP_NAME__ || currentAppName!\n const app = appInstanceMap.get(newChild.__MICRO_APP_NAME__)\n if (app?.container) {\n completePathDynamic(app, newChild)\n return invokePrototypeMethod(\n app,\n rawMethod,\n parent,\n handleNewNode(newChild, app),\n passiveChild && getMappingNode(passiveChild),\n )\n }\n }\n\n if (rawMethod === globalEnv.rawAppend || rawMethod === globalEnv.rawPrepend) {\n return rawMethod.call(parent, newChild)\n }\n\n return rawMethod.call(parent, newChild, passiveChild)\n}\n\n/**\n * Rewrite element prototype method\n */\nexport function patchElementAndDocument (): void {\n patchDocument()\n\n const rawRootElement = globalEnv.rawRootElement\n const rawRootNode = globalEnv.rawRootNode\n\n // prototype methods of add element👇\n rawRootElement.prototype.appendChild = function appendChild<T extends Node> (newChild: T): T {\n return commonElementHandler(this, newChild, null, globalEnv.rawAppendChild)\n }\n\n rawRootElement.prototype.insertBefore = function insertBefore<T extends Node> (newChild: T, refChild: Node | null): T {\n return commonElementHandler(this, newChild, refChild, globalEnv.rawInsertBefore)\n }\n\n rawRootElement.prototype.replaceChild = function replaceChild<T extends Node> (newChild: Node, oldChild: T): T {\n return commonElementHandler(this, newChild, oldChild, globalEnv.rawReplaceChild)\n }\n\n rawRootElement.prototype.append = function append (...nodes: (Node | string)[]): void {\n let i = 0\n while (i < nodes.length) {\n let node = nodes[i]\n node = isNode(node) ? node : globalEnv.rawCreateTextNode.call(globalEnv.rawDocument, node)\n commonElementHandler(this, markElement(node as Node), null, globalEnv.rawAppend)\n i++\n }\n }\n\n rawRootElement.prototype.prepend = function prepend (...nodes: (Node | string)[]): void {\n let i = nodes.length\n while (i > 0) {\n let node = nodes[i - 1]\n node = isNode(node) ? node : globalEnv.rawCreateTextNode.call(globalEnv.rawDocument, node)\n commonElementHandler(this, markElement(node as Node), null, globalEnv.rawPrepend)\n i--\n }\n }\n\n // prototype methods of delete element👇\n rawRootElement.prototype.removeChild = function removeChild<T extends Node> (oldChild: T): T {\n if (oldChild?.__MICRO_APP_NAME__) {\n const app = appInstanceMap.get(oldChild.__MICRO_APP_NAME__)\n if (app?.container) {\n return invokePrototypeMethod(\n app,\n globalEnv.rawRemoveChild,\n this,\n getMappingNode(oldChild),\n )\n }\n try {\n return globalEnv.rawRemoveChild.call(this, oldChild) as T\n } catch {\n return (oldChild?.parentNode && globalEnv.rawRemoveChild.call(oldChild.parentNode, oldChild)) as T\n }\n }\n\n return globalEnv.rawRemoveChild.call(this, oldChild) as T\n }\n\n /**\n * The insertAdjacentElement method of the Element interface inserts a given element node at a given position relative to the element it is invoked upon.\n * NOTE:\n * 1. parameter 2 of insertAdjacentElement must type 'Element'\n */\n rawRootElement.prototype.insertAdjacentElement = function (where: InsertPosition, element: Element): Element | null {\n if (element?.__MICRO_APP_NAME__ && isElement(element)) {\n const app = appInstanceMap.get(element.__MICRO_APP_NAME__)\n if (app?.container) {\n const processedEle = handleNewNode(element, app) as Element\n if (!isElement(processedEle)) return element\n const realParent = getHijackParent(this, processedEle, app) ?? this\n return globalEnv.rawInsertAdjacentElement.call(realParent, where, processedEle)\n }\n }\n return globalEnv.rawInsertAdjacentElement.call(this, where, element)\n }\n\n // patch cloneNode\n rawRootElement.prototype.cloneNode = function cloneNode (deep?: boolean): Node {\n const clonedNode = globalEnv.rawCloneNode.call(this, deep)\n this.__MICRO_APP_NAME__ && (clonedNode.__MICRO_APP_NAME__ = this.__MICRO_APP_NAME__)\n return clonedNode\n }\n\n function getQueryTarget (node: Node): Node | null {\n const currentAppName = getCurrentAppName()\n if ((node === document.body || node === document.head) && currentAppName) {\n const app = appInstanceMap.get(currentAppName)\n if (app?.container) {\n if (node === document.body) {\n return app.querySelector('micro-app-body')\n } else if (node === document.head) {\n return app.querySelector('micro-app-head')\n }\n }\n }\n return null\n }\n\n rawRootElement.prototype.querySelector = function querySelector (selectors: string): Node | null {\n const target = getQueryTarget(this) ?? this\n return globalEnv.rawElementQuerySelector.call(target, selectors)\n }\n\n rawRootElement.prototype.querySelectorAll = function querySelectorAll (selectors: string): NodeListOf<Node> {\n const target = getQueryTarget(this) ?? this\n return globalEnv.rawElementQuerySelectorAll.call(target, selectors)\n }\n\n // rewrite setAttribute, complete resource address\n rawRootElement.prototype.setAttribute = function setAttribute (key: string, value: any): void {\n const appName = this.__MICRO_APP_NAME__ || getCurrentAppName()\n if (\n appName &&\n appInstanceMap.has(appName) &&\n (\n ((key === 'src' || key === 'srcset') && /^(img|script|video|audio|source|embed)$/i.test(this.tagName)) ||\n (key === 'href' && /^link$/i.test(this.tagName))\n )\n ) {\n const app = appInstanceMap.get(appName)\n value = CompletionPath(value, app!.url)\n }\n\n globalEnv.rawSetAttribute.call(this, key, value)\n }\n\n /**\n * TODO: 兼容直接通过img.src等操作设置的资源\n * NOTE:\n * 1. 卸载时恢复原始值\n * 2. 循环嵌套的情况\n * 3. 放在global_env中统一处理\n * 4. 是否和completePathDynamic的作用重复?\n */\n // const protoAttrList: Array<[HTMLElement, string]> = [\n // [HTMLImageElement.prototype, 'src'],\n // [HTMLScriptElement.prototype, 'src'],\n // [HTMLLinkElement.prototype, 'href'],\n // ]\n\n // protoAttrList.forEach(([target, attr]) => {\n // const { enumerable, configurable, get, set } = Object.getOwnPropertyDescriptor(target, attr) || {\n // enumerable: true,\n // configurable: true,\n // }\n\n // rawDefineProperty(target, attr, {\n // enumerable,\n // configurable,\n // get: function () {\n // return get?.call(this)\n // },\n // set: function (value) {\n // const currentAppName = getCurrentAppName()\n // if (currentAppName && appInstanceMap.has(currentAppName)) {\n // const app = appInstanceMap.get(currentAppName)\n // value = CompletionPath(value, app!.url)\n // }\n // set?.call(this, value)\n // },\n // })\n // })\n\n rawDefineProperty(rawRootElement.prototype, 'innerHTML', {\n configurable: true,\n enumerable: true,\n get () {\n return globalEnv.rawInnerHTMLDesc.get.call(this)\n },\n set (code: string) {\n globalEnv.rawInnerHTMLDesc.set.call(this, code)\n const currentAppName = getCurrentAppName()\n Array.from(this.children).forEach((child) => {\n if (isElement(child) && currentAppName) {\n // TODO: 使用updateElementInfo进行更新\n child.__MICRO_APP_NAME__ = currentAppName\n }\n })\n }\n })\n\n rawDefineProperty(rawRootNode.prototype, 'parentNode', {\n configurable: true,\n enumerable: true,\n get () {\n /**\n * hijack parentNode of html\n * Scenes:\n * 1. element-ui@2/lib/utils/popper.js\n * // root is child app window, so root.document is proxyDocument or microDocument\n * if (element.parentNode === root.document) ...\n */\n const currentAppName = getCurrentAppName()\n if (currentAppName && this === globalEnv.rawDocument.firstElementChild) {\n const microDocument = appInstanceMap.get(currentAppName)?.sandBox?.proxyWindow?.document\n if (microDocument) return microDocument\n }\n const result = globalEnv.rawParentNodeDesc.get.call(this)\n /**\n * If parentNode is <micro-app-body>, return rawDocument.body\n * Scenes:\n * 1. element-ui@2/lib/utils/vue-popper.js\n * if (this.popperElm.parentNode === document.body) ...\n * WARNING:\n * Will it cause other problems ?\n * e.g. target.parentNode.remove(target)\n * BUG:\n * 1. vue2 umdMode, throw error when render again (<div id='app'></div> will be deleted when render again ) -- Abandon this way at 2023.2.28 before v1.0.0-beta.0, it will cause vue2 throw error when render again\n */\n // if (isMicroAppBody(result) && appInstanceMap.get(this.__MICRO_APP_NAME__)?.container) {\n // return document.body\n // }\n return result\n },\n })\n}\n\n/**\n * Mark the newly created element in the micro application\n * @param element new element\n */\nfunction markElement <T extends Node> (element: T): T {\n const currentAppName = getCurrentAppName()\n if (currentAppName) element.__MICRO_APP_NAME__ = currentAppName\n return element\n}\n\n// methods of document\nfunction patchDocument () {\n const rawDocument = globalEnv.rawDocument\n const rawRootDocument = globalEnv.rawRootDocument\n\n function getBindTarget (target: Document): Document {\n return isProxyDocument(target) ? rawDocument : target\n }\n\n // create element 👇\n rawRootDocument.prototype.createElement = function createElement (\n tagName: string,\n options?: ElementCreationOptions,\n ): HTMLElement {\n const element = globalEnv.rawCreateElement.call(getBindTarget(this), tagName, options)\n return markElement(element)\n }\n\n rawRootDocument.prototype.createElementNS = function createElementNS (\n namespaceURI: string,\n name: string,\n options?: string | ElementCreationOptions,\n ): any {\n const element = globalEnv.rawCreateElementNS.call(getBindTarget(this), namespaceURI, name, options)\n return markElement(element)\n }\n\n rawRootDocument.prototype.createDocumentFragment = function createDocumentFragment (): DocumentFragment {\n const element = globalEnv.rawCreateDocumentFragment.call(getBindTarget(this))\n return markElement(element)\n }\n\n // rawRootDocument.prototype.createTextNode = function createTextNode (data: string): Text {\n // const element = globalEnv.rawCreateTextNode.call(getBindTarget(this), data)\n // return markElement(element)\n // }\n\n rawRootDocument.prototype.createComment = function createComment (data: string): Comment {\n const element = globalEnv.rawCreateComment.call(getBindTarget(this), data)\n return markElement(element)\n }\n\n // query element👇\n function querySelector (this: Document, selectors: string): any {\n const _this = getBindTarget(this)\n const currentAppName = getCurrentAppName()\n if (\n !currentAppName ||\n !selectors ||\n isUniqueElement(selectors) ||\n // see https://github.com/micro-zoe/micro-app/issues/56\n rawDocument !== _this\n ) {\n return globalEnv.rawQuerySelector.call(_this, selectors)\n }\n\n return appInstanceMap.get(currentAppName)?.querySelector(selectors) ?? null\n }\n\n function querySelectorAll (this: Document, selectors: string): any {\n const _this = getBindTarget(this)\n const currentAppName = getCurrentAppName()\n if (\n !currentAppName ||\n !selectors ||\n isUniqueElement(selectors) ||\n rawDocument !== _this\n ) {\n return globalEnv.rawQuerySelectorAll.call(_this, selectors)\n }\n\n return appInstanceMap.get(currentAppName)?.querySelectorAll(selectors) ?? []\n }\n\n rawRootDocument.prototype.querySelector = querySelector\n rawRootDocument.prototype.querySelectorAll = querySelectorAll\n\n rawRootDocument.prototype.getElementById = function getElementById (key: string): HTMLElement | null {\n const _this = getBindTarget(this)\n if (!getCurrentAppName() || isInvalidQuerySelectorKey(key)) {\n return globalEnv.rawGetElementById.call(_this, key)\n }\n\n try {\n return querySelector.call(_this, `#${key}`)\n } catch {\n return globalEnv.rawGetElementById.call(_this, key)\n }\n }\n\n rawRootDocument.prototype.getElementsByClassName = function getElementsByClassName (key: string): HTMLCollectionOf<Element> {\n const _this = getBindTarget(this)\n if (!getCurrentAppName() || isInvalidQuerySelectorKey(key)) {\n return globalEnv.rawGetElementsByClassName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(_this, `.${key}`)\n } catch {\n return globalEnv.rawGetElementsByClassName.call(_this, key)\n }\n }\n\n rawRootDocument.prototype.getElementsByTagName = function getElementsByTagName (key: string): HTMLCollectionOf<Element> {\n const _this = getBindTarget(this)\n const currentAppName = getCurrentAppName()\n if (\n !currentAppName ||\n isUniqueElement(key) ||\n isInvalidQuerySelectorKey(key) ||\n (!appInstanceMap.get(currentAppName)?.inline && /^script$/i.test(key))\n ) {\n return globalEnv.rawGetElementsByTagName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(_this, key)\n } catch {\n return globalEnv.rawGetElementsByTagName.call(_this, key)\n }\n }\n\n rawRootDocument.prototype.getElementsByName = function getElementsByName (key: string): NodeListOf<HTMLElement> {\n const _this = getBindTarget(this)\n if (!getCurrentAppName() || isInvalidQuerySelectorKey(key)) {\n return globalEnv.rawGetElementsByName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(_this, `[name=${key}]`)\n } catch {\n return globalEnv.rawGetElementsByName.call(_this, key)\n }\n }\n}\n\nfunction releasePatchDocument (): void {\n const rawRootDocument = globalEnv.rawRootDocument\n rawRootDocument.prototype.createElement = globalEnv.rawCreateElement\n rawRootDocument.prototype.createElementNS = globalEnv.rawCreateElementNS\n rawRootDocument.prototype.createDocumentFragment = globalEnv.rawCreateDocumentFragment\n rawRootDocument.prototype.querySelector = globalEnv.rawQuerySelector\n rawRootDocument.prototype.querySelectorAll = globalEnv.rawQuerySelectorAll\n rawRootDocument.prototype.getElementById = globalEnv.rawGetElementById\n rawRootDocument.prototype.getElementsByClassName = globalEnv.rawGetElementsByClassName\n rawRootDocument.prototype.getElementsByTagName = globalEnv.rawGetElementsByTagName\n rawRootDocument.prototype.getElementsByName = globalEnv.rawGetElementsByName\n}\n\n// release patch\nexport function releasePatchElementAndDocument (): void {\n removeDomScope()\n releasePatchDocument()\n\n const rawRootElement = globalEnv.rawRootElement\n const rawRootNode = globalEnv.rawRootNode\n rawRootElement.prototype.appendChild = globalEnv.rawAppendChild\n rawRootElement.prototype.insertBefore = globalEnv.rawInsertBefore\n rawRootElement.prototype.replaceChild = globalEnv.rawReplaceChild\n rawRootElement.prototype.removeChild = globalEnv.rawRemoveChild\n rawRootElement.prototype.append = globalEnv.rawAppend\n rawRootElement.prototype.prepend = globalEnv.rawPrepend\n rawRootElement.prototype.cloneNode = globalEnv.rawCloneNode\n rawRootElement.prototype.querySelector = globalEnv.rawElementQuerySelector\n rawRootElement.prototype.querySelectorAll = globalEnv.rawElementQuerySelectorAll\n rawRootElement.prototype.setAttribute = globalEnv.rawSetAttribute\n rawDefineProperty(rawRootElement.prototype, 'innerHTML', globalEnv.rawInnerHTMLDesc)\n rawDefineProperty(rawRootNode.prototype, 'parentNode', globalEnv.rawParentNodeDesc)\n}\n\n// Set the style of micro-app-head and micro-app-body\nlet hasRejectMicroAppStyle = false\nexport function rejectMicroAppStyle (): void {\n if (!hasRejectMicroAppStyle) {\n hasRejectMicroAppStyle = true\n const style = pureCreateElement('style')\n globalEnv.rawSetAttribute.call(style, 'type', 'text/css')\n style.textContent = `\\n${microApp.tagName}, micro-app-body { display: block; } \\nmicro-app-head { display: none; }`\n globalEnv.rawDocument.head.appendChild(style)\n }\n}\n","import type {\n AppInterface,\n RequestIdleCallbackInfo,\n RequestIdleCallbackOptions,\n} from '@micro-app/types'\nimport {\n isSupportModuleScript,\n isBrowser,\n getCurrentAppName,\n assign,\n} from './utils'\nimport {\n rejectMicroAppStyle,\n} from '../source/patch'\n\ndeclare global {\n interface Node {\n __MICRO_APP_NAME__?: string | null\n __PURE_ELEMENT__?: boolean\n __MICRO_APP_HAS_DPN__?: boolean\n data?: unknown\n rawParentNode?: ParentNode | null\n }\n\n interface HTMLStyleElement {\n __MICRO_APP_HAS_SCOPED__?: boolean\n }\n\n interface HTMLElement {\n reload(destroy?: boolean): Promise<boolean>\n mount(app: AppInterface): void\n unmount (destroy?: boolean, unmountcb?: CallableFunction): void\n }\n\n interface Window {\n requestIdleCallback (\n callback: (info: RequestIdleCallbackInfo) => void,\n opts?: RequestIdleCallbackOptions,\n ): number\n _babelPolyfill: boolean\n __MICRO_APP_ENVIRONMENT__?: boolean\n __MICRO_APP_UMD_MODE__?: boolean\n __MICRO_APP_BASE_APPLICATION__?: boolean\n __REACT_ERROR_OVERLAY_GLOBAL_HOOK__: boolean\n rawLocation: Location\n rawWindow: Window\n rawDocument: Document\n Document: any\n Element: any,\n Node: any,\n EventTarget: any,\n HTMLElement: HTMLElement,\n }\n}\n\nconst globalEnv: Record<string, any> = {\n // active sandbox count\n activeSandbox: 0,\n}\n\n/**\n * Note loop nesting\n * Only prototype or unique values can be put here\n */\nexport function initGlobalEnv (): void {\n if (isBrowser) {\n const rawWindow = window.rawWindow || Function('return window')()\n const rawDocument = window.rawDocument || Function('return document')()\n const rawRootDocument = rawWindow.Document || Function('return Document')()\n const rawRootElement = rawWindow.Element\n const rawRootNode = rawWindow.Node\n const rawRootEventTarget = rawWindow.EventTarget\n\n // save patch raw methods, pay attention to this binding\n const rawSetAttribute = rawRootElement.prototype.setAttribute\n const rawAppendChild = rawRootElement.prototype.appendChild\n const rawInsertBefore = rawRootElement.prototype.insertBefore\n const rawReplaceChild = rawRootElement.prototype.replaceChild\n const rawRemoveChild = rawRootElement.prototype.removeChild\n const rawAppend = rawRootElement.prototype.append\n const rawPrepend = rawRootElement.prototype.prepend\n const rawCloneNode = rawRootElement.prototype.cloneNode\n const rawElementQuerySelector = rawRootElement.prototype.querySelector\n const rawElementQuerySelectorAll = rawRootElement.prototype.querySelectorAll\n const rawInsertAdjacentElement = rawRootElement.prototype.insertAdjacentElement\n const rawInnerHTMLDesc = Object.getOwnPropertyDescriptor(rawRootElement.prototype, 'innerHTML')\n const rawParentNodeDesc = Object.getOwnPropertyDescriptor(rawRootNode.prototype, 'parentNode')\n\n // Document proto methods\n const rawCreateElement = rawRootDocument.prototype.createElement\n const rawCreateElementNS = rawRootDocument.prototype.createElementNS\n const rawCreateDocumentFragment = rawRootDocument.prototype.createDocumentFragment\n const rawCreateTextNode = rawRootDocument.prototype.createTextNode\n const rawCreateComment = rawRootDocument.prototype.createComment\n const rawQuerySelector = rawRootDocument.prototype.querySelector\n const rawQuerySelectorAll = rawRootDocument.prototype.querySelectorAll\n const rawGetElementById = rawRootDocument.prototype.getElementById\n const rawGetElementsByClassName = rawRootDocument.prototype.getElementsByClassName\n const rawGetElementsByTagName = rawRootDocument.prototype.getElementsByTagName\n const rawGetElementsByName = rawRootDocument.prototype.getElementsByName\n\n const ImageProxy = new Proxy(Image, {\n construct (Target, args): HTMLImageElement {\n const elementImage = new Target(...args)\n const currentAppName = getCurrentAppName()\n if (currentAppName) elementImage.__MICRO_APP_NAME__ = currentAppName\n return elementImage\n },\n })\n\n /**\n * save effect raw methods\n * pay attention to this binding, especially setInterval, setTimeout, clearInterval, clearTimeout\n */\n const rawSetInterval = rawWindow.setInterval\n const rawSetTimeout = rawWindow.setTimeout\n const rawClearInterval = rawWindow.clearInterval\n const rawClearTimeout = rawWindow.clearTimeout\n const rawPushState = rawWindow.history.pushState\n const rawReplaceState = rawWindow.history.replaceState\n const rawAddEventListener = rawRootEventTarget.prototype.addEventListener\n const rawRemoveEventListener = rawRootEventTarget.prototype.removeEventListener\n const rawDispatchEvent = rawRootEventTarget.prototype.dispatchEvent\n\n // mark current application as base application\n window.__MICRO_APP_BASE_APPLICATION__ = true\n\n assign(globalEnv, {\n supportModuleScript: isSupportModuleScript(),\n\n // common global vars\n rawWindow,\n rawDocument,\n rawRootDocument,\n rawRootElement,\n rawRootNode,\n\n // source/patch\n rawSetAttribute,\n rawAppendChild,\n rawInsertBefore,\n rawReplaceChild,\n rawRemoveChild,\n rawAppend,\n rawPrepend,\n rawCloneNode,\n rawElementQuerySelector,\n rawElementQuerySelectorAll,\n rawInsertAdjacentElement,\n rawInnerHTMLDesc,\n rawParentNodeDesc,\n\n rawCreateElement,\n rawCreateElementNS,\n rawCreateDocumentFragment,\n rawCreateTextNode,\n rawCreateComment,\n rawQuerySelector,\n rawQuerySelectorAll,\n rawGetElementById,\n rawGetElementsByClassName,\n rawGetElementsByTagName,\n rawGetElementsByName,\n ImageProxy,\n\n // sandbox/effect\n rawSetInterval,\n rawSetTimeout,\n rawClearInterval,\n rawClearTimeout,\n rawPushState,\n rawReplaceState,\n rawAddEventListener,\n rawRemoveEventListener,\n rawDispatchEvent,\n\n // iframe\n })\n\n // global effect\n rejectMicroAppStyle()\n }\n}\n\nexport default globalEnv\n","/* eslint-disable no-new */\nimport type {\n AttrType,\n MicroAppElementType,\n AppInterface,\n OptionsType,\n NormalKey,\n} from '@micro-app/types'\nimport microApp from './micro_app'\nimport dispatchLifecyclesEvent from './interact/lifecycles_event'\nimport globalEnv from './libs/global_env'\nimport {\n defer,\n formatAppName,\n formatAppURL,\n version,\n logError,\n logWarn,\n isString,\n isFunction,\n CompletionPath,\n createURL,\n isPlainObject,\n getBaseHTMLElement,\n} from './libs/utils'\nimport {\n ObservedAttrName,\n lifeCycles,\n appStates,\n} from './constants'\nimport CreateApp, {\n appInstanceMap,\n} from './create_app'\nimport {\n router,\n getNoHashMicroPathFromURL,\n getRouterMode,\n} from './sandbox/router'\n\n/**\n * define element\n * @param tagName element name\n*/\nexport function defineElement (tagName: string): void {\n class MicroAppElement extends getBaseHTMLElement() implements MicroAppElementType {\n static get observedAttributes (): string[] {\n return ['name', 'url']\n }\n\n private isWaiting = false\n private cacheData: Record<PropertyKey, unknown> | null = null\n private connectedCount = 0\n private connectStateMap: Map<number, boolean> = new Map()\n public appName = '' // app name\n public appUrl = '' // app url\n public ssrUrl = '' // html path in ssr mode\n public version = version\n\n // 👇 Configuration\n // name: app name\n // url: html address\n // shadowDom: use shadowDOM, default is false\n // destroy: whether delete cache resources when unmount, default is false\n // inline: whether js runs in inline script mode, default is false\n // disableScopecss: whether disable css scoped, default is false\n // disableSandbox: whether disable sandbox, default is false\n // baseRoute: route prefix, default is ''\n // keep-alive: open keep-alive mode\n\n public connectedCallback (): void {\n const cacheCount = ++this.connectedCount\n this.connectStateMap.set(cacheCount, true)\n /**\n * In some special scenes, such as vue's keep-alive, the micro-app will be inserted and deleted twice in an instant\n * So we execute the mount method async and record connectState to prevent repeated rendering\n */\n const effectiveApp = this.appName && this.appUrl\n defer(() => {\n if (this.connectStateMap.get(cacheCount)) {\n dispatchLifecyclesEvent(\n this,\n this.appName,\n lifeCycles.CREATED,\n )\n /**\n * If insert micro-app element without name or url, and set them in next action like angular,\n * handleConnected will be executed twice, causing the app render repeatedly,\n * so we only execute handleConnected() if url and name exist when connectedCallback\n */\n effectiveApp && this.handleConnected()\n }\n })\n }\n\n public disconnectedCallback (): void {\n this.connectStateMap.set(this.connectedCount, false)\n this.handleDisconnected()\n }\n\n /**\n * Re render app from the command line\n * MicroAppElement.reload(destroy)\n */\n public reload (destroy?: boolean): Promise<boolean> {\n return new Promise((resolve) => {\n const handleAfterReload = () => {\n this.removeEventListener(lifeCycles.MOUNTED, handleAfterReload)\n this.removeEventListener(lifeCycles.AFTERSHOW, handleAfterReload)\n resolve(true)\n }\n this.addEventListener(lifeCycles.MOUNTED, handleAfterReload)\n this.addEventListener(lifeCycles.AFTERSHOW, handleAfterReload)\n this.handleDisconnected(destroy, () => {\n this.handleConnected()\n })\n })\n }\n\n /**\n * common action for unmount\n * @param destroy reload param\n */\n private handleDisconnected (destroy = false, callback?: CallableFunction): void {\n const app = appInstanceMap.get(this.appName)\n if (app && !app.isUnmounted() && !app.isHidden()) {\n // keep-alive\n if (this.getKeepAliveModeResult() && !destroy) {\n this.handleHiddenKeepAliveApp(callback)\n } else {\n this.unmount(destroy, callback)\n }\n }\n }\n\n public attributeChangedCallback (attr: ObservedAttrName, _oldVal: string, newVal: string): void {\n if (\n this.legalAttribute(attr, newVal) &&\n this[attr === ObservedAttrName.NAME ? 'appName' : 'appUrl'] !== newVal\n ) {\n if (\n attr === ObservedAttrName.URL && (\n !this.appUrl ||\n !this.connectStateMap.get(this.connectedCount) // TODO: 这里的逻辑可否再优化一下\n )\n ) {\n newVal = formatAppURL(newVal, this.appName)\n if (!newVal) {\n return logError(`Invalid attribute url ${newVal}`, this.appName)\n }\n this.appUrl = newVal\n this.handleInitialNameAndUrl()\n } else if (\n attr === ObservedAttrName.NAME && (\n !this.appName ||\n !this.connectStateMap.get(this.connectedCount) // TODO: 这里的逻辑可否再优化一下\n )\n ) {\n const formatNewName = formatAppName(newVal)\n\n if (!formatNewName) {\n return logError(`Invalid attribute name ${newVal}`, this.appName)\n }\n\n // TODO: 当micro-app还未插入文档中就修改name,逻辑可否再优化一下\n if (this.cacheData) {\n microApp.setData(formatNewName, this.cacheData)\n this.cacheData = null\n }\n\n this.appName = formatNewName\n if (formatNewName !== newVal) {\n this.setAttribute('name', this.appName)\n }\n this.handleInitialNameAndUrl()\n } else if (!this.isWaiting) {\n this.isWaiting = true\n defer(this.handleAttributeUpdate)\n }\n }\n }\n\n // handle for connectedCallback run before attributeChangedCallback\n private handleInitialNameAndUrl (): void {\n this.connectStateMap.get(this.connectedCount) && this.handleConnected()\n }\n\n /**\n * first mount of this app\n */\n private handleConnected (): void {\n if (!this.appName || !this.appUrl) return\n\n if (this.getDisposeResult('shadowDOM') && !this.shadowRoot && isFunction(this.attachShadow)) {\n this.attachShadow({ mode: 'open' })\n }\n\n this.updateSsrUrl(this.appUrl)\n\n if (appInstanceMap.has(this.appName)) {\n const oldApp = appInstanceMap.get(this.appName)!\n const oldAppUrl = oldApp.ssrUrl || oldApp.url\n const targetUrl = this.ssrUrl || this.appUrl\n /**\n * NOTE:\n * 1. keep-alive don't care about ssrUrl\n * 2. Even if the keep-alive app is pushed into the background, it is still active and cannot be replaced. Otherwise, it is difficult for developers to troubleshoot in case of conflict and will leave developers at a loss\n * 3. When scopecss, useSandbox of prefetch app different from target app, delete prefetch app and create new one\n */\n if (\n oldApp.isHidden() &&\n oldApp.url === this.appUrl\n ) {\n this.handleShowKeepAliveApp(oldApp)\n } else if (\n oldAppUrl === targetUrl && (\n oldApp.isUnmounted() ||\n (\n oldApp.isPrefetch &&\n this.sameCoreOptions(oldApp)\n )\n )\n ) {\n this.handleMount(oldApp)\n } else if (oldApp.isPrefetch || oldApp.isUnmounted()) {\n if (__DEV__ && this.sameCoreOptions(oldApp)) {\n /**\n * url is different & old app is unmounted or prefetch, create new app to replace old one\n */\n logWarn(`the ${oldApp.isPrefetch ? 'prefetch' : 'unmounted'} app with url: ${oldAppUrl} replaced by a new app with url: ${targetUrl}`, this.appName)\n }\n this.handleCreateApp()\n } else {\n logError(`app name conflict, an app named: ${this.appName} with url: ${oldAppUrl} is running`)\n }\n } else {\n this.handleCreateApp()\n }\n }\n\n /**\n * handle for change of name an url after element init\n */\n private handleAttributeUpdate = (): void => {\n this.isWaiting = false\n const formatAttrName = formatAppName(this.getAttribute('name'))\n const formatAttrUrl = formatAppURL(this.getAttribute('url'), this.appName)\n if (this.legalAttribute('name', formatAttrName) && this.legalAttribute('url', formatAttrUrl)) {\n const oldApp = appInstanceMap.get(formatAttrName)\n /**\n * If oldApp exist & appName is different, determine whether oldApp is running\n */\n if (formatAttrName !== this.appName && oldApp) {\n if (!oldApp.isUnmounted() && !oldApp.isHidden() && !oldApp.isPrefetch) {\n this.setAttribute('name', this.appName)\n return logError(`app name conflict, an app named ${formatAttrName} is running`)\n }\n }\n\n if (formatAttrName !== this.appName || formatAttrUrl !== this.appUrl) {\n if (formatAttrName === this.appName) {\n this.unmount(true, () => {\n this.actionsForAttributeChange(formatAttrName, formatAttrUrl, oldApp)\n })\n } else if (this.getKeepAliveModeResult()) {\n this.handleHiddenKeepAliveApp()\n this.actionsForAttributeChange(formatAttrName, formatAttrUrl, oldApp)\n } else {\n this.unmount(false, () => {\n this.actionsForAttributeChange(formatAttrName, formatAttrUrl, oldApp)\n })\n }\n }\n } else if (formatAttrName !== this.appName) {\n this.setAttribute('name', this.appName)\n }\n }\n\n // remount app or create app if attribute url or name change\n private actionsForAttributeChange (\n formatAttrName: string,\n formatAttrUrl: string,\n oldApp: AppInterface | void,\n ): void {\n /**\n * do not add judgment of formatAttrUrl === this.appUrl\n */\n this.updateSsrUrl(formatAttrUrl)\n\n this.appName = formatAttrName\n this.appUrl = formatAttrUrl\n ;(this.shadowRoot ?? this).innerHTML = ''\n if (formatAttrName !== this.getAttribute('name')) {\n this.setAttribute('name', this.appName)\n }\n\n /**\n * when oldApp not null: this.appName === oldApp.name\n * scene1: if formatAttrName and this.appName are equal: exitApp is the current app, the url must be different, oldApp has been unmounted\n * scene2: if formatAttrName and this.appName are different: oldApp must be prefetch or unmounted, if url is equal, then just mount, if url is different, then create new app to replace oldApp\n * scene3: url is different but ssrUrl is equal\n * scene4: url is equal but ssrUrl is different, if url is equal, name must different\n * scene5: if oldApp is KEEP_ALIVE_HIDDEN, name must different\n */\n if (oldApp) {\n if (oldApp.isHidden()) {\n if (oldApp.url === this.appUrl) {\n this.handleShowKeepAliveApp(oldApp)\n } else {\n // the hidden keep-alive app is still active\n logError(`app name conflict, an app named ${this.appName} is running`)\n }\n /**\n * TODO:\n * 1. oldApp必是unmountApp或preFetchApp,这里还应该考虑沙箱、iframe、样式隔离不一致的情况\n * 2. unmountApp要不要判断样式隔离、沙箱、iframe,然后彻底删除并再次渲染?(包括handleConnected里的处理,先不改?)\n * 推荐:if (\n * oldApp.url === this.appUrl &&\n * oldApp.ssrUrl === this.ssrUrl && (\n * oldApp.isUnmounted() ||\n * (oldApp.isPrefetch && this.sameCoreOptions(oldApp))\n * )\n * )\n */\n } else if (oldApp.url === this.appUrl && oldApp.ssrUrl === this.ssrUrl) {\n // mount app\n this.handleMount(oldApp)\n } else {\n this.handleCreateApp()\n }\n } else {\n this.handleCreateApp()\n }\n }\n\n /**\n * judge the attribute is legal\n * @param name attribute name\n * @param val attribute value\n */\n private legalAttribute (name: string, val: AttrType): boolean {\n if (!isString(val) || !val) {\n logError(`unexpected attribute ${name}, please check again`, this.appName)\n\n return false\n }\n\n return true\n }\n\n // create app instance\n private handleCreateApp (): void {\n const createAppInstance = () => new CreateApp({\n name: this.appName,\n url: this.appUrl,\n container: this.shadowRoot ?? this,\n scopecss: this.useScopecss(),\n useSandbox: this.useSandbox(),\n inline: this.getDisposeResult('inline'),\n iframe: this.getDisposeResult('iframe'),\n ssrUrl: this.ssrUrl,\n routerMode: this.getMemoryRouterMode(),\n })\n\n /**\n * Actions for destroy old app\n * If oldApp exist, it must be 3 scenes:\n * 1. oldApp is unmounted app (url is is different)\n * 2. oldApp is prefetch, not prerender (url, scopecss, useSandbox, iframe is different)\n * 3. oldApp is prerender (url, scopecss, useSandbox, iframe is different)\n */\n const oldApp = appInstanceMap.get(this.appName)\n if (oldApp) {\n if (oldApp.isPrerender) {\n this.unmount(true, createAppInstance)\n } else {\n oldApp.actionsForCompletelyDestroy()\n createAppInstance()\n }\n } else {\n createAppInstance()\n }\n }\n\n /**\n * mount app\n * some serious note before mount:\n * 1. is prefetch ?\n * 2. is remount in another container ?\n * 3. is remount with change properties of the container ?\n */\n private handleMount (app: AppInterface): void {\n app.isPrefetch = false\n /**\n * Fix error when navigate before app.mount by microApp.router.push(...)\n * Issue: https://github.com/micro-zoe/micro-app/issues/908\n */\n app.setAppState(appStates.BEFORE_MOUNT)\n // exec mount async, simulate the first render scene\n defer(() => this.mount(app))\n }\n\n /**\n * public mount action for micro_app_element & create_app\n */\n public mount (app: AppInterface): void {\n app.mount({\n container: this.shadowRoot ?? this,\n inline: this.getDisposeResult('inline'),\n routerMode: this.getMemoryRouterMode(),\n baseroute: this.getBaseRouteCompatible(),\n defaultPage: this.getDefaultPage(),\n disablePatchRequest: this.getDisposeResult('disable-patch-request'),\n fiber: this.getDisposeResult('fiber'),\n })\n }\n\n /**\n * unmount app\n * @param destroy delete cache resources when unmount\n * @param unmountcb callback\n */\n public unmount (destroy?: boolean, unmountcb?: CallableFunction): void {\n const app = appInstanceMap.get(this.appName)\n if (app && !app.isUnmounted()) {\n app.unmount({\n destroy: destroy || this.getDestroyCompatibleResult(),\n clearData: this.getDisposeResult('clear-data'),\n keepRouteState: this.getDisposeResult('keep-router-state'),\n unmountcb,\n })\n }\n }\n\n // hidden app when disconnectedCallback called with keep-alive\n private handleHiddenKeepAliveApp (callback?: CallableFunction): void {\n const app = appInstanceMap.get(this.appName)\n if (app && !app.isUnmounted() && !app.isHidden()) {\n app.hiddenKeepAliveApp(callback)\n }\n }\n\n // show app when connectedCallback called with keep-alive\n private handleShowKeepAliveApp (app: AppInterface): void {\n // must be async\n defer(() => app.showKeepAliveApp(this.shadowRoot ?? this))\n }\n\n /**\n * Get configuration\n * Global setting is lowest priority\n * @param name Configuration item name\n */\n public getDisposeResult <T extends keyof OptionsType> (name: T): boolean {\n return (this.compatibleProperties(name) || !!microApp.options[name]) && this.compatibleDisableProperties(name)\n }\n\n // compatible of disableScopecss & disableSandbox\n private compatibleProperties (name: string): boolean {\n if (name === 'disable-scopecss') {\n return this.hasAttribute('disable-scopecss') || this.hasAttribute('disableScopecss')\n } else if (name === 'disable-sandbox') {\n return this.hasAttribute('disable-sandbox') || this.hasAttribute('disableSandbox')\n }\n return this.hasAttribute(name)\n }\n\n // compatible of disableScopecss & disableSandbox\n private compatibleDisableProperties (name: string): boolean {\n if (name === 'disable-scopecss') {\n return this.getAttribute('disable-scopecss') !== 'false' && this.getAttribute('disableScopecss') !== 'false'\n } else if (name === 'disable-sandbox') {\n return this.getAttribute('disable-sandbox') !== 'false' && this.getAttribute('disableSandbox') !== 'false'\n }\n return this.getAttribute(name) !== 'false'\n }\n\n private useScopecss (): boolean {\n return !(this.getDisposeResult('disable-scopecss') || this.getDisposeResult('shadowDOM'))\n }\n\n private useSandbox (): boolean {\n return !this.getDisposeResult('disable-sandbox')\n }\n\n /**\n * Determine whether the core options of the existApp is consistent with the new one\n */\n private sameCoreOptions (app: AppInterface): boolean {\n return (\n app.scopecss === this.useScopecss() &&\n app.useSandbox === this.useSandbox() &&\n app.iframe === this.getDisposeResult('iframe')\n )\n }\n\n /**\n * 2021-09-08\n * get baseRoute\n * getAttribute('baseurl') is compatible writing of versions below 0.3.1\n */\n private getBaseRouteCompatible (): string {\n return this.getAttribute('baseroute') ?? this.getAttribute('baseurl') ?? ''\n }\n\n // compatible of destroy\n private getDestroyCompatibleResult (): boolean {\n return this.getDisposeResult('destroy') || this.getDisposeResult('destory')\n }\n\n /**\n * destroy has priority over destroy keep-alive\n */\n private getKeepAliveModeResult (): boolean {\n return this.getDisposeResult('keep-alive') && !this.getDestroyCompatibleResult()\n }\n\n /**\n * change ssrUrl in ssr mode\n */\n private updateSsrUrl (baseUrl: string): void {\n if (this.getDisposeResult('ssr')) {\n // TODO: disable-memory-router不存在了,这里需要更新一下\n if (this.getDisposeResult('disable-memory-router') || this.getDisposeResult('disableSandbox')) {\n const rawLocation = globalEnv.rawWindow.location\n this.ssrUrl = CompletionPath(rawLocation.pathname + rawLocation.search, baseUrl)\n } else {\n // get path from browser URL\n let targetPath = getNoHashMicroPathFromURL(this.appName, baseUrl)\n const defaultPagePath = this.getDefaultPage()\n if (!targetPath && defaultPagePath) {\n const targetLocation = createURL(defaultPagePath, baseUrl)\n targetPath = targetLocation.origin + targetLocation.pathname + targetLocation.search\n }\n this.ssrUrl = targetPath\n }\n } else if (this.ssrUrl) {\n this.ssrUrl = ''\n }\n }\n\n /**\n * get config of default page\n */\n private getDefaultPage (): string {\n return (\n router.getDefaultPage(this.appName) ||\n this.getAttribute('default-page') ||\n this.getAttribute('defaultPage') ||\n ''\n )\n }\n\n /**\n * get config of router-mode\n * @returns router-mode\n */\n private getMemoryRouterMode () : string {\n return getRouterMode(this.getAttribute('router-mode'), this)\n }\n\n /**\n * rewrite micro-app.setAttribute, process attr data\n * @param key attr name\n * @param value attr value\n */\n public setAttribute (key: string, value: any): void {\n if (key === 'data') {\n if (isPlainObject(value)) {\n const cloneValue: Record<NormalKey, unknown> = {}\n Object.getOwnPropertyNames(value).forEach((ownKey: NormalKey) => {\n if (!(isString(ownKey) && ownKey.indexOf('__') === 0)) {\n cloneValue[ownKey] = value[ownKey]\n }\n })\n this.data = cloneValue\n } else if (value !== '[object Object]') {\n logWarn('property data must be an object', this.appName)\n }\n } else {\n globalEnv.rawSetAttribute.call(this, key, value)\n }\n }\n\n /**\n * Data from the base application\n */\n set data (value: Record<PropertyKey, unknown> | null) {\n if (this.appName) {\n microApp.setData(this.appName, value as Record<PropertyKey, unknown>)\n } else {\n this.cacheData = value\n }\n }\n\n /**\n * get data only used in jsx-custom-event once\n */\n get data (): Record<PropertyKey, unknown> | null {\n if (this.appName) {\n return microApp.getData(this.appName, true)\n } else if (this.cacheData) {\n return this.cacheData\n }\n return null\n }\n }\n\n globalEnv.rawWindow.customElements.define(tagName, MicroAppElement)\n}\n","import type {\n prefetchParamList,\n prefetchParam,\n globalAssetsType,\n} from '@micro-app/types'\nimport type {\n SourceCenter as SourceCenterType,\n} from './source/source_center'\nimport microApp from './micro_app'\nimport sourceCenter from './source/source_center'\nimport {\n PREFETCH_LEVEL,\n} from './constants'\nimport CreateApp, {\n appInstanceMap,\n} from './create_app'\nimport {\n requestIdleCallback,\n formatAppURL,\n formatAppName,\n promiseStream,\n logError,\n isBrowser,\n isArray,\n isPlainObject,\n isString,\n isFunction,\n promiseRequestIdle,\n isNumber,\n} from './libs/utils'\nimport {\n fetchSource,\n} from './source/fetch'\nimport {\n getRouterMode,\n} from './sandbox/router'\n\n/**\n * preFetch([\n * {\n * name: string,\n * url: string,\n * iframe: boolean,\n * inline: boolean,\n * 'disable-scopecss': boolean,\n * 'disable-sandbox': boolean,\n * level: number,\n * 'default-page': string,\n * 'disable-patch-request': boolean,\n * },\n * ...\n * ])\n * Note:\n * 1: preFetch is async and is performed only when the browser is idle\n * 2: options of prefetch preferably match the config of the micro-app element, although this is not required\n * @param apps micro app options\n * @param delay delay time\n */\nexport default function preFetch (apps: prefetchParamList, delay?: number): void {\n if (!isBrowser) {\n return logError('preFetch is only supported in browser environment')\n }\n\n requestIdleCallback(() => {\n const delayTime = isNumber(delay) ? delay : microApp.options.prefetchDelay\n\n /**\n * TODO: remove setTimeout\n * Is there a better way?\n */\n setTimeout(() => {\n // releasePrefetchEffect()\n preFetchInSerial(apps)\n }, isNumber(delayTime) ? delayTime : 3000)\n })\n\n // const handleOnLoad = (): void => {\n // releasePrefetchEffect()\n // requestIdleCallback(() => {\n // preFetchInSerial(apps)\n // })\n // }\n\n // const releasePrefetchEffect = (): void => {\n // window.removeEventListener('load', handleOnLoad)\n // clearTimeout(preFetchTime)\n // }\n\n // window.addEventListener('load', handleOnLoad)\n}\n\nfunction preFetchInSerial (apps: prefetchParamList): void {\n isFunction(apps) && (apps = apps())\n\n if (isArray(apps)) {\n apps.reduce((pre, next) => pre.then(() => preFetchAction(next)), Promise.resolve())\n }\n}\n\n// sequential preload app\nfunction preFetchAction (options: prefetchParam): Promise<void> {\n return promiseRequestIdle((resolve: PromiseConstructor['resolve']) => {\n if (isPlainObject(options) && navigator.onLine) {\n options.name = formatAppName(options.name)\n options.url = formatAppURL(options.url, options.name)\n if (options.name && options.url && !appInstanceMap.has(options.name)) {\n const app = new CreateApp({\n name: options.name,\n url: options.url,\n isPrefetch: true,\n scopecss: !(options['disable-scopecss'] ?? options.disableScopecss ?? microApp.options['disable-scopecss']),\n useSandbox: !(options['disable-sandbox'] ?? options.disableSandbox ?? microApp.options['disable-sandbox']),\n inline: options.inline ?? microApp.options.inline,\n iframe: options.iframe ?? microApp.options.iframe,\n prefetchLevel: options.level && PREFETCH_LEVEL.includes(options.level) ? options.level : microApp.options.prefetchLevel && PREFETCH_LEVEL.includes(microApp.options.prefetchLevel) ? microApp.options.prefetchLevel : 2,\n })\n\n const oldOnload = app.onLoad\n const oldOnLoadError = app.onLoadError\n app.onLoad = (html: HTMLElement): void => {\n resolve()\n oldOnload.call(\n app,\n html,\n options['default-page'],\n options['disable-patch-request'],\n getRouterMode(options['router-mode']),\n options.baseroute,\n )\n }\n\n app.onLoadError = (...rests): void => {\n resolve()\n oldOnLoadError.call(app, ...rests)\n }\n } else {\n resolve()\n }\n } else {\n resolve()\n }\n })\n}\n\n/**\n * load global assets into cache\n * @param assets global assets of js, css\n */\nexport function getGlobalAssets (assets: globalAssetsType): void {\n if (isPlainObject(assets)) {\n requestIdleCallback(() => {\n fetchGlobalResources(assets.js, 'js', sourceCenter.script)\n fetchGlobalResources(assets.css, 'css', sourceCenter.link)\n })\n }\n}\n\n// TODO: requestIdleCallback for every file\nfunction fetchGlobalResources (resources: string[] | void, suffix: string, sourceHandler: SourceCenterType['link'] | SourceCenterType['script']) {\n if (isArray(resources)) {\n const effectiveResource = resources!.filter((path) => isString(path) && path.includes(`.${suffix}`) && !sourceHandler.hasInfo(path))\n\n const fetchResourcePromise = effectiveResource.map((path) => fetchSource(path))\n\n // fetch resource with stream\n promiseStream<string>(fetchResourcePromise, (res: {data: string, index: number}) => {\n const path = effectiveResource[res.index]\n if (suffix === 'js') {\n if (!sourceHandler.hasInfo(path)) {\n sourceHandler.setInfo(path, {\n code: res.data,\n isExternal: false,\n appSpace: {},\n })\n }\n } else {\n if (!sourceHandler.hasInfo(path)) {\n (sourceHandler as SourceCenterType['link']).setInfo(path, {\n code: res.data,\n appSpace: {}\n })\n }\n }\n }, (err: {error: Error, index: number}) => {\n logError(err)\n })\n }\n}\n","import type {\n OptionsType,\n MicroAppBaseType,\n AppInterface,\n Router,\n AppName,\n Func,\n lifeCyclesType,\n MicroAppConfig,\n GetActiveAppsParam,\n} from '@micro-app/types'\nimport { defineElement } from './micro_app_element'\nimport preFetch, { getGlobalAssets } from './prefetch'\nimport {\n logError,\n logWarn,\n isBrowser,\n isPlainObject,\n formatAppName,\n getRootContainer,\n isString,\n pureCreateElement,\n isElement,\n isFunction,\n} from './libs/utils'\nimport { EventCenterForBaseApp } from './interact'\nimport globalEnv, { initGlobalEnv } from './libs/global_env'\nimport { appInstanceMap } from './create_app'\nimport { lifeCycles } from './constants'\nimport { router } from './sandbox/router'\n\n/**\n * if app not prefetch & not unmount, then app is active\n * @param excludeHiddenApp exclude hidden keep-alive app, default is false\n * @param excludePreRender exclude pre render app\n * @returns active apps\n */\nexport function getActiveApps ({\n excludeHiddenApp = false,\n excludePreRender = false,\n}: GetActiveAppsParam = {}): AppName[] {\n const activeApps: AppName[] = []\n appInstanceMap.forEach((app: AppInterface, appName: AppName) => {\n if (\n !app.isUnmounted() &&\n (\n !app.isPrefetch || (\n app.isPrerender && !excludePreRender\n )\n ) &&\n (\n !excludeHiddenApp ||\n !app.isHidden()\n )\n ) {\n activeApps.push(appName)\n }\n })\n\n return activeApps\n}\n\n// get all registered apps\nexport function getAllApps (): string[] {\n return Array.from(appInstanceMap.keys())\n}\n\ntype unmountAppOptions = {\n destroy?: boolean // destroy app, default is false\n clearAliveState?: boolean // clear keep-alive app state, default is false\n clearData?: boolean // clear data from base app & child app\n}\n\n/**\n * unmount app by appName\n * @param appName\n * @param options unmountAppOptions\n * @returns Promise<void>\n */\nexport function unmountApp (appName: string, options?: unmountAppOptions): Promise<boolean> {\n const app = appInstanceMap.get(formatAppName(appName))\n return new Promise((resolve) => {\n if (app) {\n if (app.isUnmounted() || app.isPrefetch) {\n if (app.isPrerender) {\n app.unmount({\n destroy: !!options?.destroy,\n clearData: !!options?.clearData,\n keepRouteState: false,\n unmountcb: resolve.bind(null, true)\n })\n } else {\n if (options?.destroy) app.actionsForCompletelyDestroy()\n resolve(true)\n }\n } else if (app.isHidden()) {\n if (options?.destroy) {\n app.unmount({\n destroy: true,\n clearData: true,\n keepRouteState: true,\n unmountcb: resolve.bind(null, true)\n })\n } else if (options?.clearAliveState) {\n app.unmount({\n destroy: false,\n clearData: !!options.clearData,\n keepRouteState: true,\n unmountcb: resolve.bind(null, true)\n })\n } else {\n resolve(true)\n }\n } else {\n const container = getRootContainer(app.container!)\n const unmountHandler = () => {\n container.removeEventListener(lifeCycles.UNMOUNT, unmountHandler)\n container.removeEventListener(lifeCycles.AFTERHIDDEN, afterhiddenHandler)\n resolve(true)\n }\n\n const afterhiddenHandler = () => {\n container.removeEventListener(lifeCycles.UNMOUNT, unmountHandler)\n container.removeEventListener(lifeCycles.AFTERHIDDEN, afterhiddenHandler)\n resolve(true)\n }\n\n container.addEventListener(lifeCycles.UNMOUNT, unmountHandler)\n container.addEventListener(lifeCycles.AFTERHIDDEN, afterhiddenHandler)\n\n if (options?.destroy) {\n let destroyAttrValue, destoryAttrValue\n container.hasAttribute('destroy') && (destroyAttrValue = container.getAttribute('destroy'))\n container.hasAttribute('destory') && (destoryAttrValue = container.getAttribute('destory'))\n\n container.setAttribute('destroy', 'true')\n container.parentNode!.removeChild(container)\n\n container.removeAttribute('destroy')\n\n isString(destroyAttrValue) && container.setAttribute('destroy', destroyAttrValue)\n isString(destoryAttrValue) && container.setAttribute('destory', destoryAttrValue)\n } else if (options?.clearAliveState && container.hasAttribute('keep-alive')) {\n const keepAliveAttrValue = container.getAttribute('keep-alive')!\n container.removeAttribute('keep-alive')\n\n let clearDataAttrValue = null\n if (options.clearData) {\n clearDataAttrValue = container.getAttribute('clear-data')\n container.setAttribute('clear-data', 'true')\n }\n\n container.parentNode!.removeChild(container)\n\n container.setAttribute('keep-alive', keepAliveAttrValue)\n isString(clearDataAttrValue) && container.setAttribute('clear-data', clearDataAttrValue)\n } else {\n let clearDataAttrValue = null\n if (options?.clearData) {\n clearDataAttrValue = container.getAttribute('clear-data')\n container.setAttribute('clear-data', 'true')\n }\n\n container.parentNode!.removeChild(container)\n\n isString(clearDataAttrValue) && container.setAttribute('clear-data', clearDataAttrValue)\n }\n }\n } else {\n logWarn(`app ${appName} does not exist`)\n resolve(false)\n }\n })\n}\n\n// unmount all apps in turn\nexport function unmountAllApps (options?: unmountAppOptions): Promise<boolean> {\n return Array.from(appInstanceMap.keys()).reduce((pre, next) => pre.then(() => unmountApp(next, options)), Promise.resolve(true))\n}\n\n/**\n * Re render app from the command line\n * microApp.reload(destroy)\n * @param appName app.name\n * @param destroy unmount app with destroy mode\n * @returns Promise<boolean>\n */\nexport function reload (appName: string, destroy?: boolean): Promise<boolean> {\n return new Promise((resolve) => {\n const app = appInstanceMap.get(formatAppName(appName))\n if (app) {\n const rootContainer = app.container && getRootContainer(app.container)\n if (rootContainer) {\n resolve(rootContainer.reload(destroy))\n } else {\n logWarn(`app ${appName} is not rendered, cannot use reload`)\n resolve(false)\n }\n } else {\n logWarn(`app ${appName} does not exist`)\n resolve(false)\n }\n })\n}\n\ninterface RenderAppOptions extends MicroAppConfig {\n name: string,\n url: string,\n container: string | Element,\n baseroute?: string,\n 'default-page'?: string,\n data?: Record<PropertyKey, unknown>,\n onDataChange?: Func,\n lifeCycles?: lifeCyclesType,\n [key: string]: unknown,\n}\n\n/**\n * Manually render app\n * @param options RenderAppOptions\n * @returns Promise<boolean>\n */\nexport function renderApp (options: RenderAppOptions): Promise<boolean> {\n return new Promise((resolve) => {\n if (!isPlainObject<RenderAppOptions>(options)) return logError('renderApp options must be an object')\n const container: Element | null = isElement(options.container) ? options.container : isString(options.container) ? document.querySelector(options.container) : null\n if (!isElement(container)) return logError('Target container is not a DOM element.')\n\n const microAppElement = pureCreateElement<any>(microApp.tagName)\n\n for (const attr in options) {\n if (attr === 'onDataChange') {\n if (isFunction(options[attr])) {\n microAppElement.addEventListener('datachange', options[attr])\n }\n } else if (attr === 'lifeCycles') {\n const lifeCycleConfig = options[attr]\n if (isPlainObject(lifeCycleConfig)) {\n for (const lifeName in lifeCycleConfig) {\n if (lifeName.toUpperCase() in lifeCycles && isFunction(lifeCycleConfig[lifeName])) {\n microAppElement.addEventListener(lifeName.toLowerCase(), lifeCycleConfig[lifeName])\n }\n }\n }\n } else if (attr !== 'container') {\n microAppElement.setAttribute(attr, options[attr])\n }\n }\n\n const handleMount = () => {\n releaseListener()\n resolve(true)\n }\n\n const handleError = () => {\n releaseListener()\n resolve(false)\n }\n\n const releaseListener = () => {\n microAppElement.removeEventListener(lifeCycles.MOUNTED, handleMount)\n microAppElement.removeEventListener(lifeCycles.ERROR, handleError)\n }\n\n microAppElement.addEventListener(lifeCycles.MOUNTED, handleMount)\n microAppElement.addEventListener(lifeCycles.ERROR, handleError)\n\n container.appendChild(microAppElement)\n })\n}\n\n/**\n * get app state\n * @param appName app.name\n * @returns app.state\n */\nexport function getAppStatus (appName: string): string | void {\n const app = appInstanceMap.get(formatAppName(appName))\n if (app) {\n return app.getLifeCycleState()\n } else {\n logWarn(`app ${appName} does not exist`)\n }\n}\n\nexport class MicroApp extends EventCenterForBaseApp implements MicroAppBaseType {\n tagName = 'micro-app'\n hasInit = false\n options: OptionsType = {}\n router: Router = router\n preFetch = preFetch\n unmountApp = unmountApp\n unmountAllApps = unmountAllApps\n getActiveApps = getActiveApps\n getAllApps = getAllApps\n reload = reload\n renderApp = renderApp\n getAppStatus = getAppStatus\n start (options?: OptionsType): void {\n if (!isBrowser || !window.customElements) {\n return logError('micro-app is not supported in this environment')\n }\n\n /**\n * TODO: 优化代码和逻辑\n * 1、同一个基座中initGlobalEnv不能被多次执行,否则会导致死循环\n * 2、判断逻辑是否放在initGlobalEnv中合适?--- 不合适\n */\n if (this.hasInit) {\n return logError('microApp.start executed repeatedly')\n }\n\n this.hasInit = true\n\n if (options?.tagName) {\n if (/^micro-app(-\\S+)?/.test(options.tagName)) {\n this.tagName = options.tagName\n } else {\n return logError(`${options.tagName} is invalid tagName`)\n }\n }\n\n initGlobalEnv()\n\n if (globalEnv.rawWindow.customElements.get(this.tagName)) {\n return logWarn(`element ${this.tagName} is already defined`)\n }\n\n if (isPlainObject<OptionsType>(options)) {\n this.options = options\n options['disable-scopecss'] = options['disable-scopecss'] ?? options.disableScopecss\n options['disable-sandbox'] = options['disable-sandbox'] ?? options.disableSandbox\n\n // load app assets when browser is idle\n options.preFetchApps && preFetch(options.preFetchApps)\n\n // load global assets when browser is idle\n options.globalAssets && getGlobalAssets(options.globalAssets)\n\n if (isPlainObject(options.plugins)) {\n const modules = options.plugins.modules\n if (isPlainObject(modules)) {\n for (const appName in modules) {\n const formattedAppName = formatAppName(appName)\n if (formattedAppName && appName !== formattedAppName) {\n modules[formattedAppName] = modules[appName]\n delete modules[appName]\n }\n }\n }\n }\n }\n\n // define customElement after init\n defineElement(this.tagName)\n }\n}\n\nconst microApp = new MicroApp()\n\nexport default microApp\n"],"names":["version","isBrowser","window","globalThis","global","self","Function","noopFalse","isArray","Array","assign","Object","rawDefineProperty","defineProperty","rawDefineProperties","defineProperties","rawToString","prototype","toString","rawHasOwnProperty","hasOwnProperty","toTypeString","value","call","isUndefined","target","undefined","isNull","isString","isBoolean","isNumber","isFunction","isPlainObject","isObject","isPromise","isConstructor","targetStr","constructor","getOwnPropertyNames","length","test","isURL","URL","href","isElement","Element","tagName","isNode","Node","nodeType","isLinkElement","isStyleElement","isScriptElement","isMicroAppBody","toUpperCase","logError","msg","appName","rest","appNameTip","console","error","logWarn","warn","defer","fn","args","Promise","resolve","then","bind","createURL","Location","path","base","addProtocol","url","startsWith","location","protocol","formatAppURL","origin","pathname","search","fullPath","replace","e","formatAppName","name","getEffectivePath","pathArr","split","pop","join","CompletionPath","baseURI","promiseStream","promiseList","successCb","errorCb","finallyCb","finishedNum","isFinished","forEach","p","i","res","data","index","catch","err","requestIdleCallback","lastTime","Date","now","setTimeout","didTimeout","timeRemaining","Math","max","promiseRequestIdle","callback","currentMicroAppName","setCurrentAppName","throttleDeferForSetAppName","getCurrentAppName","removeDomScope","pureCreateElement","options","element","rawDocument","document","createElement","__MICRO_APP_NAME__","__PURE_ELEMENT__","cloneContainer","deep","innerHTML","clonedNode","cloneNode","fragment","createDocumentFragment","from","childNodes","node","appendChild","isInvalidQuerySelectorKey","key","isUniqueElement","getRootContainer","ShadowRoot","isShadowRoot","host","trim","str","isFireFox","navigator","userAgent","indexOf","parseQuery","result","queryList","queryItem","eqPos","slice","currentValue","push","stringifyQuery","queryObject","useSetRecord","handlers","Set","add","handler","has","delete","list","getAttributes","attr","attributes","attrMap","Map","set","injectFiberTask","fiberTasks","serialExecFiberTasks","tasks","reduce","pre","next","isInlineScript","address","execMicroAppGlobalHook","hookName","dispatchLifecyclesEvent","lifecycleName","detail","container","event","CustomEvent","currentTarget","get","formatEventInfo","microApp","lifeCycles","dispatchEvent","dispatchCustomEventToMicroApp","app","eventName","sandBox","microAppWindow","fetchSource","fetch","text","HTMLLoader","getInstance","this","instance","run","htmlUrl","ssrUrl","includes","cache","htmlStr","onerror","Error","formatHTML","onLoadError","processHtml","plugins","match","code","mergedPlugins","modules","preCode","plugin","rootSelectorREG","bodySelectorREG","parseError","linkPath","reason","filename","CSSParser","createMatcherForRuleWithChildRule","createMatcherForNoneBraceAtRule","exec","cssText","prefix","matchRules","decodeURIComponent","reset","scopecssDisable","scopecssDisableNextLine","scopecssDisableSelectors","matchLeadingSpaces","matchComments","charAt","matchAtRule","matchStyleRule","selectors","formatSelector","recordResult","styleDeclarations","skip","m","commonMatch","_","separator","selector","matchOpenBrace","matchAllDeclarations","matchCloseBrace","nesting","cssValue","all","$1","getLinkFileDir","keyframesRule","mediaRule","customMediaRule","supportsRule","importRule","charsetRule","namespaceRule","containerRule","documentRule","pageRule","hostRule","fontFaceRule","keyframeRule","r","valList","commonHandlerForAtRuleWithSelfRule","reg","RegExp","matchComment","commentText","rule","matchArray","matchStr","strFragment","encodeURIComponent","commonAction","styleElement","__MICRO_APP_HAS_SCOPED__","parser","textContent","scopedCSS","scopecss","createPrefix","observer","MutationObserver","disconnect","hasAttribute","observe","childList","regCharacter","eventHandler","srcElement","dispatchOnLoadEvent","onload","dispatchOnErrorEvent","ObservedAttrName","appStates","microGlobalEvent","keepAliveStates","MicroAppConfig","linkList","scriptList","createSourceHandler","targetList","setInfo","info","getInfo","hasInfo","deleteInfo","link","script","deleteInlineInfo","addressList","createSourceCenter","extractLinkFromHtml","parent","isDynamic","rel","getAttribute","replaceComment","linkInfo","sourceCenter","appSpaceData","attrs","appSpace","source","links","createComment","placeholder","removeChild","globalEnv","rawSetAttribute","replaceChild","fetchLinksFromHtml","wrapElement","microAppHead","fiberStyleResult","styleList","fetchLinkPromise","map","fiberLinkTasks","convertStyle","handleConvertStyle","parentNode","fetchLinkSuccess","onLoad","parsedCode","existParsedCode","item","getExistParseCode","setConvertStyleAttr","PREFETCH_LEVEL","DEFAULT_ROUTER_MODE","ROUTER_MODE_CUSTOM","ROUTER_MODE_LIST","SCOPE_WINDOW_EVENT","SCOPE_WINDOW_ON_EVENT","SCOPE_DOCUMENT_EVENT","SCOPE_DOCUMENT_ON_EVENT","GLOBAL_KEY_TO_WINDOW","RAW_GLOBAL_TARGET","GLOBAL_CACHED_KEY","scriptTypes","isTypeModule","scriptInfo","module","useSandbox","iframe","isInlineMode","inline","isSpecialScript","getEffectWindow","rawWindow","getParsedFunction","currentCode","parsedFunction","getExistParseResult","code2Function","getUniqueNonceSrc","nonceStr","random","substr","isWrapInSandBox","getSandboxType","extractScriptElement","src","checkExcludeUrl","type","checkIgnoreUrl","currentScript","supportModuleScript","noModule","async","pure","isExternal","scripts","getAssetsPlugins","some","excludeChecker","ignoreChecker","fetchScriptsFromHtml","fetchScriptPromise","fetchScriptPromiseInfo","isPrefetch","isPrerender","fiberScriptTasks","fiber","prefetchLevel","bindScope","sandboxType","fetchScriptSuccess","runScript","replaceElement","__MICRO_APP_PROXY_WINDOW__","proxyWindow","setActiveProxyWindow","actionsBeforeRunScript","scriptElement","onloadHandler","moduleCount","convertScript","setConvertScriptAttr","runCode2InlineScript","microBody","querySelector","runParsedFunction","newCode","processCode","usePlugins","configs","config","loader","flatChildren","fiberStyleTasks","children","child","dom","extractSourceDom","wrapDiv","getWrapElement","rawElementQuerySelector","microAppBody","size","eventCenter","temRecordStep","recordStep","queue","shift","eventInfo","eventList","tempData","force","resArr","isEqual","f","callbacks","dispatchDataEvent","nextStepList","nextStep","isLegalName","enqueue","process","oldData","newData","keys","on","autoTrigger","off","clear","clearData","dispatch","getData","createEventName","fromBaseApp","EventCenterForGlobal","addGlobalDataListener","cb","__APP_NAME__","__AUTO_TRIGGER__","removeGlobalDataListener","setGlobalData","forceSetGlobalData","getGlobalData","clearGlobalData","clearGlobalDataListener","EventCenterForBaseApp","addDataListener","removeDataListener","setData","forceSetData","clearDataListener","EventCenterForMicroApp","super","appInstanceMap","forceDispatch","recordDataCenterSnapshot","microAppEventCenter","umdDataListeners","normal","globalEventInfo","subAppEventInfo","rebuildDataCenterSnapshot","resetDataCenterSnapshot","AppManager","getAll","values","unmountNestedApp","releaseUnmountOfNestedApp","disconnectedCallback","__MICRO_APP_UMD_MODE__","__MICRO_APP_ENVIRONMENT__","removeEventListener","isBoundedFunction","__MICRO_APP_IS_BOUND_FUNCTION__","bindFunctionToRawTarget","rawTarget","__MICRO_APP_IS_CONSTRUCTOR__","isConstructorFunction","cacheKey","bindRawObjectValue","configurable","enumerable","writable","patchDocument","sandbox","proxyDocument","documentEffect","eventListenerMap","sstEventListenerMap","onClickHandler","sstOnClickHandler","rawCreateElement","rawAddEventListener","rawRemoveEventListener","addEventListener","listener","listenerList","__MICRO_APP_MARK_OPTIONS__","record","cacheList","rebuild","onclick","release","mergedProxyDocumentProps","builtInProxyProps","customProxyDocumentProps","genProxyDocumentProps","Proxy","Symbol","toStringTag","Reflect","proxyCallback","createProxyDocument","MicroDocument","rawRootDocument","hasInstance","proto","getPrototypeOf","setPrototypeOf","createMicroDocument","Document","patchWindow","filter","getOwnPropertyDescriptor","patchWindowProperty","descriptorTargetMap","scopeProperties","adapter","escapeSetterKeyList","injectedKeys","descriptor","escapeProperties","staticEscapeProperties","escapeKeys","staticScopeProperties","ownKeys","concat","create","deleteProperty","createProxyWindow","intervalIdMap","timeoutIdMap","rawDispatchEvent","rawSetInterval","rawSetTimeout","rawClearInterval","rawClearTimeout","getEventTarget","setInterval","timeout","intervalId","timeoutId","clearInterval","clearTimeout","clearTimer","patchWindowEffect","setMicroState","microState","isRouterModeCustom","rawState","history","state","additionalState","microAppState","getMicroState","ENC_AD_RE","ENC_EQ_RE","DEC_AD_RE","DEC_EQ_RE","encodeMicroPath","commonDecode","decodeMicroPath","decPath","getMicroPathFromURL","rawLocation","getQueryObjectFromURL","hash","microPath","hashQuery","searchQuery","setMicroPathToURL","targetLocation","targetFullPath","isAttach2Hash","encodedMicroPath","baseHash","isEffectiveApp","routerMode","getRouterMode","mode","microAppElement","getDisposeResult","addHistoryListener","popStateHandler","getActiveApps","excludeHiddenApp","excludePreRender","onlyForBrowser","updateMicroLocationWithEvent","isHashChange","oldHref","oldHash","updateMicroLocation","newPopStateEvent","PopStateEvent","isIframeSandbox","onpopstate","dispatchPopStateEventToMicroApp","newHashChangeEvent","HashChangeEvent","newURL","oldURL","onhashchange","dispatchHashChangeEventToMicroApp","dispatchNativeEvent","dispatchNativePopStateEvent","dispatchNativeHashChangeEvent","createMicroHistory","microLocation","rawHistory","getMicroHistoryMethod","methodName","rests","navigateWithNativeEvent","updateIframeBase","nativeHistoryNavigate","pushState","replaceState","title","rawPushState","rawReplaceState","oldFullPath","attachRouteToBrowserURL","reWriteHistoryMethod","method","currentHref","apply","patchHistory","releasePatchHistory","router","executeNavigationGuard","clearRouterWhenUnmount","handleNavigate","to","currentFullPath","navigateWithRawHistory","createNavigationMethod","reject","sandboxReady","createRawHistoryMethod","beforeGuards","afterGuards","runGuards","guards","guard","commonHandlerForAttachToURL","current","encode","decode","go","back","forward","beforeEach","afterEach","attachToURL","attachAllToURL","includeHiddenApp","includePreRender","defaultPageRecord","useMapRecord","setDefaultPage","removeDefaultPage","getDefaultPage","createDefaultPageApi","baseRouterProxy","setBaseAppRouter","baseRouter","getBaseAppRouter","createBaseRouterApi","createRouterApi","escape2RawWindowKeys","escape2RawWindowRegExpKeys","uniqueDocumentElement","hijackMicroLocationKeys","proxy2RawDocOrShadowKeys","proxy2RawDocOrShadowMethods","proxy2RawDocumentKeys","proxy2RawDocumentMethods","locationKeys","guardLocationKeys","createMicroLocation","childStaticLocation","browserHost","childHost","isIframe","withLocation","getTarget","commonHandler","proxyLocation","setMicroPathResult","reload","handleForPathNameAndSearch","targetPath","createLocationMethod","locationMethodName","forcedReload","createGuardLocation","guardLocation","oAssign","newLocation","initRouteStateWithURL","defaultPage","updateBrowserURLWithLocation","autoTriggerNavigationGuard","clearRouteStateFromURL","keepRouteState","removePathFromBrowser","hashQueryStr","Number","Boolean","searchQueryStr","removeMicroPathFromURL","removeMicroState","Adapter","injectReactHMRProperty","patchElementTree","updateElementInfo","rawRootNode","createGetterForIframeParentNode","rawParentNodeDesc","parentNodeDesc","HTMLBuildInNode","getRootElementParentNode","body","createMicroFetch","rawFetch","input","init","createMicroXMLHttpRequest","rawXMLHttpRequest","XMLHttpRequest","open","reqUrl","createMicroEventSource","clearMicroEventSource","eventSourceMap","rawEventSource","EventSource","eventSourceUrl","eventSourceInitDict","eventSourceList","close","useMicroEventSource","WithSandBox","EventTarget","patchWith","getSpecialProperties","patchRouter","windowEffect","initStaticGlobalKeys","start","umdMode","baseroute","disablePatchRequest","active","initRouteState","removeHistoryListener","__MICRO_APP_BASE_ROUTE__","__MICRO_APP_BASE_URL__","initGlobalKeysWhenStart","__MICRO_APP_URL__","activeSandbox","patchElementAndDocument","activeCount","_babelPolyfill","stop","destroy","recordAndReleaseEffect","clearRouteState","releasePatchElementAndDocument","__MICRO_APP_PUBLIC_PATH__","__MICRO_APP_WINDOW__","__MICRO_APP_PRE_RENDER__","__MICRO_APP_SANDBOX__","__MICRO_APP_SANDBOX_TYPE__","setMappingPropertiesWithRawDescriptor","preventRecord","resetEffectSnapshot","recordEffectSnapshot","releaseGlobalEffect","rebuildEffectSnapshot","keepAlive","commonActionForSpecialProperties","setPreRenderState","markUmdMode","topValue","parentValue","top","createDescriptorForMicroAppWindow","setHijackProperty","patchRequestApi","setScopeProperties","modifiedEval","modifiedImage","eval","Image","ImageProxy","microFetch","microXMLHttpRequest","microEventSource","microHistory","createMicroRouter","setRouteInfoForKeepAliveApp","removeRouteInfoForKeepAliveApp","patchStaticElement","actionBeforeExecScripts","setStaticAppState","__MICRO_APP_STATE__","customProperties","microRootDocument","microDocument","rawMicroCreateElement","rawMicroCreateTextNode","createTextNode","rawMicroCreateComment","rawMicroQuerySelector","rawMicroQuerySelectorAll","querySelectorAll","rawMicroGetElementById","getElementById","rawMicroGetElementsByClassName","getElementsByClassName","rawMicroGetElementsByTagName","getElementsByTagName","rawMicroGetElementsByName","getElementsByName","rawMicroElementFromPoint","elementFromPoint","rawMicroCaretRangeFromPoint","caretRangeFromPoint","getDefaultRawTarget","_this","x","y","range","patchDocumentPrototype","getCommonDescriptor","getter","createDescriptors","documentElement","scrollingElement","desc","patchDocumentProperty","bindTarget","createSetterHandler","__MICRO_APP_BOUND_FUNCTION__","patchDocumentEffect","patchElement","rawRootElement","microRootNode","microRootElement","rawMicroAppendChild","rawMicroInsertBefore","insertBefore","rawMicroReplaceChild","rawMicroRemoveChild","rawMicroAppend","append","rawMicroPrepend","prepend","rawMicroInsertAdjacentElement","insertAdjacentElement","rawMicroCloneNode","rawInnerHTMLDesc","rawOwnerDocumentDesc","isPureNode","isBaseElement","getRawTarget","microHead","head","getRootNode","oldChild","contains","nodes","hasPureNode","where","construct","Target","elementImage","patchIframeNode","rawMicroSetAttribute","setAttribute","protoAttrList","HTMLImageElement","HTMLScriptElement","HTMLLinkElement","patchIframeAttribute","IframeSandbox","baseElement","deleteIframeElement","createIframeElement","contentWindow","patchIframe","createIframeTemplate","childFullPath","iframeAttrs","style","id","createIframeBase","oldMicroDocument","iframeLocationReady","$dom","firstChild","clearDOM","html","CreateApp","CREATED","getInlineModeState","loadSourceCode","createSandbox","setAppState","LOADING","loadSourceLevel","isUnmounted","mount","LOAD_FAILED","appState","BEFORE_MOUNT","nextAction","preRenderEvents","dispatchBeforeMount","setLifeCycleState","BEFOREMOUNT","MOUNTING","handleMounted","umdHookMount","initHook","deferScriptPromise","deferScriptInfo","errorCount","execScripts","unmount","getUmdLibraryHooks","umdHookUnmount","umdHookMountResult","dispatchAction","dispatchMountedEvent","MOUNTED","getMicroAppGlobalHook","ONMOUNT","isHidden","unmountcb","UNMOUNT","umdHookUnmountResult","ONUNMOUNT","handleUnmounted","actionsForUnmount","clearOptions","setKeepAliveState","actionsForCompletelyDestroy","hiddenKeepAliveApp","KEEP_ALIVE_HIDDEN","AFTERHIDDEN","showKeepAliveApp","BEFORESHOW","KEEP_ALIVE_SHOW","AFTERSHOW","ERROR","getAppState","lifeCycleState","getLifeCycleState","keepAliveState","getKeepAliveState","libraryName","rawElementQuerySelectorAll","dynamicElementInMicroAppMap","WeakMap","getMappingNode","handleNewNode","linkReplaceComment","excludeAssetFilter","replaceStyle","originLink","handleDynamicLink","formatDynamicLink","originScript","dispatchScriptOnLoadEvent","runDynamicScript","runDynamicRemoteScript","runDynamicInlineScript","invokePrototypeMethod","rawMethod","targetChild","passiveChild","hijackParent","getHijackParent","rawRemoveChild","__MICRO_APP_HAS_DPN__","rawAppendChild","invokeRawMethod","rawAppend","rawPrepend","commonElementHandler","newChild","currentAppName","completePathDynamic","getBindTarget","isProxyDocument","rawQuerySelector","rawQuerySelectorAll","markElement","createElementNS","namespaceURI","rawCreateElementNS","rawCreateDocumentFragment","rawCreateComment","rawGetElementById","rawGetElementsByClassName","rawGetElementsByTagName","rawGetElementsByName","getQueryTarget","refChild","rawInsertBefore","rawReplaceChild","rawCreateTextNode","processedEle","realParent","rawInsertAdjacentElement","rawCloneNode","firstElementChild","releasePatchDocument","hasRejectMicroAppStyle","initGlobalEnv","rawRootEventTarget","__MICRO_APP_BASE_APPLICATION__","rejectMicroAppStyle","defineElement","MicroAppElement","HTMLElement","getBaseHTMLElement","isWaiting","formatAttrName","formatAttrUrl","legalAttribute","oldApp","appUrl","actionsForAttributeChange","getKeepAliveModeResult","handleHiddenKeepAliveApp","observedAttributes","connectedCallback","cacheCount","connectedCount","connectStateMap","effectiveApp","handleConnected","handleDisconnected","handleAfterReload","attributeChangedCallback","_oldVal","newVal","NAME","handleAttributeUpdate","formatNewName","cacheData","handleInitialNameAndUrl","shadowRoot","attachShadow","updateSsrUrl","oldAppUrl","targetUrl","handleShowKeepAliveApp","sameCoreOptions","handleMount","handleCreateApp","val","createAppInstance","useScopecss","getMemoryRouterMode","getBaseRouteCompatible","getDestroyCompatibleResult","compatibleProperties","compatibleDisableProperties","baseUrl","formatLocation","getNoHashMicroPathFromURL","defaultPagePath","cloneValue","ownKey","customElements","define","preFetch","apps","delay","delayTime","prefetchDelay","preFetchAction","onLine","disableScopecss","disableSandbox","level","oldOnload","oldOnLoadError","preFetchInSerial","fetchGlobalResources","resources","suffix","sourceHandler","effectiveResource","activeApps","getAllApps","unmountApp","clearAliveState","unmountHandler","afterhiddenHandler","destroyAttrValue","destoryAttrValue","removeAttribute","keepAliveAttrValue","clearDataAttrValue","unmountAllApps","rootContainer","renderApp","lifeCycleConfig","lifeName","toLowerCase","releaseListener","handleError","getAppStatus","MicroApp","assets","hasInit","preFetchApps","globalAssets","js","css","formattedAppName"],"mappings":"sPAWaA,EAAU,aAGVC,EAA8B,oBAAXC,OAGnBC,EAAgC,oB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oB18B,EAAQhL,UAC7BgL,EAAQhL,KAQzBshC,GAAcv3B,KAAK1K,gBAIjB6J,GAAW,IAAIi+B"}
1
+ {"version":3,"file":"index.umd.js","sources":["../src/libs/utils.ts","../src/interact/lifecycles_event.ts","../src/source/fetch.ts","../src/source/loader/html.ts","../src/sandbox/scoped_css.ts","../src/source/load_event.ts","../src/constants.ts","../src/source/source_center.ts","../src/source/links.ts","../src/source/scripts.ts","../src/source/index.ts","../src/interact/index.ts","../src/interact/event_center.ts","../src/app_manager.ts","../src/libs/nest_app.ts","../src/sandbox/bind_function.ts","../src/sandbox/with/document.ts","../src/sandbox/with/window.ts","../src/sandbox/router/core.ts","../src/sandbox/router/event.ts","../src/sandbox/router/history.ts","../src/sandbox/router/api.ts","../src/sandbox/iframe/special_key.ts","../src/sandbox/router/location.ts","../src/sandbox/router/index.ts","../src/sandbox/adapter.ts","../src/sandbox/request.ts","../src/sandbox/with/index.ts","../src/sandbox/iframe/window.ts","../src/sandbox/iframe/document.ts","../src/sandbox/iframe/element.ts","../src/sandbox/iframe/index.ts","../src/sandbox/iframe/router.ts","../src/create_app.ts","../src/source/patch.ts","../src/libs/global_env.ts","../src/micro_app_element.ts","../src/prefetch.ts","../src/micro_app.ts"],"sourcesContent":["/* eslint-disable no-new-func, indent, no-self-compare, @typescript-eslint/explicit-module-boundary-types */\nimport type {\n Func,\n LocationQueryObject,\n LocationQueryValue,\n MicroLocation,\n AttrsType,\n fiberTasks,\n MicroAppElementTagNameMap,\n} from '@micro-app/types'\n\nexport const version = '__MICRO_APP_VERSION__'\n\n// do not use isUndefined\nexport const isBrowser = typeof window !== 'undefined'\n\n// do not use isUndefined\nexport const globalThis = (typeof global !== 'undefined')\n ? global\n : (\n (typeof window !== 'undefined')\n ? window\n : (\n (typeof self !== 'undefined') ? self : Function('return this')()\n )\n )\n\nexport const noop = () => {}\nexport const noopFalse = () => false\n\n// Array.isArray\nexport const isArray = Array.isArray\n// Object.assign\nexport const assign = Object.assign\n\n// Object prototype methods\nexport const rawDefineProperty = Object.defineProperty\nexport const rawDefineProperties = Object.defineProperties\nexport const rawToString = Object.prototype.toString\nexport const rawHasOwnProperty = Object.prototype.hasOwnProperty\n\nexport const toTypeString = (value: unknown): string => rawToString.call(value)\n\n// is Undefined\nexport function isUndefined (target: unknown): target is undefined {\n return target === undefined\n}\n\n// is Null\nexport function isNull (target: unknown): target is null {\n return target === null\n}\n\n// is String\nexport function isString (target: unknown): target is string {\n return typeof target === 'string'\n}\n\n// is Boolean\nexport function isBoolean (target: unknown): target is boolean {\n return typeof target === 'boolean'\n}\n\n// is Number\nexport function isNumber (target: unknown): target is Number {\n return typeof target === 'number'\n}\n\n// is function\nexport function isFunction (target: unknown): target is Function {\n return typeof target === 'function'\n}\n\n// is PlainObject\nexport function isPlainObject <T = Record<PropertyKey, unknown>> (target: unknown): target is T {\n return toTypeString(target) === '[object Object]'\n}\n\n// is Object\nexport function isObject (target: unknown): target is Object {\n return !isNull(target) && typeof target === 'object'\n}\n\n// is Promise\nexport function isPromise (target: unknown): target is Promise<unknown> {\n return toTypeString(target) === '[object Promise]'\n}\n\n// is bind function\nexport function isBoundFunction (target: unknown): boolean {\n return isFunction(target) && target.name.indexOf('bound ') === 0 && !target.hasOwnProperty('prototype')\n}\n\n// is constructor function\nexport function isConstructor (target: unknown): boolean {\n if (isFunction(target)) {\n const targetStr = target.toString()\n return (\n target.prototype?.constructor === target &&\n Object.getOwnPropertyNames(target.prototype).length > 1\n ) ||\n /^function\\s+[A-Z]/.test(targetStr) ||\n /^class\\s+/.test(targetStr)\n }\n return false\n}\n\n// is ShadowRoot\nexport function isShadowRoot (target: unknown): target is ShadowRoot {\n return typeof ShadowRoot !== 'undefined' && target instanceof ShadowRoot\n}\n\nexport function isURL (target: unknown): target is URL {\n return target instanceof URL || !!(target as URL)?.href\n}\n\n// iframe element not instanceof base app Element, use tagName instead\nexport function isElement (target: unknown): target is Element {\n return target instanceof Element || isString((target as Element)?.tagName)\n}\n\n// iframe node not instanceof base app Node, use nodeType instead\nexport function isNode (target: unknown): target is Node {\n return target instanceof Node || isNumber((target as Node)?.nodeType)\n}\n\nexport function isLinkElement (target: unknown): target is HTMLLinkElement {\n return toTypeString(target) === '[object HTMLLinkElement]'\n}\n\nexport function isStyleElement (target: unknown): target is HTMLStyleElement {\n return toTypeString(target) === '[object HTMLStyleElement]'\n}\n\nexport function isScriptElement (target: unknown): target is HTMLScriptElement {\n return toTypeString(target) === '[object HTMLScriptElement]'\n}\n\nexport function isIFrameElement (target: unknown): target is HTMLIFrameElement {\n return toTypeString(target) === '[object HTMLIFrameElement]'\n}\n\nexport function isDivElement (target: unknown): target is HTMLDivElement {\n return toTypeString(target) === '[object HTMLDivElement]'\n}\n\nexport function isImageElement (target: unknown): target is HTMLImageElement {\n return toTypeString(target) === '[object HTMLImageElement]'\n}\n\nexport function isBaseElement (target: unknown): target is HTMLBaseElement {\n return toTypeString(target) === '[object HTMLBaseElement]'\n}\n\nexport function isMicroAppBody (target: unknown): target is HTMLElement {\n return isElement(target) && target.tagName.toUpperCase() === 'MICRO-APP-BODY'\n}\n\n// is ProxyDocument\nexport function isProxyDocument (target: unknown): target is Document {\n return toTypeString(target) === '[object ProxyDocument]'\n}\n\nexport function includes (target: unknown[], searchElement: unknown, fromIndex?: number): boolean {\n if (target == null) {\n throw new TypeError('includes target is null or undefined')\n }\n\n const O = Object(target)\n const len = parseInt(O.length, 10) || 0\n if (len === 0) return false\n // @ts-ignore\n fromIndex = parseInt(fromIndex, 10) || 0\n let i = Math.max(fromIndex >= 0 ? fromIndex : len + fromIndex, 0)\n while (i < len) {\n // NaN !== NaN\n if (searchElement === O[i] || (searchElement !== searchElement && O[i] !== O[i])) {\n return true\n }\n i++\n }\n return false\n}\n\n/**\n * format error log\n * @param msg message\n * @param appName app name, default is null\n */\nexport function logError (\n msg: unknown,\n appName: string | null = null,\n ...rest: unknown[]\n): void {\n const appNameTip = appName && isString(appName) ? ` app ${appName}:` : ''\n if (isString(msg)) {\n console.error(`[micro-app]${appNameTip} ${msg}`, ...rest)\n } else {\n console.error(`[micro-app]${appNameTip}`, msg, ...rest)\n }\n}\n\n/**\n * format warn log\n * @param msg message\n * @param appName app name, default is null\n */\nexport function logWarn (\n msg: unknown,\n appName: string | null = null,\n ...rest: unknown[]\n): void {\n const appNameTip = appName && isString(appName) ? ` app ${appName}:` : ''\n if (isString(msg)) {\n console.warn(`[micro-app]${appNameTip} ${msg}`, ...rest)\n } else {\n console.warn(`[micro-app]${appNameTip}`, msg, ...rest)\n }\n}\n\n/**\n * async execution\n * @param fn callback\n * @param args params\n */\nexport function defer (fn: Func, ...args: unknown[]): void {\n Promise.resolve().then(fn.bind(null, ...args))\n}\n\n/**\n * create URL as MicroLocation\n */\nexport const createURL = (function (): (path: string | URL, base?: string) => MicroLocation {\n class Location extends URL {}\n return (path: string | URL, base?: string): MicroLocation => {\n return (base ? new Location('' + path, base) : new Location('' + path)) as MicroLocation\n }\n})()\n\n/**\n * Add address protocol\n * @param url address\n */\nexport function addProtocol (url: string): string {\n return url.startsWith('//') ? `${globalThis.location.protocol}${url}` : url\n}\n\n/**\n * format URL address\n * note the scenes:\n * 1. micro-app -> attributeChangedCallback\n * 2. preFetch\n */\nexport function formatAppURL (url: string | null, appName: string | null = null): string {\n if (!isString(url) || !url) return ''\n\n try {\n const { origin, pathname, search } = createURL(addProtocol(url), (window.rawWindow || window).location.href)\n // If it ends with .html/.node/.php/.net/.etc, don’t need to add /\n if (/\\.(\\w+)$/.test(pathname)) {\n return `${origin}${pathname}${search}`\n }\n const fullPath = `${origin}${pathname}/`.replace(/\\/\\/$/, '/')\n return /^https?:\\/\\//.test(fullPath) ? `${fullPath}${search}` : ''\n } catch (e) {\n logError(e, appName)\n return ''\n }\n}\n\n/**\n * format name\n * note the scenes:\n * 1. micro-app -> attributeChangedCallback\n * 2. event_center -> EventCenterForMicroApp -> constructor\n * 3. event_center -> EventCenterForBaseApp -> all methods\n * 4. preFetch\n * 5. plugins\n * 6. router api (push, replace)\n */\nexport function formatAppName (name: string | null): string {\n if (!isString(name) || !name) return ''\n return name.replace(/(^\\d+)|([^\\w\\d-_])/gi, '')\n}\n\n/**\n * Get valid address, such as https://xxx/xx/xx.html to https://xxx/xx/\n * @param url app.url\n */\nexport function getEffectivePath (url: string): string {\n const { origin, pathname } = createURL(url)\n if (/\\.(\\w+)$/.test(pathname)) {\n const fullPath = `${origin}${pathname}`\n const pathArr = fullPath.split('/')\n pathArr.pop()\n return pathArr.join('/') + '/'\n }\n\n return `${origin}${pathname}/`.replace(/\\/\\/$/, '/')\n}\n\n/**\n * Complete address\n * @param path address\n * @param baseURI base url(app.url)\n */\nexport function CompletionPath (path: string, baseURI: string): string {\n if (\n !path ||\n /^((((ht|f)tps?)|file):)?\\/\\//.test(path) ||\n /^(data|blob):/.test(path)\n ) return path\n\n return createURL(path, getEffectivePath(addProtocol(baseURI))).toString()\n}\n\n/**\n * Get the folder where the link resource is located,\n * which is used to complete the relative address in the css\n * @param linkPath full link address\n */\nexport function getLinkFileDir (linkPath: string): string {\n const pathArr = linkPath.split('/')\n pathArr.pop()\n return addProtocol(pathArr.join('/') + '/')\n}\n\n/**\n * promise stream\n * @param promiseList promise list\n * @param successCb success callback\n * @param errorCb failed callback\n * @param finallyCb finally callback\n */\nexport function promiseStream <T> (\n promiseList: Array<Promise<T> | T>,\n successCb: CallableFunction,\n errorCb: CallableFunction,\n finallyCb?: CallableFunction,\n): void {\n let finishedNum = 0\n\n function isFinished () {\n if (++finishedNum === promiseList.length && finallyCb) finallyCb()\n }\n\n promiseList.forEach((p, i) => {\n if (isPromise(p)) {\n (p as Promise<T>).then((res: T) => {\n successCb({ data: res, index: i })\n isFinished()\n }).catch((err: Error) => {\n errorCb({ error: err, index: i })\n isFinished()\n })\n } else {\n successCb({ data: p, index: i })\n isFinished()\n }\n })\n}\n\n// Check whether the browser supports module script\nexport function isSupportModuleScript (): boolean {\n const s = document.createElement('script')\n return 'noModule' in s\n}\n\n// Create a random symbol string\nexport function createNonceSrc (): string {\n return 'inline-' + Math.random().toString(36).substr(2, 15)\n}\n\n// Array deduplication\nexport function unique (array: any[]): any[] {\n return array.filter(function (this: Record<PropertyKey, boolean>, item) {\n return item in this ? false : (this[item] = true)\n }, Object.create(null))\n}\n\n// requestIdleCallback polyfill\nexport const requestIdleCallback = globalThis.requestIdleCallback ||\n function (fn: CallableFunction) {\n const lastTime = Date.now()\n return setTimeout(function () {\n fn({\n didTimeout: false,\n timeRemaining () {\n return Math.max(0, 50 - (Date.now() - lastTime))\n },\n })\n }, 1)\n }\n\n/**\n * Wrap requestIdleCallback with promise\n * Exec callback when browser idle\n */\nexport function promiseRequestIdle (callback: CallableFunction): Promise<void> {\n return new Promise((resolve) => {\n requestIdleCallback(() => {\n callback(resolve)\n })\n })\n}\n\n/**\n * Record the currently running app.name\n */\nlet currentMicroAppName: string | null = null\nexport function setCurrentAppName (appName: string | null): void {\n currentMicroAppName = appName\n}\n\n// get the currently running app.name\nexport function getCurrentAppName (): string | null {\n return currentMicroAppName\n}\n\n// Clear appName\nlet preventSetAppName = false\nexport function removeDomScope (force?: boolean): void {\n setCurrentAppName(null)\n if (force && !preventSetAppName) {\n preventSetAppName = true\n defer(() => {\n preventSetAppName = false\n })\n }\n}\n\nexport function throttleDeferForSetAppName (appName: string) {\n if (currentMicroAppName !== appName && !preventSetAppName) {\n setCurrentAppName(appName)\n defer(() => {\n setCurrentAppName(null)\n })\n }\n}\n\n// is safari browser\nexport function isSafari (): boolean {\n return /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)\n}\n\n/**\n * Create pure elements\n */\nexport function pureCreateElement<K extends keyof MicroAppElementTagNameMap> (tagName: K, options?: ElementCreationOptions): MicroAppElementTagNameMap[K] {\n const element = (window.rawDocument || document).createElement(tagName, options)\n if (element.__MICRO_APP_NAME__) delete element.__MICRO_APP_NAME__\n element.__PURE_ELEMENT__ = true\n return element\n}\n\n// is invalid key of querySelector\nexport function isInvalidQuerySelectorKey (key: string): boolean {\n if (__TEST__) return !key || /(^\\d)|([^\\w\\d-_$])/gi.test(key)\n return !key || /(^\\d)|([^\\w\\d-_\\u4e00-\\u9fa5])/gi.test(key)\n}\n\n// unique element\nexport function isUniqueElement (key: string): boolean {\n return (\n /^body$/i.test(key) ||\n /^head$/i.test(key) ||\n /^html$/i.test(key) ||\n /^title$/i.test(key) ||\n /^:root$/i.test(key)\n )\n}\n\n/**\n * get micro-app element\n * @param target app container\n */\nexport function getRootContainer (target: HTMLElement | ShadowRoot): HTMLElement {\n return (isShadowRoot(target) ? (target as ShadowRoot).host : target) as HTMLElement\n}\n\n/**\n * trim start & end\n */\nexport function trim (str: string): string {\n return str ? str.replace(/^\\s+|\\s+$/g, '') : ''\n}\n\nexport function isFireFox (): boolean {\n return navigator.userAgent.indexOf('Firefox') > -1\n}\n\n/**\n * Transforms a queryString into object.\n * @param search - search string to parse\n * @returns a query object\n */\nexport function parseQuery (search: string): LocationQueryObject {\n const result: LocationQueryObject = {}\n const queryList = search.split('&')\n\n // we will not decode the key/value to ensure that the values are consistent when update URL\n for (const queryItem of queryList) {\n const eqPos = queryItem.indexOf('=')\n const key = eqPos < 0 ? queryItem : queryItem.slice(0, eqPos)\n const value = eqPos < 0 ? null : queryItem.slice(eqPos + 1)\n\n if (key in result) {\n let currentValue = result[key]\n if (!isArray(currentValue)) {\n currentValue = result[key] = [currentValue]\n }\n currentValue.push(value)\n } else {\n result[key] = value\n }\n }\n\n return result\n}\n\n/**\n * Transforms an object to query string\n * @param queryObject - query object to stringify\n * @returns query string without the leading `?`\n */\nexport function stringifyQuery (queryObject: LocationQueryObject): string {\n let result = ''\n\n for (const key in queryObject) {\n const value = queryObject[key]\n if (isNull(value)) {\n result += (result.length ? '&' : '') + key\n } else {\n const valueList: LocationQueryValue[] = isArray(value) ? value : [value]\n\n valueList.forEach(value => {\n if (!isUndefined(value)) {\n result += (result.length ? '&' : '') + key\n if (!isNull(value)) result += '=' + value\n }\n })\n }\n }\n\n return result\n}\n\n/**\n * Register or unregister callback/guard with Set\n */\nexport function useSetRecord<T> () {\n const handlers: Set<T> = new Set()\n\n function add (handler: T): () => boolean {\n handlers.add(handler)\n return (): boolean => {\n if (handlers.has(handler)) return handlers.delete(handler)\n return false\n }\n }\n\n return {\n add,\n list: () => handlers,\n }\n}\n\n/**\n * record data with Map\n */\nexport function useMapRecord<T> () {\n const data: Map<PropertyKey, T> = new Map()\n\n function add (key: PropertyKey, value: T): () => boolean {\n data.set(key, value)\n return (): boolean => {\n if (data.has(key)) return data.delete(key)\n return false\n }\n }\n\n return {\n add,\n get: (key: PropertyKey) => data.get(key),\n delete: (key: PropertyKey): boolean => {\n if (data.has(key)) return data.delete(key)\n return false\n }\n }\n}\n\nexport function getAttributes (element: Element): AttrsType {\n const attr = element.attributes\n const attrMap: AttrsType = new Map()\n for (let i = 0; i < attr.length; i++) {\n attrMap.set(attr[i].name, attr[i].value)\n }\n return attrMap\n}\n\n/**\n * if fiberTasks exist, wrap callback with promiseRequestIdle\n * if not, execute callback\n * @param fiberTasks fiber task list\n * @param callback action callback\n */\nexport function injectFiberTask (fiberTasks: fiberTasks, callback: CallableFunction): void {\n if (fiberTasks) {\n fiberTasks.push(() => promiseRequestIdle((resolve: PromiseConstructor['resolve']) => {\n callback()\n resolve()\n }))\n } else {\n callback()\n }\n}\n\n/**\n * serial exec fiber task of link, style, script\n * @param tasks task array or null\n */\nexport function serialExecFiberTasks (tasks: fiberTasks): Promise<void> | null {\n return tasks?.reduce((pre, next) => pre.then(next), Promise.resolve()) || null\n}\n\n/**\n * inline script start with inline-xxx\n * @param address source address\n */\nexport function isInlineScript (address: string): boolean {\n return address.startsWith('inline-')\n}\n\n/**\n * call function with try catch\n * @param fn target function\n * @param appName app.name\n * @param args arguments\n */\nexport function execMicroAppGlobalHook (\n fn: Func | null,\n appName: string,\n hookName: string,\n ...args: unknown[]\n): void {\n try {\n isFunction(fn) && fn(...args)\n } catch (e) {\n logError(`An error occurred in app ${appName} window.${hookName} \\n`, null, e)\n }\n}\n\n/**\n * remove all childNode from target node\n * @param $dom target node\n */\nexport function clearDOM ($dom: HTMLElement | ShadowRoot | Document): void {\n while ($dom?.firstChild) {\n $dom.removeChild($dom.firstChild)\n }\n}\n\ntype BaseHTMLElementType = HTMLElement & {\n new (): HTMLElement;\n prototype: HTMLElement;\n}\n\n/**\n * get HTMLElement from base app\n * @returns HTMLElement\n */\nexport function getBaseHTMLElement (): BaseHTMLElementType {\n return (window.rawWindow?.HTMLElement || window.HTMLElement) as BaseHTMLElementType\n}\n","import type { lifeCyclesType, AppInterface } from '@micro-app/types'\nimport microApp from '../micro_app'\nimport { logError, isFunction, removeDomScope, getRootContainer, assign } from '../libs/utils'\n\nfunction formatEventInfo (event: CustomEvent, element: HTMLElement): void {\n Object.defineProperties(event, {\n currentTarget: {\n get () {\n return element\n }\n },\n target: {\n get () {\n return element\n }\n },\n })\n}\n\ntype LifecycleEventName = keyof lifeCyclesType\n\n/**\n * dispatch lifeCycles event to base app\n * created, beforemount, mounted, unmount, error\n * @param element container\n * @param appName app.name\n * @param lifecycleName lifeCycle name\n * @param error param from error hook\n */\nexport default function dispatchLifecyclesEvent (\n element: HTMLElement | ShadowRoot,\n appName: string,\n lifecycleName: LifecycleEventName,\n error?: Error,\n): void {\n if (!element) {\n return logError(`element does not exist in lifecycle ${lifecycleName}`, appName)\n }\n\n element = getRootContainer(element)\n\n // clear dom scope before dispatch lifeCycles event to base app, especially mounted & unmount\n removeDomScope()\n\n const detail = assign({\n name: appName,\n container: element,\n }, error && {\n error\n })\n\n const event = new CustomEvent(lifecycleName, {\n detail,\n })\n\n formatEventInfo(event, element)\n // global hooks\n if (isFunction(microApp.options.lifeCycles?.[lifecycleName])) {\n microApp.options.lifeCycles![lifecycleName]!(event)\n }\n\n element.dispatchEvent(event)\n}\n\n/**\n * Dispatch custom event to micro app\n * @param app app\n * @param eventName event name ['unmount', 'appstate-change']\n * @param detail event detail\n */\nexport function dispatchCustomEventToMicroApp (\n app: AppInterface,\n eventName: string,\n detail: Record<string, any> = {},\n): void {\n const event = new CustomEvent(eventName, {\n detail,\n })\n\n app.sandBox?.microAppWindow.dispatchEvent(event)\n}\n","import { isFunction, removeDomScope } from '../libs/utils'\nimport microApp from '../micro_app'\n\n/**\n * fetch source of html, js, css\n * @param url source path\n * @param appName app name\n * @param config fetch options\n */\nexport function fetchSource (url: string, appName: string | null = null, options = {}): Promise<string> {\n /**\n * When child navigate to new async page, click event will scope dom to child and then fetch new source\n * this may cause error when fetch rewrite by baseApp\n * e.g.\n * baseApp: <script crossorigin src=\"https://sgm-static.jd.com/sgm-2.8.0.js\" name=\"SGMH5\" sid=\"6f88a6e4ba4b4ae5acef2ec22c075085\" appKey=\"jdb-adminb2b-pc\"></script>\n */\n removeDomScope()\n if (isFunction(microApp.options.fetch)) {\n return microApp.options.fetch(url, options, appName)\n }\n // Don’t use globalEnv.rawWindow.fetch, will cause sgm-2.8.0.js throw error in nest app\n return window.fetch(url, options).then((res: Response) => {\n return res.text()\n })\n}\n","import { AppInterface, plugins } from '@micro-app/types'\nimport { fetchSource } from '../fetch'\nimport { isFunction, isPlainObject, logError } from '../../libs/utils'\nimport microApp from '../../micro_app'\n\nexport interface IHTMLLoader {\n run (app: AppInterface, successCb: CallableFunction): void\n}\n\nexport class HTMLLoader implements IHTMLLoader {\n private static instance: HTMLLoader;\n public static getInstance (): HTMLLoader {\n if (!this.instance) {\n this.instance = new HTMLLoader()\n }\n return this.instance\n }\n\n /**\n * run logic of load and format html\n * @param successCb success callback\n * @param errorCb error callback, type: (err: Error, meetFetchErr: boolean) => void\n */\n public run (app: AppInterface, successCb: CallableFunction): void {\n const appName = app.name\n const htmlUrl = app.ssrUrl || app.url\n const htmlPromise = htmlUrl.includes('.js')\n ? Promise.resolve(`<micro-app-head><script src='${htmlUrl}'></script></micro-app-head><micro-app-body></micro-app-body>`)\n : fetchSource(htmlUrl, appName, { cache: 'no-cache' })\n htmlPromise.then((htmlStr: string) => {\n if (!htmlStr) {\n const msg = 'html is empty, please check in detail'\n app.onerror(new Error(msg))\n return logError(msg, appName)\n }\n\n htmlStr = this.formatHTML(htmlUrl, htmlStr, appName)\n\n successCb(htmlStr, app)\n }).catch((e) => {\n logError(`Failed to fetch data from ${app.url}, micro-app stop rendering`, appName, e)\n app.onLoadError(e)\n })\n }\n\n private formatHTML (htmlUrl: string, htmlStr: string, appName: string) {\n return this.processHtml(htmlUrl, htmlStr, appName, microApp.options.plugins)\n .replace(/<head[^>]*>[\\s\\S]*?<\\/head>/i, (match) => {\n return match\n .replace(/<head/i, '<micro-app-head')\n .replace(/<\\/head>/i, '</micro-app-head>')\n })\n .replace(/<body[^>]*>[\\s\\S]*?<\\/body>/i, (match) => {\n return match\n .replace(/<body/i, '<micro-app-body')\n .replace(/<\\/body>/i, '</micro-app-body>')\n })\n }\n\n private processHtml (url: string, code: string, appName: string, plugins: plugins | void): string {\n if (!plugins) return code\n\n const mergedPlugins: NonNullable<plugins['global']> = []\n plugins.global && mergedPlugins.push(...plugins.global)\n plugins.modules?.[appName] && mergedPlugins.push(...plugins.modules[appName])\n\n if (mergedPlugins.length > 0) {\n return mergedPlugins.reduce((preCode, plugin) => {\n if (isPlainObject(plugin) && isFunction(plugin.processHtml)) {\n return plugin.processHtml!(preCode, url)\n }\n return preCode\n }, code)\n }\n return code\n }\n}\n","/* eslint-disable no-useless-escape, no-cond-assign */\nimport type { AppInterface } from '@micro-app/types'\nimport { CompletionPath, getLinkFileDir, logError, trim, isFireFox } from '../libs/utils'\nimport microApp from '../micro_app'\n\n// common reg\nconst rootSelectorREG = /(^|\\s+)(html|:root)(?=[\\s>~[.#:]+|$)/\nconst bodySelectorREG = /(^|\\s+)((html[\\s>~]+body)|body)(?=[\\s>~[.#:]+|$)/\n\ntype parseErrorType = Error & { reason: string, filename?: string }\nfunction parseError (msg: string, linkPath?: string): void {\n msg = linkPath ? `${linkPath} ${msg}` : msg\n const err = new Error(msg) as parseErrorType\n err.reason = msg\n if (linkPath) {\n err.filename = linkPath\n }\n\n throw err\n}\n\n/**\n * Reference https://github.com/reworkcss/css\n * CSSParser mainly deals with 3 scenes: styleRule, @, and comment\n * And scopecss deals with 2 scenes: selector & url\n * And can also disable scopecss with inline comments\n */\nclass CSSParser {\n private cssText = '' // css content\n private prefix = '' // prefix as micro-app[name=xxx]\n private baseURI = '' // domain name\n private linkPath = '' // link resource address, if it is the style converted from link, it will have linkPath\n private result = '' // parsed cssText\n private scopecssDisable = false // use block comments /* scopecss-disable */ to disable scopecss in your file, and use /* scopecss-enable */ to enable scopecss\n private scopecssDisableSelectors: Array<string> = [] // disable or enable scopecss for specific selectors\n private scopecssDisableNextLine = false // use block comments /* scopecss-disable-next-line */ to disable scopecss on a specific line\n\n public exec (\n cssText: string,\n prefix: string,\n baseURI: string,\n linkPath?: string,\n ): string {\n this.cssText = cssText\n this.prefix = prefix\n this.baseURI = baseURI\n this.linkPath = linkPath || ''\n this.matchRules()\n return isFireFox() ? decodeURIComponent(this.result) : this.result\n }\n\n public reset (): void {\n this.cssText = this.prefix = this.baseURI = this.linkPath = this.result = ''\n this.scopecssDisable = this.scopecssDisableNextLine = false\n this.scopecssDisableSelectors = []\n }\n\n // core action for match rules\n private matchRules (): void {\n this.matchLeadingSpaces()\n this.matchComments()\n while (\n this.cssText.length &&\n this.cssText.charAt(0) !== '}' &&\n (this.matchAtRule() || this.matchStyleRule())\n ) {\n this.matchComments()\n }\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule\n private matchStyleRule (): boolean | void {\n const selectors = this.formatSelector(true)\n\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n\n if (!selectors) return parseError('selector missing', this.linkPath)\n\n this.recordResult(selectors)\n\n this.matchComments()\n\n this.styleDeclarations()\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n private formatSelector (skip: boolean): false | string {\n const m = this.commonMatch(/^[^{]+/, skip)\n if (!m) return false\n\n return m[0].replace(/(^|,[\\n\\s]*)([^,]+)/g, (_, separator, selector) => {\n selector = trim(selector)\n if (!(\n this.scopecssDisableNextLine ||\n (\n this.scopecssDisable && (\n !this.scopecssDisableSelectors.length ||\n this.scopecssDisableSelectors.includes(selector)\n )\n ) ||\n rootSelectorREG.test(selector)\n )) {\n if (bodySelectorREG.test(selector)) {\n selector = selector.replace(bodySelectorREG, this.prefix + ' micro-app-body')\n } else {\n selector = this.prefix + ' ' + selector\n }\n }\n\n return separator + selector\n })\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration\n private styleDeclarations (): boolean | void {\n if (!this.matchOpenBrace()) return parseError(\"Declaration missing '{'\", this.linkPath)\n\n this.matchAllDeclarations()\n\n if (!this.matchCloseBrace()) return parseError(\"Declaration missing '}'\", this.linkPath)\n\n return true\n }\n\n private matchAllDeclarations (nesting = 1): void {\n let cssValue = (this.commonMatch(/^(?:url\\([\"']?(?:[^)\"'}]+)[\"']?\\)|[^{}/])*/, true) as RegExpExecArray)[0]\n\n if (cssValue) {\n if (\n !this.scopecssDisableNextLine &&\n (!this.scopecssDisable || this.scopecssDisableSelectors.length)\n ) {\n cssValue = cssValue.replace(/url\\([\"']?([^)\"']+)[\"']?\\)/gm, (all, $1) => {\n if (/^((data|blob):|#)/.test($1) || /^(https?:)?\\/\\//.test($1)) {\n return all\n }\n\n // ./a/b.png ../a/b.png a/b.png\n if (/^((\\.\\.?\\/)|[^/])/.test($1) && this.linkPath) {\n this.baseURI = getLinkFileDir(this.linkPath)\n }\n\n return `url(\"${CompletionPath($1, this.baseURI)}\")`\n })\n }\n\n this.recordResult(cssValue)\n }\n\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n\n if (!this.cssText) return\n\n if (this.cssText.charAt(0) === '}') {\n if (!nesting) return\n if (nesting > 1) {\n this.commonMatch(/}+/)\n }\n return this.matchAllDeclarations(nesting - 1)\n }\n\n // extract comments in declarations\n if (this.cssText.charAt(0) === '/') {\n if (this.cssText.charAt(1) === '*') {\n this.matchComments()\n } else {\n this.commonMatch(/\\/+/)\n }\n }\n\n if (this.cssText.charAt(0) === '{') {\n this.commonMatch(/{+\\s*/)\n nesting++\n }\n\n return this.matchAllDeclarations(nesting)\n }\n\n private matchAtRule (): boolean | void {\n if (this.cssText[0] !== '@') return false\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n return this.keyframesRule() ||\n this.mediaRule() ||\n this.customMediaRule() ||\n this.supportsRule() ||\n this.importRule() ||\n this.charsetRule() ||\n this.namespaceRule() ||\n this.containerRule() ||\n this.documentRule() ||\n this.pageRule() ||\n this.hostRule() ||\n this.fontFaceRule()\n }\n\n // :global is CSS Modules rule, it will be converted to normal syntax\n // private matchGlobalRule (): boolean | void {\n // if (this.cssText[0] !== ':') return false\n // // reset scopecssDisableNextLine\n // this.scopecssDisableNextLine = false\n\n // return this.globalRule()\n // }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframesRule\n private keyframesRule (): boolean | void {\n if (!this.commonMatch(/^@([-\\w]+)?keyframes\\s*/)) return false\n\n if (!this.commonMatch(/^[^{]+/)) return parseError('@keyframes missing name', this.linkPath)\n\n this.matchComments()\n\n if (!this.matchOpenBrace()) return parseError(\"@keyframes missing '{'\", this.linkPath)\n\n this.matchComments()\n while (this.keyframeRule()) {\n this.matchComments()\n }\n\n if (!this.matchCloseBrace()) return parseError(\"@keyframes missing '}'\", this.linkPath)\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n private keyframeRule (): boolean {\n let r; const valList = []\n\n while (r = this.commonMatch(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/)) {\n valList.push(r[1])\n this.commonMatch(/^,\\s*/)\n }\n\n if (!valList.length) return false\n\n this.styleDeclarations()\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n // https://github.com/postcss/postcss-custom-media\n private customMediaRule (): boolean {\n if (!this.commonMatch(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/)) return false\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSPageRule\n private pageRule (): boolean | void {\n if (!this.commonMatch(/^@page */)) return false\n\n this.formatSelector(false)\n\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n\n return this.commonHandlerForAtRuleWithSelfRule('page')\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSFontFaceRule\n private fontFaceRule (): boolean | void {\n if (!this.commonMatch(/^@font-face\\s*/)) return false\n\n return this.commonHandlerForAtRuleWithSelfRule('font-face')\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSMediaRule\n private mediaRule = this.createMatcherForRuleWithChildRule(/^@media *([^{]+)/, '@media')\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSSupportsRule\n private supportsRule = this.createMatcherForRuleWithChildRule(/^@supports *([^{]+)/, '@supports')\n private documentRule = this.createMatcherForRuleWithChildRule(/^@([-\\w]+)?document *([^{]+)/, '@document')\n private hostRule = this.createMatcherForRuleWithChildRule(/^@host\\s*/, '@host')\n // :global is CSS Modules rule, it will be converted to normal syntax\n // private globalRule = this.createMatcherForRuleWithChildRule(/^:global([^{]*)/, ':global')\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSImportRule\n private importRule = this.createMatcherForNoneBraceAtRule('import')\n // Removed in most browsers\n private charsetRule = this.createMatcherForNoneBraceAtRule('charset')\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSNamespaceRule\n private namespaceRule = this.createMatcherForNoneBraceAtRule('namespace')\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@container\n private containerRule = this.createMatcherForRuleWithChildRule(/^@container *([^{]+)/, '@container')\n\n // common matcher for @media, @supports, @document, @host, :global, @container\n private createMatcherForRuleWithChildRule (reg: RegExp, name: string): () => boolean | void {\n return () => {\n if (!this.commonMatch(reg)) return false\n\n if (!this.matchOpenBrace()) return parseError(`${name} missing '{'`, this.linkPath)\n\n this.matchComments()\n\n this.matchRules()\n\n if (!this.matchCloseBrace()) return parseError(`${name} missing '}'`, this.linkPath)\n\n this.matchLeadingSpaces()\n\n return true\n }\n }\n\n // common matcher for @import, @charset, @namespace\n private createMatcherForNoneBraceAtRule (name: string): () => boolean {\n const reg = new RegExp('^@' + name + '\\\\s*([^;]+);')\n return () => {\n if (!this.commonMatch(reg)) return false\n this.matchLeadingSpaces()\n return true\n }\n }\n\n // common handler for @font-face, @page\n private commonHandlerForAtRuleWithSelfRule (name: string): boolean | void {\n if (!this.matchOpenBrace()) return parseError(`@${name} missing '{'`, this.linkPath)\n\n this.matchAllDeclarations()\n\n if (!this.matchCloseBrace()) return parseError(`@${name} missing '}'`, this.linkPath)\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n // match and slice comments\n private matchComments (): void {\n while (this.matchComment());\n }\n\n // css comment\n private matchComment (): boolean | void {\n if (this.cssText.charAt(0) !== '/' || this.cssText.charAt(1) !== '*') return false\n // reset scopecssDisableNextLine\n this.scopecssDisableNextLine = false\n\n let i = 2\n while (this.cssText.charAt(i) !== '' && (this.cssText.charAt(i) !== '*' || this.cssText.charAt(i + 1) !== '/')) ++i\n i += 2\n\n if (this.cssText.charAt(i - 1) === '') {\n return parseError('End of comment missing', this.linkPath)\n }\n\n // get comment content\n let commentText = this.cssText.slice(2, i - 2)\n\n this.recordResult(`/*${commentText}*/`)\n\n commentText = trim(commentText.replace(/^\\s*!/, ''))\n\n // set ignore config\n if (commentText === 'scopecss-disable-next-line') {\n this.scopecssDisableNextLine = true\n } else if (/^scopecss-disable/.test(commentText)) {\n if (commentText === 'scopecss-disable') {\n this.scopecssDisable = true\n } else {\n this.scopecssDisable = true\n const ignoreRules = commentText.replace('scopecss-disable', '').split(',')\n ignoreRules.forEach((rule: string) => {\n this.scopecssDisableSelectors.push(trim(rule))\n })\n }\n } else if (commentText === 'scopecss-enable') {\n this.scopecssDisable = false\n this.scopecssDisableSelectors = []\n }\n\n this.cssText = this.cssText.slice(i)\n\n this.matchLeadingSpaces()\n\n return true\n }\n\n private commonMatch (reg: RegExp, skip = false): RegExpExecArray | null | void {\n const matchArray = reg.exec(this.cssText)\n if (!matchArray) return\n const matchStr = matchArray[0]\n this.cssText = this.cssText.slice(matchStr.length)\n if (!skip) this.recordResult(matchStr)\n return matchArray\n }\n\n private matchOpenBrace () {\n return this.commonMatch(/^{\\s*/)\n }\n\n private matchCloseBrace () {\n return this.commonMatch(/^}/)\n }\n\n // match and slice the leading spaces\n private matchLeadingSpaces (): void {\n this.commonMatch(/^\\s*/)\n }\n\n // splice string\n private recordResult (strFragment: string): void {\n // Firefox performance degradation when string contain special characters, see https://github.com/micro-zoe/micro-app/issues/256\n if (isFireFox()) {\n this.result += encodeURIComponent(strFragment)\n } else {\n this.result += strFragment\n }\n }\n}\n\n/**\n * common method of bind CSS\n */\nfunction commonAction (\n styleElement: HTMLStyleElement,\n appName: string,\n prefix: string,\n baseURI: string,\n linkPath?: string,\n) {\n if (!styleElement.__MICRO_APP_HAS_SCOPED__) {\n styleElement.__MICRO_APP_HAS_SCOPED__ = true\n let result: string | null = null\n try {\n result = parser.exec(\n styleElement.textContent!,\n prefix,\n baseURI,\n linkPath,\n )\n parser.reset()\n } catch (e) {\n parser.reset()\n logError('An error occurred while parsing CSS:\\n', appName, e)\n }\n\n if (result) styleElement.textContent = result\n }\n}\n\nlet parser: CSSParser\n/**\n * scopedCSS\n * @param styleElement target style element\n * @param appName app name\n */\nexport default function scopedCSS (\n styleElement: HTMLStyleElement,\n app: AppInterface,\n linkPath?: string,\n): HTMLStyleElement {\n if (app.scopecss) {\n const prefix = createPrefix(app.name)\n\n if (!parser) parser = new CSSParser()\n\n if (styleElement.textContent) {\n commonAction(\n styleElement,\n app.name,\n prefix,\n app.url,\n linkPath,\n )\n } else {\n const observer = new MutationObserver(function () {\n observer.disconnect()\n // styled-component will be ignore\n if (styleElement.textContent && !styleElement.hasAttribute('data-styled')) {\n commonAction(\n styleElement,\n app.name,\n prefix,\n app.url,\n linkPath,\n )\n }\n })\n\n observer.observe(styleElement, { childList: true })\n }\n }\n\n return styleElement\n}\n\nexport function createPrefix (appName: string, reg = false): string {\n const regCharacter = reg ? '\\\\' : ''\n return `${microApp.tagName}${regCharacter}[name=${appName}${regCharacter}]`\n}\n","import { isFunction } from '../libs/utils'\n\nfunction eventHandler (event: Event, element: HTMLLinkElement | HTMLScriptElement): void {\n Object.defineProperties(event, {\n currentTarget: {\n get () {\n return element\n }\n },\n srcElement: {\n get () {\n return element\n }\n },\n target: {\n get () {\n return element\n }\n },\n })\n}\n\nexport function dispatchOnLoadEvent (element: HTMLLinkElement | HTMLScriptElement): void {\n const event = new CustomEvent('load')\n eventHandler(event, element)\n if (isFunction(element.onload)) {\n element.onload!(event)\n } else {\n element.dispatchEvent(event)\n }\n}\n\nexport function dispatchOnErrorEvent (element: HTMLLinkElement | HTMLScriptElement): void {\n const event = new CustomEvent('error')\n eventHandler(event, element)\n if (isFunction(element.onerror)) {\n element.onerror!(event)\n } else {\n element.dispatchEvent(event)\n }\n}\n","export enum ObservedAttrName {\n NAME = 'name',\n URL = 'url',\n}\n\n// app status\nexport enum appStates {\n CREATED = 'created',\n LOADING = 'loading',\n LOAD_FAILED = 'load_failed',\n BEFORE_MOUNT = 'before_mount',\n MOUNTING = 'mounting',\n MOUNTED = 'mounted',\n UNMOUNT = 'unmount',\n}\n\n// lifecycles\nexport enum lifeCycles {\n CREATED = 'created',\n BEFOREMOUNT = 'beforemount',\n MOUNTED = 'mounted',\n UNMOUNT = 'unmount',\n ERROR = 'error',\n // 👇 keep-alive only\n BEFORESHOW = 'beforeshow',\n AFTERSHOW = 'aftershow',\n AFTERHIDDEN = 'afterhidden',\n}\n\n// global event of child app\nexport enum microGlobalEvent {\n ONMOUNT = 'onmount',\n ONUNMOUNT = 'onunmount',\n}\n\n// keep-alive status\nexport enum keepAliveStates {\n KEEP_ALIVE_SHOW = 'keep_alive_show',\n KEEP_ALIVE_HIDDEN = 'keep_alive_hidden',\n}\n\n// micro-app config\nexport enum MicroAppConfig {\n DESTROY = 'destroy',\n DESTORY = 'destory',\n INLINE = 'inline',\n DISABLESCOPECSS = 'disableScopecss',\n DISABLESANDBOX = 'disableSandbox',\n DISABLE_SCOPECSS = 'disable-scopecss',\n DISABLE_SANDBOX = 'disable-sandbox',\n DISABLE_MEMORY_ROUTER = 'disable-memory-router',\n DISABLE_PATCH_REQUEST = 'disable-patch-request',\n KEEP_ROUTER_STATE = 'keep-router-state',\n HIDDEN_ROUTER = 'hidden-router',\n KEEP_ALIVE = 'keep-alive',\n CLEAR_DATA ='clear-data',\n SSR = 'ssr',\n FIBER = 'fiber',\n}\n\n// prefetch level\nexport const PREFETCH_LEVEL: number[] = [1, 2, 3]\n\n// memory router constants\n// default mode, child router info will sync to browser url\nexport const DEFAULT_ROUTER_MODE = 'search'\n/**\n * render base on browser url, and location.origin location.href point to base app\n * equal to disable-memory-router\n * NOTE:\n * 1. The only difference between native and native-scope is location.origin, in native-scope mode location.origin point to child app\n*/\nexport const ROUTER_MODE_NATIVE = 'native'\n// render base on browser url, but location.origin location.href point to child app\nexport const ROUTER_MODE_NATIVE_SCOPE = 'native-scope'\n// search mode, but child router info will not sync to browser url\nexport const ROUTER_MODE_PURE = 'pure'\nexport const ROUTER_MODE_LIST: string[] = [\n DEFAULT_ROUTER_MODE,\n ROUTER_MODE_NATIVE,\n ROUTER_MODE_NATIVE_SCOPE,\n ROUTER_MODE_PURE,\n]\n\n// event bound to child app window\nexport const SCOPE_WINDOW_EVENT = [\n 'popstate',\n 'hashchange',\n 'load',\n 'beforeunload',\n 'unload',\n 'unmount',\n 'appstate-change',\n 'statechange',\n 'mounted',\n]\n\n// on event bound to child app window\n// TODO: with和iframe处理方式不同,需修改\nexport const SCOPE_WINDOW_ON_EVENT = [\n 'onpopstate',\n 'onhashchange',\n 'onload',\n 'onbeforeunload',\n 'onunload',\n 'onerror'\n]\n\n// event bound to child app document\nexport const SCOPE_DOCUMENT_EVENT = [\n 'DOMContentLoaded',\n 'readystatechange',\n]\n\n// on event bound to child app document\nexport const SCOPE_DOCUMENT_ON_EVENT = [\n 'onreadystatechange',\n]\n\n// global key point to window\nexport const GLOBAL_KEY_TO_WINDOW: Array<PropertyKey> = [\n 'window',\n 'self',\n 'globalThis',\n]\n\nexport const RAW_GLOBAL_TARGET: Array<PropertyKey> = ['rawWindow', 'rawDocument']\n\n/**\n * global key must be static key, they can not rewrite\n * e.g.\n * window.Promise = newValue\n * new Promise ==> still get old value, not newValue, because they are cached by top function\n * NOTE:\n * 1. Do not add fetch, XMLHttpRequest, EventSource\n */\nexport const GLOBAL_CACHED_KEY = 'window,self,globalThis,document,Document,Array,Object,String,Boolean,Math,Number,Symbol,Date,Function,Proxy,WeakMap,WeakSet,Set,Map,Reflect,Element,Node,RegExp,Error,TypeError,JSON,isNaN,parseFloat,parseInt,performance,console,decodeURI,encodeURI,decodeURIComponent,encodeURIComponent,navigator,undefined,location,history'\n","import type { LinkSourceInfo, ScriptSourceInfo, SourceAddress } from '@micro-app/types'\nimport { isInlineScript } from '../libs/utils'\n\nexport interface SourceCenter<L = LinkSourceInfo, S = ScriptSourceInfo> {\n link: {\n setInfo (address: SourceAddress, info: L): void,\n getInfo (address: SourceAddress): L | null,\n hasInfo (address: SourceAddress): boolean,\n deleteInfo (address: SourceAddress): boolean,\n },\n script: {\n setInfo (address: SourceAddress, info: S): void,\n getInfo (address: SourceAddress): S | null,\n hasInfo (address: SourceAddress): boolean,\n deleteInfo (address: SourceAddress): boolean,\n deleteInlineInfo (addressList: Set<SourceAddress>): void,\n }\n}\n\nexport type LinkListType = Map<SourceAddress, LinkSourceInfo>\nexport type ScriptListType = Map<SourceAddress, ScriptSourceInfo>\n\n/**\n * SourceCenter is a resource management center\n * All html, js, css will be recorded and processed here\n * NOTE:\n * 1. All resources are global and shared between apps\n * 2. Pay attention to the case of html with parameters\n * 3. The resource is first processed by the plugin\n */\nfunction createSourceCenter (): SourceCenter {\n const linkList: LinkListType = new Map()\n const scriptList: ScriptListType = new Map()\n\n function createSourceHandler <P, T extends Map<SourceAddress, P>> (targetList: T): SourceCenter<P>['link'] | SourceCenter<LinkSourceInfo, P>['script'] {\n return {\n setInfo (address: SourceAddress, info: P): void {\n targetList.set(address, info)\n },\n getInfo (address: SourceAddress): P | null {\n return targetList.get(address) ?? null\n },\n hasInfo (address: SourceAddress): boolean {\n return targetList.has(address)\n },\n deleteInfo (address: SourceAddress): boolean {\n return targetList.delete(address)\n }\n }\n }\n\n return {\n link: createSourceHandler<LinkSourceInfo, LinkListType>(linkList),\n script: {\n ...createSourceHandler<ScriptSourceInfo, ScriptListType>(scriptList),\n deleteInlineInfo (addressList: Set<SourceAddress>): void {\n addressList.forEach((address) => {\n if (isInlineScript(address)) {\n scriptList.delete(address)\n }\n })\n }\n },\n }\n}\n\nexport default createSourceCenter()\n","import type {\n AppInterface,\n LinkSourceInfo,\n AttrsType,\n fiberTasks,\n} from '@micro-app/types'\nimport { fetchSource } from './fetch'\nimport {\n CompletionPath,\n promiseStream,\n pureCreateElement,\n defer,\n logError,\n getAttributes,\n injectFiberTask,\n serialExecFiberTasks,\n} from '../libs/utils'\nimport scopedCSS, { createPrefix } from '../sandbox/scoped_css'\nimport {\n dispatchOnLoadEvent,\n dispatchOnErrorEvent,\n} from './load_event'\nimport sourceCenter from './source_center'\nimport globalEnv from '../libs/global_env'\n\n/**\n *\n * @param appName app.name\n * @param linkInfo linkInfo of current address\n */\nfunction getExistParseCode (\n appName: string,\n prefix: string,\n linkInfo: LinkSourceInfo,\n): string | void {\n const appSpace = linkInfo.appSpace\n for (const item in appSpace) {\n if (item !== appName) {\n const appSpaceData = appSpace[item]\n if (appSpaceData.parsedCode) {\n return appSpaceData.parsedCode.replace(new RegExp(createPrefix(item, true), 'g'), prefix)\n }\n }\n }\n}\n\n// transfer the attributes on the link to convertStyle\nfunction setConvertStyleAttr (convertStyle: HTMLStyleElement, attrs: AttrsType): void {\n attrs.forEach((value, key) => {\n if (key === 'rel') return\n if (key === 'href') key = 'data-origin-href'\n globalEnv.rawSetAttribute.call(convertStyle, key, value)\n })\n}\n\n/**\n * Extract link elements\n * @param link link element\n * @param parent parent element of link\n * @param app app\n * @param microAppHead micro-app-head element\n * @param isDynamic dynamic insert\n */\nexport function extractLinkFromHtml (\n link: HTMLLinkElement,\n parent: Node | null,\n app: AppInterface,\n isDynamic = false,\n): any {\n const rel = link.getAttribute('rel')\n let href = link.getAttribute('href')\n let replaceComment: Comment | null = null\n if (rel === 'stylesheet' && href) {\n href = CompletionPath(href, app.url)\n let linkInfo = sourceCenter.link.getInfo(href)\n const appSpaceData = {\n attrs: getAttributes(link),\n }\n if (!linkInfo) {\n linkInfo = {\n code: '',\n appSpace: {\n [app.name]: appSpaceData,\n }\n }\n } else {\n linkInfo.appSpace[app.name] = linkInfo.appSpace[app.name] || appSpaceData\n }\n\n sourceCenter.link.setInfo(href, linkInfo)\n\n if (!isDynamic) {\n app.source.links.add(href)\n replaceComment = document.createComment(`link element with href=${href} move to micro-app-head as style element`)\n linkInfo.appSpace[app.name].placeholder = replaceComment\n } else {\n return { address: href, linkInfo }\n }\n } else if (rel && ['prefetch', 'preload', 'prerender'].includes(rel)) {\n // preload prefetch prerender ....\n if (isDynamic) {\n replaceComment = document.createComment(`link element with rel=${rel}${href ? ' & href=' + href : ''} removed by micro-app`)\n } else {\n parent?.removeChild(link)\n }\n } else if (href) {\n // dns-prefetch preconnect modulepreload search ....\n globalEnv.rawSetAttribute.call(link, 'href', CompletionPath(href, app.url))\n }\n\n if (isDynamic) {\n return { replaceComment }\n } else if (replaceComment) {\n return parent?.replaceChild(replaceComment, link)\n }\n}\n\n/**\n * Get link remote resources\n * @param wrapElement htmlDom\n * @param app app\n * @param microAppHead micro-app-head\n */\nexport function fetchLinksFromHtml (\n wrapElement: HTMLElement,\n app: AppInterface,\n microAppHead: Element,\n fiberStyleResult: Promise<void> | null,\n): void {\n const styleList: Array<string> = Array.from(app.source.links)\n const fetchLinkPromise: Array<Promise<string> | string> = styleList.map((address) => {\n const linkInfo = sourceCenter.link.getInfo(address)!\n return linkInfo.code ? linkInfo.code : fetchSource(address, app.name)\n })\n\n const fiberLinkTasks: fiberTasks = fiberStyleResult ? [] : null\n\n promiseStream<string>(fetchLinkPromise, (res: { data: string, index: number }) => {\n injectFiberTask(fiberLinkTasks, () => fetchLinkSuccess(\n styleList[res.index],\n res.data,\n microAppHead,\n app,\n ))\n }, (err: {error: Error, index: number}) => {\n logError(err, app.name)\n }, () => {\n /**\n * 1. If fiberStyleResult exist, fiberLinkTasks must exist\n * 2. Download link source while processing style\n * 3. Process style first, and then process link\n */\n if (fiberStyleResult) {\n fiberStyleResult.then(() => {\n fiberLinkTasks!.push(() => Promise.resolve(app.onLoad({ html: wrapElement })))\n serialExecFiberTasks(fiberLinkTasks)\n })\n } else {\n app.onLoad({ html: wrapElement })\n }\n })\n}\n\n/**\n * Fetch link succeeded, replace placeholder with style tag\n * NOTE:\n * 1. Only exec when init, no longer exec when remount\n * 2. Only handler html link element, not dynamic link or style\n * 3. The same prefix can reuse parsedCode\n * 4. Async exec with requestIdleCallback in prefetch or fiber\n * 5. appSpace[app.name].placeholder/attrs must exist\n * @param address resource address\n * @param code link source code\n * @param microAppHead micro-app-head\n * @param app app instance\n */\nexport function fetchLinkSuccess (\n address: string,\n code: string,\n microAppHead: Element,\n app: AppInterface,\n): void {\n /**\n * linkInfo must exist, but linkInfo.code not\n * so we set code to linkInfo.code\n */\n const linkInfo = sourceCenter.link.getInfo(address)!\n linkInfo.code = code\n const appSpaceData = linkInfo.appSpace[app.name]\n const placeholder = appSpaceData.placeholder!\n /**\n * When prefetch app is replaced by a new app in the processing phase, since the linkInfo is common, when the linkInfo of the prefetch app is processed, it may have already been processed.\n * This causes placeholder to be possibly null\n * e.g.\n * 1. prefetch app.url different from <micro-app></micro-app>\n * 2. prefetch param different from <micro-app></micro-app>\n */\n if (placeholder) {\n const convertStyle = pureCreateElement('style')\n\n handleConvertStyle(\n app,\n address,\n convertStyle,\n linkInfo,\n appSpaceData.attrs,\n )\n\n if (placeholder.parentNode) {\n placeholder.parentNode.replaceChild(convertStyle, placeholder)\n } else {\n microAppHead.appendChild(convertStyle)\n }\n\n // clear placeholder\n appSpaceData.placeholder = null\n }\n}\n\n/**\n * Get parsedCode, update convertStyle\n * Actions:\n * 1. get scope css (through scopedCSS or oldData)\n * 2. record parsedCode\n * 3. set parsedCode to convertStyle if need\n * @param app app instance\n * @param address resource address\n * @param convertStyle converted style\n * @param linkInfo linkInfo in sourceCenter\n * @param attrs attrs of link\n */\nexport function handleConvertStyle (\n app: AppInterface,\n address: string,\n convertStyle: HTMLStyleElement,\n linkInfo: LinkSourceInfo,\n attrs: AttrsType,\n): void {\n if (app.scopecss) {\n const appSpaceData = linkInfo.appSpace[app.name]\n appSpaceData.prefix = appSpaceData.prefix || createPrefix(app.name)\n if (!appSpaceData.parsedCode) {\n const existParsedCode = getExistParseCode(app.name, appSpaceData.prefix, linkInfo)\n if (!existParsedCode) {\n convertStyle.textContent = linkInfo.code\n scopedCSS(convertStyle, app, address)\n } else {\n convertStyle.textContent = existParsedCode\n }\n appSpaceData.parsedCode = convertStyle.textContent\n } else {\n convertStyle.textContent = appSpaceData.parsedCode\n }\n } else {\n convertStyle.textContent = linkInfo.code\n }\n\n setConvertStyleAttr(convertStyle, attrs)\n}\n\n/**\n * Handle css of dynamic link\n * @param address link address\n * @param app app\n * @param linkInfo linkInfo\n * @param originLink origin link element\n */\nexport function formatDynamicLink (\n address: string,\n app: AppInterface,\n linkInfo: LinkSourceInfo,\n originLink: HTMLLinkElement,\n): HTMLStyleElement {\n const convertStyle = pureCreateElement('style')\n\n const handleDynamicLink = () => {\n handleConvertStyle(\n app,\n address,\n convertStyle,\n linkInfo,\n linkInfo.appSpace[app.name].attrs,\n )\n dispatchOnLoadEvent(originLink)\n }\n\n if (linkInfo.code) {\n defer(handleDynamicLink)\n } else {\n fetchSource(address, app.name).then((data: string) => {\n linkInfo.code = data\n handleDynamicLink()\n }).catch((err) => {\n logError(err, app.name)\n dispatchOnErrorEvent(originLink)\n })\n }\n\n return convertStyle\n}\n","/* eslint-disable node/no-callback-literal, no-void */\nimport type {\n AppInterface,\n ScriptSourceInfo,\n plugins,\n Func,\n fiberTasks,\n AttrsType,\n microAppWindowType,\n} from '@micro-app/types'\nimport { fetchSource } from './fetch'\nimport {\n CompletionPath,\n promiseStream,\n createNonceSrc,\n pureCreateElement,\n defer,\n logError,\n isUndefined,\n isPlainObject,\n isArray,\n isFunction,\n getAttributes,\n injectFiberTask,\n serialExecFiberTasks,\n isInlineScript,\n isString,\n} from '../libs/utils'\nimport {\n dispatchOnLoadEvent,\n dispatchOnErrorEvent,\n} from './load_event'\nimport microApp from '../micro_app'\nimport globalEnv from '../libs/global_env'\nimport { GLOBAL_CACHED_KEY } from '../constants'\nimport sourceCenter from './source_center'\n\nexport type moduleCallBack = Func & { moduleCount?: number, errorCount?: number }\n\nconst scriptTypes = ['text/javascript', 'text/ecmascript', 'application/javascript', 'application/ecmascript', 'module', 'systemjs-module', 'systemjs-importmap']\n\n// whether use type='module' script\nfunction isTypeModule (app: AppInterface, scriptInfo: ScriptSourceInfo): boolean {\n return scriptInfo.appSpace[app.name].module && (!app.useSandbox || app.iframe)\n}\n\n// special script element\nfunction isSpecialScript (app: AppInterface, scriptInfo: ScriptSourceInfo): boolean {\n const attrs = scriptInfo.appSpace[app.name].attrs\n return attrs.has('id')\n}\n\n/**\n * whether to run js in inline mode\n * scene:\n * 1. inline config for app\n * 2. inline attr in script element\n * 3. module script\n * 4. script with special attr\n */\nfunction isInlineMode (app: AppInterface, scriptInfo: ScriptSourceInfo): boolean {\n return (\n app.inline ||\n scriptInfo.appSpace[app.name].inline ||\n isTypeModule(app, scriptInfo) ||\n isSpecialScript(app, scriptInfo)\n )\n}\n\n// TODO: iframe重新插入window前后不一致,通过iframe Function创建的函数无法复用\nfunction getEffectWindow (app: AppInterface): microAppWindowType {\n return app.iframe ? app.sandBox.microAppWindow : globalEnv.rawWindow\n}\n\n// Convert string code to function\nfunction code2Function (app: AppInterface, code: string): Function {\n const targetWindow = getEffectWindow(app)\n return new targetWindow.Function(code)\n}\n\n/**\n * If the appSpace of the current js address has other app, try to reuse parsedFunction of other app\n * @param appName app.name\n * @param scriptInfo scriptInfo of current address\n * @param currentCode pure code of current address\n */\nfunction getExistParseResult (\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n currentCode: string,\n): Function | void {\n const appSpace = scriptInfo.appSpace\n for (const item in appSpace) {\n if (item !== app.name) {\n const appSpaceData = appSpace[item]\n if (appSpaceData.parsedCode === currentCode && appSpaceData.parsedFunction) {\n return appSpaceData.parsedFunction\n }\n }\n }\n}\n\n/**\n * get parsedFunction from exist data or parsedCode\n * @returns parsedFunction\n */\nfunction getParsedFunction (\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n parsedCode: string,\n): Function {\n return getExistParseResult(app, scriptInfo, parsedCode) || code2Function(app, parsedCode)\n}\n\n// Prevent randomly created strings from repeating\nfunction getUniqueNonceSrc (): string {\n const nonceStr: string = createNonceSrc()\n if (sourceCenter.script.hasInfo(nonceStr)) {\n return getUniqueNonceSrc()\n }\n return nonceStr\n}\n\n// transfer the attributes on the script to convertScript\nfunction setConvertScriptAttr (convertScript: HTMLScriptElement, attrs: AttrsType): void {\n attrs.forEach((value, key) => {\n if ((key === 'type' && value === 'module') || key === 'defer' || key === 'async') return\n if (key === 'src') key = 'data-origin-src'\n globalEnv.rawSetAttribute.call(convertScript, key, value)\n })\n}\n\n// wrap code in sandbox\nfunction isWrapInSandBox (app: AppInterface, scriptInfo: ScriptSourceInfo): boolean {\n return app.useSandbox && !isTypeModule(app, scriptInfo)\n}\n\nfunction getSandboxType (app: AppInterface, scriptInfo: ScriptSourceInfo): 'with' | 'iframe' | 'disable' {\n return isWrapInSandBox(app, scriptInfo) ? app.iframe ? 'iframe' : 'with' : 'disable'\n}\n\n/**\n * Extract script elements\n * @param script script element\n * @param parent parent element of script\n * @param app app\n * @param isDynamic dynamic insert\n */\nexport function extractScriptElement (\n script: HTMLScriptElement,\n parent: Node | null,\n app: AppInterface,\n isDynamic = false,\n): any {\n let replaceComment: Comment | null = null\n let src: string | null = script.getAttribute('src')\n if (src) src = CompletionPath(src, app.url)\n if (script.hasAttribute('exclude') || checkExcludeUrl(src, app.name)) {\n replaceComment = document.createComment('script element with exclude attribute removed by micro-app')\n } else if (\n (\n script.type &&\n !scriptTypes.includes(script.type)\n ) ||\n script.hasAttribute('ignore') ||\n checkIgnoreUrl(src, app.name)\n ) {\n // 配置为忽略的脚本,清空 rawDocument.currentScript,避免被忽略的脚本内获取 currentScript 出错\n if (globalEnv.rawDocument?.currentScript) {\n delete globalEnv.rawDocument.currentScript\n }\n return null\n } else if (\n (globalEnv.supportModuleScript && script.noModule) ||\n (!globalEnv.supportModuleScript && script.type === 'module')\n ) {\n replaceComment = document.createComment(`${script.noModule ? 'noModule' : 'module'} script ignored by micro-app`)\n } else if (src) { // remote script\n let scriptInfo = sourceCenter.script.getInfo(src)\n const appSpaceData = {\n async: script.hasAttribute('async'),\n defer: script.defer || script.type === 'module',\n module: script.type === 'module',\n inline: script.hasAttribute('inline'),\n pure: script.hasAttribute('pure'),\n attrs: getAttributes(script),\n }\n if (!scriptInfo) {\n scriptInfo = {\n code: '',\n isExternal: true,\n appSpace: {\n [app.name]: appSpaceData,\n }\n }\n } else {\n /**\n * Reuse when appSpace exists\n * NOTE:\n * 1. The same static script, appSpace must be the same (in fact, it may be different when url change)\n * 2. The same dynamic script, appSpace may be the same, but we still reuse appSpace, which should pay attention\n */\n scriptInfo.appSpace[app.name] = scriptInfo.appSpace[app.name] || appSpaceData\n }\n\n sourceCenter.script.setInfo(src, scriptInfo)\n\n if (!isDynamic) {\n app.source.scripts.add(src)\n replaceComment = document.createComment(`script with src='${src}' extract by micro-app`)\n } else {\n return { address: src, scriptInfo }\n }\n } else if (script.textContent) { // inline script\n /**\n * NOTE:\n * 1. Each inline script is unique\n * 2. Every dynamic created inline script will be re-executed\n * ACTION:\n * 1. Delete dynamic inline script info after exec\n * 2. Delete static inline script info when destroy\n */\n const nonceStr: string = getUniqueNonceSrc()\n const scriptInfo = {\n code: script.textContent,\n isExternal: false,\n appSpace: {\n [app.name]: {\n async: false,\n defer: script.type === 'module',\n module: script.type === 'module',\n inline: script.hasAttribute('inline'),\n pure: script.hasAttribute('pure'),\n attrs: getAttributes(script),\n }\n }\n }\n if (!isDynamic) {\n app.source.scripts.add(nonceStr)\n sourceCenter.script.setInfo(nonceStr, scriptInfo)\n replaceComment = document.createComment('inline script extract by micro-app')\n } else {\n // Because each dynamic script is unique, it is not put into sourceCenter\n return { address: nonceStr, scriptInfo }\n }\n } else if (!isDynamic) {\n /**\n * script with empty src or empty script.textContent remove in static html\n * & not removed if it created by dynamic\n */\n replaceComment = document.createComment('script element removed by micro-app')\n }\n\n if (isDynamic) {\n return { replaceComment }\n } else {\n return parent?.replaceChild(replaceComment!, script)\n }\n}\n\n/**\n * get assets plugins\n * @param appName app name\n */\nexport function getAssetsPlugins (appName: string): plugins['global'] {\n const globalPlugins = microApp.options.plugins?.global || []\n const modulePlugins = microApp.options.plugins?.modules?.[appName] || []\n\n return [...globalPlugins, ...modulePlugins]\n}\n\n/**\n * whether the address needs to be excluded\n * @param address css or js link\n * @param plugins microApp plugins\n */\nexport function checkExcludeUrl (address: string | null, appName: string): boolean {\n if (!address) return false\n const plugins = getAssetsPlugins(appName) || []\n return plugins.some(plugin => {\n if (!plugin.excludeChecker) return false\n return plugin.excludeChecker(address)\n })\n}\n\n/**\n * whether the address needs to be ignore\n * @param address css or js link\n * @param plugins microApp plugins\n */\nexport function checkIgnoreUrl (address: string | null, appName: string): boolean {\n if (!address) return false\n const plugins = getAssetsPlugins(appName) || []\n return plugins.some(plugin => {\n if (!plugin.ignoreChecker) return false\n return plugin.ignoreChecker(address)\n })\n}\n\n/**\n * Get remote resources of script\n * @param wrapElement htmlDom\n * @param app app\n */\nexport function fetchScriptsFromHtml (\n wrapElement: HTMLElement,\n app: AppInterface,\n): void {\n const scriptList: Array<string> = Array.from(app.source.scripts)\n const fetchScriptPromise: Array<Promise<string> | string> = []\n const fetchScriptPromiseInfo: Array<[string, ScriptSourceInfo]> = []\n for (const address of scriptList) {\n const scriptInfo = sourceCenter.script.getInfo(address)!\n const appSpaceData = scriptInfo.appSpace[app.name]\n if ((!appSpaceData.defer && !appSpaceData.async) || (app.isPrefetch && !app.isPrerender)) {\n fetchScriptPromise.push(scriptInfo.code ? scriptInfo.code : fetchSource(address, app.name))\n fetchScriptPromiseInfo.push([address, scriptInfo])\n }\n }\n\n const fiberScriptTasks: fiberTasks = app.isPrefetch || app.fiber ? [] : null\n\n if (fetchScriptPromise.length) {\n promiseStream<string>(fetchScriptPromise, (res: {data: string, index: number}) => {\n injectFiberTask(fiberScriptTasks, () => fetchScriptSuccess(\n fetchScriptPromiseInfo[res.index][0],\n fetchScriptPromiseInfo[res.index][1],\n res.data,\n app,\n ))\n }, (err: {error: Error, index: number}) => {\n logError(err, app.name)\n }, () => {\n if (fiberScriptTasks) {\n fiberScriptTasks.push(() => Promise.resolve(app.onLoad({ html: wrapElement })))\n serialExecFiberTasks(fiberScriptTasks)\n } else {\n app.onLoad({ html: wrapElement })\n }\n })\n } else {\n app.onLoad({ html: wrapElement })\n }\n}\n\n/**\n * fetch js succeeded, record the code value\n * @param address script address\n * @param scriptInfo resource script info\n * @param data code\n */\nexport function fetchScriptSuccess (\n address: string,\n scriptInfo: ScriptSourceInfo,\n code: string,\n app: AppInterface,\n): void {\n // reset scriptInfo.code\n scriptInfo.code = code\n\n /**\n * Pre parse script for prefetch, improve rendering performance\n * NOTE:\n * 1. if global parseResult exist, skip this step\n * 2. if app is inline or script is esmodule, skip this step\n * 3. if global parseResult not exist, the current script occupies the position, when js is reused, parseResult is reference\n */\n if (app.isPrefetch && app.prefetchLevel === 2) {\n const appSpaceData = scriptInfo.appSpace[app.name]\n /**\n * When prefetch app is replaced by a new app in the processing phase, since the scriptInfo is common, when the scriptInfo of the prefetch app is processed, it may have already been processed.\n * This causes parsedCode to already exist when preloading ends\n * e.g.\n * 1. prefetch app.url different from <micro-app></micro-app>\n * 2. prefetch param different from <micro-app></micro-app>\n */\n if (!appSpaceData.parsedCode) {\n appSpaceData.parsedCode = bindScope(address, app, code, scriptInfo)\n appSpaceData.sandboxType = getSandboxType(app, scriptInfo)\n if (!isInlineMode(app, scriptInfo)) {\n try {\n appSpaceData.parsedFunction = getParsedFunction(app, scriptInfo, appSpaceData.parsedCode)\n } catch (err) {\n logError('Something went wrong while handling preloaded resources', app.name, '\\n', err)\n }\n }\n }\n }\n}\n\n/**\n * Execute js in the mount lifecycle\n * @param app app\n * @param initHook callback for umd mode\n */\nexport function execScripts (\n app: AppInterface,\n initHook: moduleCallBack,\n): void {\n const fiberScriptTasks: fiberTasks = app.fiber ? [] : null\n const scriptList: Array<string> = Array.from(app.source.scripts)\n const deferScriptPromise: Array<Promise<string>|string> = []\n const deferScriptInfo: Array<[string, ScriptSourceInfo]> = []\n for (const address of scriptList) {\n const scriptInfo = sourceCenter.script.getInfo(address)!\n const appSpaceData = scriptInfo.appSpace[app.name]\n // Notice the second render\n if (appSpaceData.defer || appSpaceData.async) {\n // TODO: defer和module彻底分开,不要混在一起\n if (scriptInfo.isExternal && !scriptInfo.code && !isTypeModule(app, scriptInfo)) {\n deferScriptPromise.push(fetchSource(address, app.name))\n } else {\n deferScriptPromise.push(scriptInfo.code)\n }\n deferScriptInfo.push([address, scriptInfo])\n\n isTypeModule(app, scriptInfo) && (initHook.moduleCount = initHook.moduleCount ? ++initHook.moduleCount : 1)\n } else {\n injectFiberTask(fiberScriptTasks, () => {\n runScript(address, app, scriptInfo)\n initHook(false)\n })\n }\n }\n\n if (deferScriptPromise.length) {\n promiseStream<string>(deferScriptPromise, (res: {data: string, index: number}) => {\n const scriptInfo = deferScriptInfo[res.index][1]\n scriptInfo.code = scriptInfo.code || res.data\n }, (err: {error: Error, index: number}) => {\n initHook.errorCount = initHook.errorCount ? ++initHook.errorCount : 1\n logError(err, app.name)\n }, () => {\n deferScriptInfo.forEach(([address, scriptInfo]) => {\n if (isString(scriptInfo.code)) {\n injectFiberTask(fiberScriptTasks, () => {\n runScript(address, app, scriptInfo, initHook)\n !isTypeModule(app, scriptInfo) && initHook(false)\n })\n }\n })\n\n /**\n * Fiber wraps js in requestIdleCallback and executes it in sequence\n * NOTE:\n * 1. In order to ensure the execution order, wait for all js loaded and then execute\n * 2. If js create a dynamic script, it may be errors in the execution order, because the subsequent js is wrapped in requestIdleCallback, even putting dynamic script in requestIdleCallback doesn't solve it\n *\n * BUG: NOTE.2 - execution order problem\n */\n if (fiberScriptTasks) {\n fiberScriptTasks.push(() => Promise.resolve(initHook(\n isUndefined(initHook.moduleCount) ||\n initHook.errorCount === deferScriptPromise.length\n )))\n serialExecFiberTasks(fiberScriptTasks)\n } else {\n initHook(\n isUndefined(initHook.moduleCount) ||\n initHook.errorCount === deferScriptPromise.length\n )\n }\n })\n } else {\n if (fiberScriptTasks) {\n fiberScriptTasks.push(() => Promise.resolve(initHook(true)))\n serialExecFiberTasks(fiberScriptTasks)\n } else {\n initHook(true)\n }\n }\n}\n\n/**\n * run code\n * @param address script address\n * @param app app\n * @param scriptInfo script info\n * @param callback callback of module script\n */\nexport function runScript (\n address: string,\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n callback?: moduleCallBack,\n replaceElement?: HTMLScriptElement,\n): void {\n try {\n actionsBeforeRunScript(app)\n const appSpaceData = scriptInfo.appSpace[app.name]\n const sandboxType = getSandboxType(app, scriptInfo)\n /**\n * NOTE:\n * 1. plugins and wrapCode will only be executed once\n * 2. if parsedCode not exist, parsedFunction is not exist\n * 3. if parsedCode exist, parsedFunction does not necessarily exist\n */\n if (!appSpaceData.parsedCode || appSpaceData.sandboxType !== sandboxType) {\n appSpaceData.parsedCode = bindScope(address, app, scriptInfo.code, scriptInfo)\n appSpaceData.sandboxType = sandboxType\n appSpaceData.parsedFunction = null\n }\n\n /**\n * TODO: 优化逻辑\n * 是否是内联模式应该由外部传入,这样自外而内更加统一,逻辑更加清晰\n */\n if (isInlineMode(app, scriptInfo)) {\n const scriptElement = replaceElement || pureCreateElement('script')\n runCode2InlineScript(\n address,\n appSpaceData.parsedCode,\n isTypeModule(app, scriptInfo),\n scriptElement,\n appSpaceData.attrs,\n callback,\n )\n\n /**\n * TODO: 优化逻辑\n * replaceElement不存在说明是初始化执行,需要主动插入script\n * 但这里的逻辑不清晰,应该明确声明是什么环境下才需要主动插入,而不是用replaceElement间接判断\n * replaceElement还有可能是注释类型(一定是在后台执行),这里的判断都是间接判断,不够直观\n */\n if (!replaceElement) {\n // TEST IGNORE\n const parent = app.iframe ? app.sandBox!.microBody : app.querySelector('micro-app-body')\n parent?.appendChild(scriptElement)\n }\n } else {\n runParsedFunction(app, scriptInfo)\n }\n } catch (e) {\n console.error(`[micro-app from ${replaceElement ? 'runDynamicScript' : 'runScript'}] app ${app.name}: `, e, address)\n // throw error in with sandbox to parent app\n throw e\n }\n}\n\n/**\n * Get dynamically created remote script\n * @param address script address\n * @param app app instance\n * @param scriptInfo scriptInfo\n * @param originScript origin script element\n */\nexport function runDynamicRemoteScript (\n address: string,\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n originScript: HTMLScriptElement,\n): HTMLScriptElement | Comment {\n const replaceElement = isInlineMode(app, scriptInfo) ? pureCreateElement('script') : document.createComment('dynamic script extract by micro-app')\n\n const dispatchScriptOnLoadEvent = () => dispatchOnLoadEvent(originScript)\n\n const runDynamicScript = () => {\n const descriptor = Object.getOwnPropertyDescriptor(globalEnv.rawDocument, 'currentScript')\n if (!descriptor || descriptor.configurable) {\n Object.defineProperty(globalEnv.rawDocument, 'currentScript', {\n value: originScript,\n configurable: true,\n })\n }\n\n runScript(address, app, scriptInfo, dispatchScriptOnLoadEvent, replaceElement as HTMLScriptElement)\n\n !isTypeModule(app, scriptInfo) && dispatchScriptOnLoadEvent()\n }\n\n if (scriptInfo.code || isTypeModule(app, scriptInfo)) {\n defer(runDynamicScript)\n } else {\n fetchSource(address, app.name).then((code: string) => {\n scriptInfo.code = code\n runDynamicScript()\n }).catch((err) => {\n logError(err, app.name)\n dispatchOnErrorEvent(originScript)\n })\n }\n\n return replaceElement\n}\n\n/**\n * Get dynamically created inline script\n * @param address script address\n * @param app app instance\n * @param scriptInfo scriptInfo\n */\nexport function runDynamicInlineScript (\n address: string,\n app: AppInterface,\n scriptInfo: ScriptSourceInfo,\n): HTMLScriptElement | Comment {\n const replaceElement = isInlineMode(app, scriptInfo) ? pureCreateElement('script') : document.createComment('dynamic script extract by micro-app')\n\n runScript(address, app, scriptInfo, void 0, replaceElement as HTMLScriptElement)\n\n return replaceElement\n}\n\n/**\n * common handle for inline script\n * @param address script address\n * @param code bound code\n * @param module type='module' of script\n * @param scriptElement target script element\n * @param attrs attributes of script element\n * @param callback callback of module script\n */\nfunction runCode2InlineScript (\n address: string,\n code: string,\n module: boolean,\n scriptElement: HTMLScriptElement,\n attrs: AttrsType,\n callback?: moduleCallBack,\n): void {\n if (module) {\n globalEnv.rawSetAttribute.call(scriptElement, 'type', 'module')\n if (isInlineScript(address)) {\n /**\n * inline module script cannot convert to blob mode\n * Issue: https://github.com/micro-zoe/micro-app/issues/805\n */\n scriptElement.textContent = code\n } else {\n scriptElement.src = address\n }\n if (callback) {\n const onloadHandler = () => {\n callback.moduleCount && callback.moduleCount--\n callback(callback.moduleCount === 0)\n }\n /**\n * NOTE:\n * 1. module script will execute onload method only after it insert to document/iframe\n * 2. we can't know when the inline module script onload, and we use defer to simulate, this maybe cause some problems\n */\n if (isInlineScript(address)) {\n defer(onloadHandler)\n } else {\n scriptElement.onload = onloadHandler\n }\n }\n } else {\n scriptElement.textContent = code\n }\n\n setConvertScriptAttr(scriptElement, attrs)\n}\n\n// init & run code2Function\nfunction runParsedFunction (app: AppInterface, scriptInfo: ScriptSourceInfo) {\n const appSpaceData = scriptInfo.appSpace[app.name]\n if (!appSpaceData.parsedFunction) {\n appSpaceData.parsedFunction = getParsedFunction(app, scriptInfo, appSpaceData.parsedCode!)\n }\n appSpaceData.parsedFunction.call(getEffectWindow(app))\n}\n\n/**\n * bind js scope\n * @param app app\n * @param code code\n * @param scriptInfo source script info\n */\nfunction bindScope (\n address: string,\n app: AppInterface,\n code: string,\n scriptInfo: ScriptSourceInfo,\n): string {\n // TODO: 1、cache 2、esm code is null\n if (isPlainObject(microApp.options.plugins)) {\n code = usePlugins(address, code, app.name, microApp.options.plugins)\n }\n\n if (isWrapInSandBox(app, scriptInfo)) {\n return app.iframe ? `(function(window,self,global,location){;${code}\\n${isInlineScript(address) ? '' : `//# sourceURL=${address}\\n`}}).call(window.__MICRO_APP_SANDBOX__.proxyWindow,window.__MICRO_APP_SANDBOX__.proxyWindow,window.__MICRO_APP_SANDBOX__.proxyWindow,window.__MICRO_APP_SANDBOX__.proxyWindow,window.__MICRO_APP_SANDBOX__.proxyLocation);` : `;(function(proxyWindow){with(proxyWindow.__MICRO_APP_WINDOW__){(function(${GLOBAL_CACHED_KEY}){;${code}\\n${isInlineScript(address) ? '' : `//# sourceURL=${address}\\n`}}).call(proxyWindow,${GLOBAL_CACHED_KEY})}})(window.__MICRO_APP_PROXY_WINDOW__);`\n }\n\n return code\n}\n\n/**\n * actions before run script\n */\nfunction actionsBeforeRunScript (app: AppInterface): void {\n setActiveProxyWindow(app)\n}\n\n/**\n * set active sandBox.proxyWindow to window.__MICRO_APP_PROXY_WINDOW__\n */\nfunction setActiveProxyWindow (app: AppInterface): void {\n if (app.sandBox) {\n globalEnv.rawWindow.__MICRO_APP_PROXY_WINDOW__ = app.sandBox.proxyWindow\n }\n}\n\n/**\n * Call the plugin to process the file\n * @param address script address\n * @param code code\n * @param appName app name\n * @param plugins plugin list\n */\nfunction usePlugins (address: string, code: string, appName: string, plugins: plugins): string {\n const newCode = processCode(plugins.global, code, address)\n\n return processCode(plugins.modules?.[appName], newCode, address)\n}\n\nfunction processCode (configs: plugins['global'], code: string, address: string) {\n if (!isArray(configs)) {\n return code\n }\n\n return configs.reduce((preCode, config) => {\n if (isPlainObject(config) && isFunction(config.loader)) {\n return config.loader(preCode, address)\n }\n\n return preCode\n }, code)\n}\n","import type { AppInterface, fiberTasks } from '@micro-app/types'\nimport {\n logError,\n CompletionPath,\n injectFiberTask,\n serialExecFiberTasks,\n isLinkElement,\n isScriptElement,\n isStyleElement,\n isImageElement,\n} from '../libs/utils'\nimport {\n extractLinkFromHtml,\n fetchLinksFromHtml,\n} from './links'\nimport {\n extractScriptElement,\n fetchScriptsFromHtml,\n checkExcludeUrl,\n checkIgnoreUrl,\n} from './scripts'\nimport scopedCSS from '../sandbox/scoped_css'\nimport globalEnv from '../libs/global_env'\n\n/**\n * Recursively process each child element\n * @param parent parent element\n * @param app app\n * @param microAppHead micro-app-head element\n */\nfunction flatChildren (\n parent: HTMLElement,\n app: AppInterface,\n microAppHead: Element,\n fiberStyleTasks: fiberTasks,\n): void {\n const children = Array.from(parent.children)\n\n children.length && children.forEach((child) => {\n flatChildren(child as HTMLElement, app, microAppHead, fiberStyleTasks)\n })\n\n for (const dom of children) {\n if (isLinkElement(dom)) {\n if (dom.hasAttribute('exclude') || checkExcludeUrl(dom.getAttribute('href'), app.name)) {\n parent.replaceChild(document.createComment('link element with exclude attribute ignored by micro-app'), dom)\n } else if (!(dom.hasAttribute('ignore') || checkIgnoreUrl(dom.getAttribute('href'), app.name))) {\n extractLinkFromHtml(dom, parent, app)\n } else if (dom.hasAttribute('href')) {\n globalEnv.rawSetAttribute.call(dom, 'href', CompletionPath(dom.getAttribute('href')!, app.url))\n }\n } else if (isStyleElement(dom)) {\n if (dom.hasAttribute('exclude')) {\n parent.replaceChild(document.createComment('style element with exclude attribute ignored by micro-app'), dom)\n } else if (app.scopecss && !dom.hasAttribute('ignore')) {\n injectFiberTask(fiberStyleTasks, () => scopedCSS(dom, app))\n }\n } else if (isScriptElement(dom)) {\n extractScriptElement(dom, parent, app)\n } else if (isImageElement(dom) && dom.hasAttribute('src')) {\n globalEnv.rawSetAttribute.call(dom, 'src', CompletionPath(dom.getAttribute('src')!, app.url))\n }\n /**\n * Don't remove meta and title, they have some special scenes\n * e.g.\n * document.querySelector('meta[name=\"viewport\"]') // for flexible\n * document.querySelector('meta[name=\"baseurl\"]').baseurl // for api request\n *\n * Title point to main app title, child app title used to be compatible with some special scenes\n */\n // else if (dom instanceof HTMLMetaElement || dom instanceof HTMLTitleElement) {\n // parent.removeChild(dom)\n // }\n }\n}\n\n/**\n * Extract link and script, bind style scope\n * @param htmlStr html string\n * @param app app\n */\nexport function extractSourceDom (htmlStr: string, app: AppInterface): void {\n const wrapElement = app.parseHtmlString(htmlStr)\n const microAppHead = globalEnv.rawElementQuerySelector.call(wrapElement, 'micro-app-head')\n const microAppBody = globalEnv.rawElementQuerySelector.call(wrapElement, 'micro-app-body')\n\n if (!microAppHead || !microAppBody) {\n const msg = `element ${microAppHead ? 'body' : 'head'} is missing`\n app.onerror(new Error(msg))\n return logError(msg, app.name)\n }\n\n const fiberStyleTasks: fiberTasks = app.isPrefetch || app.fiber ? [] : null\n\n flatChildren(wrapElement, app, microAppHead, fiberStyleTasks)\n\n /**\n * Style and link are parallel, because it takes a lot of time for link to request resources. During this period, style processing can be performed to improve efficiency.\n */\n const fiberStyleResult = serialExecFiberTasks(fiberStyleTasks)\n\n if (app.source.links.size) {\n fetchLinksFromHtml(wrapElement, app, microAppHead, fiberStyleResult)\n } else if (fiberStyleResult) {\n fiberStyleResult.then(() => app.onLoad({ html: wrapElement }))\n } else {\n app.onLoad({ html: wrapElement })\n }\n\n if (app.source.scripts.size) {\n fetchScriptsFromHtml(wrapElement, app)\n } else {\n app.onLoad({ html: wrapElement })\n }\n}\n","import { CallableFunctionForInteract } from '@micro-app/types'\nimport EventCenter from './event_center'\nimport { appInstanceMap } from '../create_app'\nimport {\n removeDomScope,\n isString,\n isFunction,\n isPlainObject,\n formatAppName,\n logError,\n getRootContainer,\n} from '../libs/utils'\n\nconst eventCenter = new EventCenter()\n\n/**\n * Format event name\n * @param appName app.name\n * @param fromBaseApp is from base app\n */\nfunction createEventName (appName: string, fromBaseApp: boolean): string {\n if (!isString(appName) || !appName) return ''\n return fromBaseApp ? `__from_base_app_${appName}__` : `__from_micro_app_${appName}__`\n}\n\n// Global data\nclass EventCenterForGlobal {\n /**\n * add listener of global data\n * @param cb listener\n * @param autoTrigger If there is cached data when first bind listener, whether it needs to trigger, default is false\n */\n addGlobalDataListener (cb: CallableFunctionForInteract, autoTrigger?: boolean): void {\n const appName = (this as any).appName\n // if appName exists, this is in sub app\n if (appName) {\n cb.__APP_NAME__ = appName\n cb.__AUTO_TRIGGER__ = autoTrigger\n }\n eventCenter.on('global', cb, autoTrigger)\n }\n\n /**\n * remove listener of global data\n * @param cb listener\n */\n removeGlobalDataListener (cb: CallableFunctionForInteract): void {\n isFunction(cb) && eventCenter.off('global', cb)\n }\n\n /**\n * dispatch global data\n * @param data data\n */\n setGlobalData (\n data: Record<PropertyKey, unknown>,\n nextStep?: CallableFunction,\n force?: boolean,\n ): void {\n // clear dom scope before dispatch global data, apply to micro app\n removeDomScope()\n\n eventCenter.dispatch(\n 'global',\n data,\n (resArr: unknown[]) => isFunction(nextStep) && nextStep(resArr),\n force,\n )\n }\n\n forceSetGlobalData (\n data: Record<PropertyKey, unknown>,\n nextStep?: CallableFunction,\n ): void {\n this.setGlobalData(data, nextStep, true)\n }\n\n /**\n * get global data\n */\n getGlobalData (): Record<PropertyKey, unknown> | null {\n return eventCenter.getData('global')\n }\n\n /**\n * clear global data\n */\n clearGlobalData (): void {\n eventCenter.clearData('global')\n }\n\n /**\n * clear all listener of global data\n * if appName exists, only the specified functions is cleared\n * if appName not exists, only clear the base app functions\n */\n clearGlobalDataListener (): void {\n const appName = (this as any).appName\n const eventInfo = eventCenter.eventList.get('global')\n if (eventInfo) {\n for (const cb of eventInfo.callbacks) {\n if (\n (appName && appName === cb.__APP_NAME__) ||\n !(appName || cb.__APP_NAME__)\n ) {\n eventInfo.callbacks.delete(cb)\n }\n }\n }\n }\n}\n\n// Event center for base app\nexport class EventCenterForBaseApp extends EventCenterForGlobal {\n /**\n * add listener\n * @param appName app.name\n * @param cb listener\n * @param autoTrigger If there is cached data when first bind listener, whether it needs to trigger, default is false\n */\n addDataListener (appName: string, cb: CallableFunction, autoTrigger?: boolean): void {\n eventCenter.on(createEventName(formatAppName(appName), false), cb, autoTrigger)\n }\n\n /**\n * remove listener\n * @param appName app.name\n * @param cb listener\n */\n removeDataListener (appName: string, cb: CallableFunction): void {\n isFunction(cb) && eventCenter.off(createEventName(formatAppName(appName), false), cb)\n }\n\n /**\n * get data from micro app or base app\n * @param appName app.name\n * @param fromBaseApp whether get data from base app, default is false\n */\n getData (appName: string, fromBaseApp = false): Record<PropertyKey, unknown> | null {\n return eventCenter.getData(createEventName(formatAppName(appName), fromBaseApp))\n }\n\n /**\n * Dispatch data to the specified micro app\n * @param appName app.name\n * @param data data\n */\n setData (\n appName: string,\n data: Record<PropertyKey, unknown>,\n nextStep?: CallableFunction,\n force?: boolean,\n ): void {\n eventCenter.dispatch(\n createEventName(formatAppName(appName), true),\n data,\n (resArr: unknown[]) => isFunction(nextStep) && nextStep(resArr),\n force,\n )\n }\n\n forceSetData (\n appName: string,\n data: Record<PropertyKey, unknown>,\n nextStep?: CallableFunction,\n ): void {\n this.setData(appName, data, nextStep, true)\n }\n\n /**\n * clear data from base app\n * @param appName app.name\n * @param fromBaseApp whether clear data from child app, default is true\n */\n clearData (appName: string, fromBaseApp = true): void {\n eventCenter.clearData(createEventName(formatAppName(appName), fromBaseApp))\n }\n\n /**\n * clear all listener for specified micro app\n * @param appName app.name\n */\n clearDataListener (appName: string): void {\n eventCenter.off(createEventName(formatAppName(appName), false))\n }\n}\n\n// Event center for sub app\nexport class EventCenterForMicroApp extends EventCenterForGlobal {\n appName: string\n umdDataListeners?: {\n global: Set<CallableFunctionForInteract>,\n normal: Set<CallableFunctionForInteract>,\n }\n\n constructor (appName: string) {\n super()\n this.appName = formatAppName(appName)\n !this.appName && logError(`Invalid appName ${appName}`)\n }\n\n /**\n * add listener, monitor the data sent by the base app\n * @param cb listener\n * @param autoTrigger If there is cached data when first bind listener, whether it needs to trigger, default is false\n */\n addDataListener (cb: CallableFunctionForInteract, autoTrigger?: boolean): void {\n cb.__AUTO_TRIGGER__ = autoTrigger\n eventCenter.on(createEventName(this.appName, true), cb, autoTrigger)\n }\n\n /**\n * remove listener\n * @param cb listener\n */\n removeDataListener (cb: CallableFunctionForInteract): void {\n isFunction(cb) && eventCenter.off(createEventName(this.appName, true), cb)\n }\n\n /**\n * get data from base app\n */\n getData (fromBaseApp = true): Record<PropertyKey, unknown> | null {\n return eventCenter.getData(createEventName(this.appName, fromBaseApp))\n }\n\n /**\n * dispatch data to base app\n * @param data data\n */\n dispatch (data: Record<PropertyKey, unknown>, nextStep?: CallableFunction, force?: boolean): void {\n removeDomScope()\n\n eventCenter.dispatch(\n createEventName(this.appName, false),\n data,\n (resArr: unknown[]) => isFunction(nextStep) && nextStep(resArr),\n force,\n () => {\n const app = appInstanceMap.get(this.appName)\n if (app?.container && isPlainObject(data)) {\n const event = new CustomEvent('datachange', {\n detail: {\n data: eventCenter.getData(createEventName(this.appName, false))\n }\n })\n\n getRootContainer(app.container).dispatchEvent(event)\n }\n })\n }\n\n forceDispatch (data: Record<PropertyKey, unknown>, nextStep?: CallableFunction): void {\n this.dispatch(data, nextStep, true)\n }\n\n /**\n * clear data from child app\n * @param fromBaseApp whether clear data from base app, default is false\n */\n clearData (fromBaseApp = false): void {\n eventCenter.clearData(createEventName(this.appName, fromBaseApp))\n }\n\n /**\n * clear all listeners\n */\n clearDataListener (): void {\n eventCenter.off(createEventName(this.appName, true))\n }\n}\n\n/**\n * Record UMD function before exec umdHookMount\n * NOTE: record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * @param microAppEventCenter instance of EventCenterForMicroApp\n */\nexport function recordDataCenterSnapshot (microAppEventCenter: EventCenterForMicroApp): void {\n if (microAppEventCenter) {\n microAppEventCenter.umdDataListeners = {\n global: new Set(microAppEventCenter.umdDataListeners?.global),\n normal: new Set(microAppEventCenter.umdDataListeners?.normal),\n }\n\n const globalEventInfo = eventCenter.eventList.get('global')\n if (globalEventInfo) {\n for (const cb of globalEventInfo.callbacks) {\n if (microAppEventCenter.appName === cb.__APP_NAME__) {\n microAppEventCenter.umdDataListeners.global.add(cb)\n }\n }\n }\n\n const subAppEventInfo = eventCenter.eventList.get(createEventName(microAppEventCenter.appName, true))\n if (subAppEventInfo) {\n for (const cb of subAppEventInfo.callbacks) {\n microAppEventCenter.umdDataListeners.normal.add(cb)\n }\n }\n }\n}\n\n/**\n * Rebind the UMD function of the record before remount\n * @param microAppEventCenter instance of EventCenterForMicroApp\n */\nexport function rebuildDataCenterSnapshot (microAppEventCenter: EventCenterForMicroApp): void {\n // in withSandbox preRender mode with module script, umdDataListeners maybe undefined\n if (microAppEventCenter?.umdDataListeners) {\n for (const cb of microAppEventCenter.umdDataListeners.global) {\n microAppEventCenter.addGlobalDataListener(cb, cb.__AUTO_TRIGGER__)\n }\n\n for (const cb of microAppEventCenter.umdDataListeners.normal) {\n microAppEventCenter.addDataListener(cb, cb.__AUTO_TRIGGER__)\n }\n\n resetDataCenterSnapshot(microAppEventCenter)\n }\n}\n\n/**\n * delete umdDataListeners from microAppEventCenter\n * @param microAppEventCenter instance of EventCenterForMicroApp\n */\nexport function resetDataCenterSnapshot (microAppEventCenter: EventCenterForMicroApp): void {\n delete microAppEventCenter?.umdDataListeners\n}\n","/* eslint-disable no-cond-assign */\nimport { CallableFunctionForInteract, AppName } from '@micro-app/types'\nimport { logError, isFunction, isPlainObject, assign, defer } from '../libs/utils'\n\nexport default class EventCenter {\n public eventList = new Map<string, {\n data: Record<PropertyKey, unknown>,\n tempData?: Record<PropertyKey, unknown> | null,\n force?: boolean,\n callbacks: Set<CallableFunctionForInteract>,\n }>()\n\n // whether the name is legal\n private isLegalName (name: string): boolean {\n if (!name) {\n logError('event-center: Invalid name')\n return false\n }\n\n return true\n }\n\n private queue: string[] = []\n private recordStep: Record<string, {\n nextStepList: Array<CallableFunction>,\n dispatchDataEvent?: CallableFunction,\n } | null> = {}\n\n // add appName to queue\n private enqueue (\n name: AppName,\n nextStep: CallableFunction,\n dispatchDataEvent?: CallableFunction,\n ): void {\n // this.nextStepList.push(nextStep)\n if (this.recordStep[name]) {\n this.recordStep[name]!.nextStepList.push(nextStep)\n dispatchDataEvent && (this.recordStep[name]!.dispatchDataEvent = dispatchDataEvent)\n } else {\n this.recordStep[name] = {\n nextStepList: [nextStep],\n dispatchDataEvent,\n }\n }\n /**\n * The micro task is executed async when the second render of child.\n * We should ensure that the data changes are executed before binding the listening function\n */\n (!this.queue.includes(name) && this.queue.push(name) === 1) && defer(this.process)\n }\n\n // run task\n private process = (): void => {\n let name: string | void\n const temRecordStep = this.recordStep\n const queue = this.queue\n this.recordStep = {}\n this.queue = []\n while (name = queue.shift()) {\n const eventInfo = this.eventList.get(name)!\n // clear tempData, force before exec nextStep\n const tempData = eventInfo.tempData\n const force = eventInfo.force\n eventInfo.tempData = null\n eventInfo.force = false\n let resArr: unknown[]\n if (force || !this.isEqual(eventInfo.data, tempData)) {\n eventInfo.data = tempData || eventInfo.data\n for (const f of eventInfo.callbacks) {\n const res = f(eventInfo.data)\n res && (resArr ??= []).push(res)\n }\n\n temRecordStep[name]!.dispatchDataEvent?.()\n\n /**\n * WARING:\n * If data of other app is sent in nextStep, it may cause confusion of tempData and force\n */\n temRecordStep[name]!.nextStepList.forEach((nextStep) => nextStep(resArr))\n }\n }\n }\n\n /**\n * In react, each setState will trigger setData, so we need a filter operation to avoid repeated trigger\n */\n private isEqual (\n oldData: Record<PropertyKey, unknown>,\n newData: Record<PropertyKey, unknown> | null | void,\n ): boolean {\n if (!newData || Object.keys(oldData).length !== Object.keys(newData).length) return false\n\n for (const key in oldData) {\n if (Object.prototype.hasOwnProperty.call(oldData, key)) {\n if (oldData[key] !== newData[key]) return false\n }\n }\n\n return true\n }\n\n /**\n * add listener\n * @param name event name\n * @param f listener\n * @param autoTrigger If there is cached data when first bind listener, whether it needs to trigger, default is false\n */\n public on (name: string, f: CallableFunctionForInteract, autoTrigger = false): void {\n if (this.isLegalName(name)) {\n if (!isFunction(f)) {\n return logError('event-center: Invalid callback function')\n }\n\n let eventInfo = this.eventList.get(name)\n if (!eventInfo) {\n eventInfo = {\n data: {},\n callbacks: new Set(),\n }\n this.eventList.set(name, eventInfo)\n } else if (\n autoTrigger &&\n Object.keys(eventInfo.data).length &&\n (\n !this.queue.includes(name) ||\n this.isEqual(eventInfo.data, eventInfo.tempData)\n )\n ) {\n // auto trigger when data not null\n f(eventInfo.data)\n }\n\n eventInfo.callbacks.add(f)\n }\n }\n\n // remove listener, but the data is not cleared\n public off (\n name: string,\n f?: CallableFunctionForInteract,\n ): void {\n if (this.isLegalName(name)) {\n const eventInfo = this.eventList.get(name)\n if (eventInfo) {\n if (isFunction(f)) {\n eventInfo.callbacks.delete(f)\n } else {\n eventInfo.callbacks.clear()\n }\n }\n }\n }\n\n /**\n * clearData\n */\n public clearData (name: string): void {\n if (this.isLegalName(name)) {\n const eventInfo = this.eventList.get(name)\n if (eventInfo) {\n eventInfo.data = {}\n }\n }\n }\n\n // dispatch data\n public dispatch (\n name: string,\n data: Record<PropertyKey, unknown>,\n nextStep: CallableFunction,\n force?: boolean,\n dispatchDataEvent?: CallableFunction,\n ): void {\n if (this.isLegalName(name)) {\n if (!isPlainObject(data)) {\n return logError('event-center: data must be object')\n }\n\n let eventInfo = this.eventList.get(name)\n if (eventInfo) {\n eventInfo.tempData = assign({}, eventInfo.tempData || eventInfo.data, data)\n !eventInfo.force && (eventInfo.force = !!force)\n } else {\n eventInfo = {\n data: data,\n callbacks: new Set(),\n }\n this.eventList.set(name, eventInfo)\n /**\n * When sent data to parent, eventInfo probably does not exist, because parent may listen to datachange\n */\n eventInfo.force = true\n }\n // add to queue, event eventInfo is null\n this.enqueue(name, nextStep, dispatchDataEvent)\n }\n }\n\n // get data\n public getData (name: string): Record<PropertyKey, unknown> | null {\n const eventInfo = this.eventList.get(name)\n return eventInfo?.data ?? null\n }\n}\n","import { appInstanceMap } from './create_app'\nimport { AppInterface } from '@micro-app/types'\n\nexport interface IAppManager {\n get(appName: string): AppInterface | void\n set(appName: string, app: AppInterface): void\n getAll(): AppInterface[]\n clear(): void\n}\n\n// 管理 app 的单例\nexport class AppManager implements IAppManager {\n private static instance: AppManager;\n // TODO: appInstanceMap 由 AppManager 来创建,不再由 create_app 管理\n private appInstanceMap = appInstanceMap;\n\n public static getInstance (): AppManager {\n if (!this.instance) {\n this.instance = new AppManager()\n }\n return this.instance\n }\n\n public get (appName: string): AppInterface | void {\n return this.appInstanceMap.get(appName)\n }\n\n public set (appName: string, app: AppInterface): void {\n this.appInstanceMap.set(appName, app)\n }\n\n public getAll (): AppInterface[] {\n return Array.from(this.appInstanceMap.values())\n }\n\n public clear (): void {\n this.appInstanceMap.clear()\n }\n}\n","import { AppManager } from '../app_manager'\nimport { getRootContainer } from '../libs/utils'\n\nfunction unmountNestedApp (): void {\n releaseUnmountOfNestedApp()\n\n AppManager.getInstance().getAll().forEach(app => {\n // @ts-ignore\n app.container && getRootContainer(app.container).disconnectedCallback()\n })\n\n !window.__MICRO_APP_UMD_MODE__ && AppManager.getInstance().clear()\n}\n\n// release listener\nfunction releaseUnmountOfNestedApp (): void {\n if (window.__MICRO_APP_ENVIRONMENT__) {\n window.removeEventListener('unmount', unmountNestedApp, false)\n }\n}\n\n// if micro-app run in micro application, delete all next generation application when unmount event received\n// unmount event will auto release by sandbox\nexport function initEnvOfNestedApp (): void {\n if (window.__MICRO_APP_ENVIRONMENT__) {\n releaseUnmountOfNestedApp()\n window.addEventListener('unmount', unmountNestedApp, false)\n }\n}\n","/* eslint-disable no-return-assign */\nimport {\n isBoundFunction,\n isConstructor,\n rawDefineProperty,\n isBoolean,\n isFunction,\n} from '../libs/utils'\n\nfunction isBoundedFunction (value: CallableFunction & {__MICRO_APP_IS_BOUND_FUNCTION__: boolean}): boolean {\n if (isBoolean(value.__MICRO_APP_IS_BOUND_FUNCTION__)) return value.__MICRO_APP_IS_BOUND_FUNCTION__\n return value.__MICRO_APP_IS_BOUND_FUNCTION__ = isBoundFunction(value)\n}\n\nfunction isConstructorFunction (value: FunctionConstructor & {__MICRO_APP_IS_CONSTRUCTOR__: boolean}) {\n if (isBoolean(value.__MICRO_APP_IS_CONSTRUCTOR__)) return value.__MICRO_APP_IS_CONSTRUCTOR__\n return value.__MICRO_APP_IS_CONSTRUCTOR__ = isConstructor(value)\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport default function bindFunctionToRawTarget<T = Window, B = unknown> (value: any, rawTarget: T, key = 'WINDOW'): B {\n if (isFunction(value) && !isConstructorFunction(value) && !isBoundedFunction(value)) {\n const cacheKey = `__MICRO_APP_BOUND_${key}_FUNCTION__`\n if (value[cacheKey]) return value[cacheKey]\n\n const bindRawObjectValue = value.bind(rawTarget)\n\n for (const key in value) {\n bindRawObjectValue[key] = value[key]\n }\n\n if (value.hasOwnProperty('prototype')) {\n rawDefineProperty(bindRawObjectValue, 'prototype', {\n value: value.prototype,\n configurable: true,\n enumerable: false,\n writable: true,\n })\n }\n\n return value[cacheKey] = bindRawObjectValue\n }\n\n return value\n}\n","/* eslint-disable no-cond-assign */\nimport type {\n CommonEffectHook,\n MicroEventListener,\n WithSandBoxInterface,\n microAppWindowType,\n} from '@micro-app/types'\nimport microApp from '../../micro_app'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n throttleDeferForSetAppName,\n isFunction,\n rawDefineProperties,\n} from '../../libs/utils'\nimport {\n appInstanceMap,\n} from '../../create_app'\n\n/**\n * create proxyDocument and MicroDocument, rewrite document of child app\n * @param appName app name\n * @param microAppWindow Proxy target\n * @returns EffectHook\n */\nexport function patchDocument (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: WithSandBoxInterface,\n): CommonEffectHook {\n const { proxyDocument, documentEffect } = createProxyDocument(appName, sandbox)\n const MicroDocument = createMicroDocument(appName, proxyDocument)\n rawDefineProperties(microAppWindow, {\n document: {\n configurable: false,\n enumerable: true,\n get () {\n // return globalEnv.rawDocument\n return proxyDocument\n },\n },\n Document: {\n configurable: false,\n enumerable: false,\n get () {\n // return globalEnv.rawRootDocument\n return MicroDocument\n },\n }\n })\n\n return documentEffect\n}\n\n/**\n * Create new document and Document\n */\nfunction createProxyDocument (\n appName: string,\n sandbox: WithSandBoxInterface,\n): {\n proxyDocument: Document,\n documentEffect: CommonEffectHook,\n } {\n const eventListenerMap = new Map<string, Set<MicroEventListener>>()\n const sstEventListenerMap = new Map<string, Set<MicroEventListener>>()\n let onClickHandler: unknown = null\n let sstOnClickHandler: unknown = null\n const {\n rawDocument,\n rawCreateElement,\n rawCreateElementNS,\n rawAddEventListener,\n rawRemoveEventListener,\n } = globalEnv\n\n function createElement (\n tagName: string,\n options?: ElementCreationOptions,\n ): HTMLElement {\n const element = rawCreateElement.call(rawDocument, tagName, options)\n element.__MICRO_APP_NAME__ = appName\n return element\n }\n\n function createElementNS (\n namespaceURI: string,\n name: string,\n options?: string | ElementCreationOptions,\n ): HTMLElement {\n const element = rawCreateElementNS.call(rawDocument, namespaceURI, name, options)\n element.__MICRO_APP_NAME__ = appName\n return element\n }\n\n /**\n * TODO:\n * 1. listener 是否需要绑定proxyDocument,否则函数中的this指向原生window\n * 2. 相似代码提取为公共方法(with, iframe)\n * 3. 如果this不指向proxyDocument 和 rawDocument,则需要特殊处理\n */\n function addEventListener (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList) {\n listenerList.add(listener)\n } else {\n eventListenerMap.set(type, new Set([listener]))\n }\n listener && (listener.__MICRO_APP_MARK_OPTIONS__ = options)\n rawAddEventListener.call(rawDocument, type, listener, options)\n }\n\n function removeEventListener (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList?.size && listenerList.has(listener)) {\n listenerList.delete(listener)\n }\n rawRemoveEventListener.call(rawDocument, type, listener, options)\n }\n\n // reset snapshot data\n const reset = (): void => {\n sstEventListenerMap.clear()\n sstOnClickHandler = null\n }\n\n /**\n * NOTE:\n * 1. about timer(events & properties should record & rebuild at all modes, exclude default mode)\n * 2. record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * 4 modes: default-mode、umd-mode、prerender、keep-alive\n * Solution:\n * 1. default-mode(normal): clear events & timers, not record & rebuild anything\n * 2. umd-mode(normal): not clear timers, record & rebuild events\n * 3. prerender/keep-alive(default, umd): not clear timers, record & rebuild events\n */\n const record = (): void => {\n /**\n * record onclick handler\n * onClickHandler maybe set again after prerender/keep-alive app hidden\n */\n sstOnClickHandler = onClickHandler || sstOnClickHandler\n\n // record document event\n eventListenerMap.forEach((listenerList, type) => {\n if (listenerList.size) {\n const cacheList = sstEventListenerMap.get(type) || []\n sstEventListenerMap.set(type, new Set([...cacheList, ...listenerList]))\n }\n })\n }\n\n // rebuild event and timer before remount app\n const rebuild = (): void => {\n // rebuild onclick event\n if (sstOnClickHandler && !onClickHandler) proxyDocument.onclick = sstOnClickHandler\n\n // rebuild document event\n sstEventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n proxyDocument.addEventListener(type, listener, listener?.__MICRO_APP_MARK_OPTIONS__)\n }\n })\n\n reset()\n }\n\n // release all event listener & interval & timeout when unmount app\n const release = (): void => {\n // Clear the function bound by micro app through document.onclick\n if (isFunction(onClickHandler)) {\n rawRemoveEventListener.call(rawDocument, 'click', onClickHandler)\n }\n onClickHandler = null\n\n // Clear document binding event\n if (eventListenerMap.size) {\n eventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n rawRemoveEventListener.call(rawDocument, type, listener)\n }\n })\n eventListenerMap.clear()\n }\n }\n\n const genProxyDocumentProps = () => {\n // microApp framework built-in Proxy\n const builtInProxyProps = new Map([\n ['onclick', (value: unknown) => {\n if (isFunction(onClickHandler)) {\n rawRemoveEventListener.call(rawDocument, 'click', onClickHandler, false)\n }\n // TODO: listener 是否需要绑定proxyDocument,否则函数中的this指向原生window\n if (isFunction(value)) {\n rawAddEventListener.call(rawDocument, 'click', value, false)\n }\n onClickHandler = value\n }]\n ])\n // external custom proxy\n const customProxyDocumentProps = microApp.options?.customProxyDocumentProps || new Map()\n // External has higher priority than built-in\n const mergedProxyDocumentProps = new Map([\n ...builtInProxyProps,\n ...customProxyDocumentProps,\n ])\n return mergedProxyDocumentProps\n }\n\n const mergedProxyDocumentProps = genProxyDocumentProps()\n\n const proxyDocument = new Proxy(rawDocument, {\n get: (target: Document, key: PropertyKey): unknown => {\n throttleDeferForSetAppName(appName)\n // TODO: 转换成数据形式,类似iframe的方式\n if (key === 'createElement') return createElement\n if (key === 'createElementNS') return createElementNS\n if (key === Symbol.toStringTag) return 'ProxyDocument'\n if (key === 'defaultView') return sandbox.proxyWindow\n if (key === 'onclick') return onClickHandler\n if (key === 'addEventListener') return addEventListener\n if (key === 'removeEventListener') return removeEventListener\n if (key === 'microAppElement') return appInstanceMap.get(appName)?.container\n if (key === '__MICRO_APP_NAME__') return appName\n return bindFunctionToRawTarget<Document>(Reflect.get(target, key), rawDocument, 'DOCUMENT')\n },\n set: (target: Document, key: PropertyKey, value: unknown): boolean => {\n if (mergedProxyDocumentProps.has(key)) {\n const proxyCallback = mergedProxyDocumentProps.get(key)\n proxyCallback(value)\n } else if (key !== 'microAppElement') {\n /**\n * 1. Fix TypeError: Illegal invocation when set document.title\n * 2. If the set method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown.\n */\n Reflect.set(target, key, value)\n }\n return true\n }\n })\n\n return {\n proxyDocument,\n documentEffect: {\n reset,\n record,\n rebuild,\n release,\n }\n }\n}\n\n/**\n * create proto Document\n * @param appName app name\n * @param proxyDocument proxy(document)\n * @returns Document\n */\nfunction createMicroDocument (appName: string, proxyDocument: Document): Function {\n const { rawDocument, rawRootDocument } = globalEnv\n\n class MicroDocument {\n static [Symbol.hasInstance] (target: unknown) {\n let proto = target\n while (proto) {\n proto = Object.getPrototypeOf(proto)\n if (proto === MicroDocument.prototype) {\n return true\n }\n }\n return (\n target === proxyDocument ||\n target instanceof rawRootDocument\n )\n }\n }\n\n /**\n * TIP:\n * 1. child class __proto__, which represents the inherit of the constructor, always points to the parent class\n * 2. child class prototype.__proto__, which represents the inherit of methods, always points to parent class prototype\n * e.g.\n * class B extends A {}\n * B.__proto__ === A // true\n * B.prototype.__proto__ === A.prototype // true\n */\n Object.setPrototypeOf(MicroDocument, rawRootDocument)\n // Object.create(rawRootDocument.prototype) will cause MicroDocument and proxyDocument methods not same when exec Document.prototype.xxx = xxx in child app\n Object.setPrototypeOf(MicroDocument.prototype, new Proxy(rawRootDocument.prototype, {\n get (target: Document, key: PropertyKey): unknown {\n throttleDeferForSetAppName(appName)\n return bindFunctionToRawTarget<Document>(Reflect.get(target, key), rawDocument, 'DOCUMENT')\n },\n set (target: Document, key: PropertyKey, value: unknown): boolean {\n Reflect.set(target, key, value)\n return true\n }\n }))\n\n return MicroDocument\n}\n","import type {\n microAppWindowType,\n CommonEffectHook,\n MicroEventListener,\n timeInfo,\n WithSandBoxInterface,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n SCOPE_WINDOW_EVENT,\n SCOPE_WINDOW_ON_EVENT,\n RAW_GLOBAL_TARGET,\n} from '../../constants'\nimport {\n isString,\n includes,\n unique,\n throttleDeferForSetAppName,\n rawDefineProperty,\n rawHasOwnProperty,\n removeDomScope,\n getRootContainer,\n} from '../../libs/utils'\nimport {\n appInstanceMap,\n} from '../../create_app'\n\n/**\n * patch window of child app\n * @param appName app name\n * @param microAppWindow microWindow of child app\n * @param sandbox WithSandBox\n * @returns EffectHook\n */\nexport function patchWindow (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: WithSandBoxInterface,\n): CommonEffectHook {\n patchWindowProperty(microAppWindow)\n createProxyWindow(appName, microAppWindow, sandbox)\n return patchWindowEffect(microAppWindow, appName)\n}\n\n/**\n * rewrite special properties of window\n * @param appName app name\n * @param microAppWindow child app microWindow\n */\nfunction patchWindowProperty (\n microAppWindow: microAppWindowType,\n):void {\n const rawWindow = globalEnv.rawWindow\n Object.getOwnPropertyNames(rawWindow)\n .filter((key: string) => {\n return /^on/.test(key) && !SCOPE_WINDOW_ON_EVENT.includes(key)\n })\n .forEach((eventName: string) => {\n const { enumerable, writable, set } = Object.getOwnPropertyDescriptor(rawWindow, eventName) || {\n enumerable: true,\n writable: true,\n }\n rawDefineProperty(microAppWindow, eventName, {\n enumerable,\n configurable: true,\n get: () => rawWindow[eventName],\n set: writable ?? !!set\n ? (value) => { rawWindow[eventName] = value }\n : undefined,\n })\n })\n}\n\n/**\n * create proxyWindow with Proxy(microAppWindow)\n * @param appName app name\n * @param microAppWindow micro app window\n * @param sandbox WithSandBox\n */\nfunction createProxyWindow (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: WithSandBoxInterface,\n): void {\n const rawWindow = globalEnv.rawWindow\n const descriptorTargetMap = new Map<PropertyKey, 'target' | 'rawWindow'>()\n\n const proxyWindow = new Proxy(microAppWindow, {\n get: (target: microAppWindowType, key: PropertyKey): unknown => {\n throttleDeferForSetAppName(appName)\n if (\n Reflect.has(target, key) ||\n (isString(key) && /^__MICRO_APP_/.test(key)) ||\n includes(sandbox.scopeProperties, key)\n ) {\n if (includes(RAW_GLOBAL_TARGET, key)) removeDomScope()\n return Reflect.get(target, key)\n }\n\n return bindFunctionToRawTarget(Reflect.get(rawWindow, key), rawWindow)\n },\n set: (target: microAppWindowType, key: PropertyKey, value: unknown): boolean => {\n if (includes(sandbox.rawWindowScopeKeyList, key)) {\n Reflect.set(rawWindow, key, value)\n } else if (\n // target.hasOwnProperty has been rewritten\n !rawHasOwnProperty.call(target, key) &&\n rawHasOwnProperty.call(rawWindow, key) &&\n !includes(sandbox.scopeProperties, key)\n ) {\n const descriptor = Object.getOwnPropertyDescriptor(rawWindow, key)\n const { configurable, enumerable, writable, set } = descriptor!\n // set value because it can be set\n rawDefineProperty(target, key, {\n value,\n configurable,\n enumerable,\n writable: writable ?? !!set,\n })\n\n sandbox.injectedKeys.add(key)\n } else {\n // all scopeProperties will add to injectedKeys, use for key in window (Proxy.has)\n if (!Reflect.has(target, key) || includes(sandbox.scopeProperties, key)) {\n sandbox.injectedKeys.add(key)\n }\n Reflect.set(target, key, value)\n }\n\n if (\n (\n includes(sandbox.escapeProperties, key) ||\n (\n // TODO: staticEscapeProperties 合并到 escapeProperties\n includes(sandbox.staticEscapeProperties, key) &&\n !Reflect.has(rawWindow, key)\n )\n ) &&\n !includes(sandbox.scopeProperties, key)\n ) {\n !Reflect.has(rawWindow, key) && sandbox.escapeKeys.add(key)\n Reflect.set(rawWindow, key, value)\n }\n\n return true\n },\n has: (target: microAppWindowType, key: PropertyKey): boolean => {\n /**\n * Some keywords, such as Vue, need to meet two conditions at the same time:\n * 1. window.Vue --> undefined\n * 2. 'Vue' in window --> false\n * Issue https://github.com/micro-zoe/micro-app/issues/686\n */\n if (includes(sandbox.scopeProperties, key)) {\n if (sandbox.injectedKeys.has(key)) {\n return Reflect.has(target, key) // true\n }\n return !!target[key] // false\n }\n return Reflect.has(target, key) || Reflect.has(rawWindow, key)\n },\n // Object.getOwnPropertyDescriptor(window, key)\n getOwnPropertyDescriptor: (target: microAppWindowType, key: PropertyKey): PropertyDescriptor|undefined => {\n if (rawHasOwnProperty.call(target, key)) {\n descriptorTargetMap.set(key, 'target')\n return Object.getOwnPropertyDescriptor(target, key)\n }\n\n if (rawHasOwnProperty.call(rawWindow, key)) {\n descriptorTargetMap.set(key, 'rawWindow')\n const descriptor = Object.getOwnPropertyDescriptor(rawWindow, key)\n if (descriptor && !descriptor.configurable) {\n descriptor.configurable = true\n }\n return descriptor\n }\n\n return undefined\n },\n // Object.defineProperty(window, key, Descriptor)\n defineProperty: (target: microAppWindowType, key: PropertyKey, value: PropertyDescriptor): boolean => {\n const from = descriptorTargetMap.get(key)\n if (from === 'rawWindow') {\n return Reflect.defineProperty(rawWindow, key, value)\n }\n return Reflect.defineProperty(target, key, value)\n },\n // Object.getOwnPropertyNames(window)\n ownKeys: (target: microAppWindowType): Array<string | symbol> => {\n return unique(Reflect.ownKeys(rawWindow).concat(Reflect.ownKeys(target)))\n },\n deleteProperty: (target: microAppWindowType, key: PropertyKey): boolean => {\n if (rawHasOwnProperty.call(target, key)) {\n sandbox.injectedKeys.has(key) && sandbox.injectedKeys.delete(key)\n sandbox.escapeKeys.has(key) && Reflect.deleteProperty(rawWindow, key)\n return Reflect.deleteProperty(target, key)\n }\n return true\n },\n })\n\n sandbox.proxyWindow = proxyWindow\n}\n\n/**\n * Rewrite side-effect events\n * @param microAppWindow micro window\n */\nfunction patchWindowEffect (microAppWindow: microAppWindowType, appName: string): CommonEffectHook {\n const eventListenerMap = new Map<string, Set<MicroEventListener>>()\n const sstEventListenerMap = new Map<string, Set<MicroEventListener>>()\n const intervalIdMap = new Map<number, timeInfo>()\n const timeoutIdMap = new Map<number, timeInfo>()\n const {\n rawWindow,\n rawAddEventListener,\n rawRemoveEventListener,\n rawDispatchEvent,\n rawSetInterval,\n rawSetTimeout,\n rawClearInterval,\n rawClearTimeout,\n } = globalEnv\n\n /**\n * All events will bind to microAppElement or rawWindow\n * Some special events, such as popstate、load、unmount、appstate-change、statechange..., bind to microAppElement, others bind to rawWindow\n * NOTE:\n * 1、At first, microAppWindow = new EventTarget(), but it can not compatible with iOS 14 or below, so microAppElement was used instead. (2024.1.22)\n * @param type event name\n * @returns microAppElement/rawWindow\n */\n function getEventTarget (type: string): EventTarget {\n if (SCOPE_WINDOW_EVENT.includes(type) && appInstanceMap.get(appName)?.container) {\n return getRootContainer(appInstanceMap.get(appName)!.container!)\n }\n return rawWindow\n }\n\n /**\n * listener may be null, e.g test-passive\n * TODO:\n * 1. listener 是否需要绑定microAppWindow,否则函数中的this指向原生window\n * 2. 如果this不指向proxyWindow 或 microAppWindow,应该要做处理\n * window.addEventListener.call(非window, type, listener, options)\n */\n microAppWindow.addEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList) {\n listenerList.add(listener)\n } else {\n eventListenerMap.set(type, new Set([listener]))\n }\n listener && (listener.__MICRO_APP_MARK_OPTIONS__ = options)\n rawAddEventListener.call(getEventTarget(type), type, listener, options)\n }\n\n microAppWindow.removeEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList?.size && listenerList.has(listener)) {\n listenerList.delete(listener)\n }\n rawRemoveEventListener.call(getEventTarget(type), type, listener, options)\n }\n\n microAppWindow.dispatchEvent = function (event: Event): boolean {\n return rawDispatchEvent.call(getEventTarget(event?.type), event)\n }\n\n microAppWindow.setInterval = function (\n handler: TimerHandler,\n timeout?: number,\n ...args: any[]\n ): number {\n const intervalId = rawSetInterval.call(rawWindow, handler, timeout, ...args)\n intervalIdMap.set(intervalId, { handler, timeout, args })\n return intervalId\n }\n\n microAppWindow.setTimeout = function (\n handler: TimerHandler,\n timeout?: number,\n ...args: any[]\n ): number {\n const timeoutId = rawSetTimeout.call(rawWindow, handler, timeout, ...args)\n timeoutIdMap.set(timeoutId, { handler, timeout, args })\n return timeoutId\n }\n\n microAppWindow.clearInterval = function (intervalId: number) {\n intervalIdMap.delete(intervalId)\n rawClearInterval.call(rawWindow, intervalId)\n }\n\n microAppWindow.clearTimeout = function (timeoutId: number) {\n timeoutIdMap.delete(timeoutId)\n rawClearTimeout.call(rawWindow, timeoutId)\n }\n\n // reset snapshot data\n const reset = (): void => {\n sstEventListenerMap.clear()\n }\n\n /**\n * NOTE:\n * 1. about timer(events & properties should record & rebuild at all modes, exclude default mode)\n * 2. record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * 4 modes: default-mode、umd-mode、prerender、keep-alive\n * Solution:\n * 1. default-mode(normal): clear events & timers, not record & rebuild anything\n * 2. umd-mode(normal): not clear timers, record & rebuild events\n * 3. prerender/keep-alive(default, umd): not clear timers, record & rebuild events\n */\n const record = (): void => {\n // record window event\n eventListenerMap.forEach((listenerList, type) => {\n if (listenerList.size) {\n const cacheList = sstEventListenerMap.get(type) || []\n sstEventListenerMap.set(type, new Set([...cacheList, ...listenerList]))\n }\n })\n }\n\n // rebuild event and timer before remount app\n const rebuild = (): void => {\n // rebuild window event\n sstEventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n microAppWindow.addEventListener(type, listener, listener?.__MICRO_APP_MARK_OPTIONS__)\n }\n })\n\n reset()\n }\n\n // release all event listener & interval & timeout when unmount app\n const release = (clearTimer: boolean): void => {\n // Clear window binding events\n if (eventListenerMap.size) {\n eventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n rawRemoveEventListener.call(getEventTarget(type), type, listener)\n }\n })\n eventListenerMap.clear()\n }\n\n // default mode(not keep-alive or isPrerender)\n if (clearTimer) {\n intervalIdMap.forEach((_, intervalId: number) => {\n rawClearInterval.call(rawWindow, intervalId)\n })\n\n timeoutIdMap.forEach((_, timeoutId: number) => {\n rawClearTimeout.call(rawWindow, timeoutId)\n })\n\n intervalIdMap.clear()\n timeoutIdMap.clear()\n }\n }\n\n return {\n reset,\n record,\n rebuild,\n release,\n }\n}\n","import type {\n MicroLocation,\n MicroState,\n LocationQuery,\n HandleMicroPathResult,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport {\n assign,\n parseQuery,\n stringifyQuery,\n isString,\n isUndefined,\n isPlainObject,\n createURL,\n} from '../../libs/utils'\nimport {\n appInstanceMap,\n} from '../../create_app'\nimport {\n ROUTER_MODE_LIST,\n DEFAULT_ROUTER_MODE,\n ROUTER_MODE_NATIVE,\n ROUTER_MODE_NATIVE_SCOPE,\n ROUTER_MODE_PURE,\n} from '../../constants'\nimport microApp from '../../micro_app'\n\n// set micro app state to origin state\nexport function setMicroState (\n appName: string,\n microState: MicroState,\n): MicroState {\n if (isRouterModeSearch(appName)) {\n const rawState = globalEnv.rawWindow.history.state\n const additionalState: Record<string, any> = {\n microAppState: assign({}, rawState?.microAppState, {\n [appName]: microState\n })\n }\n\n // create new state object\n return assign({}, rawState, additionalState)\n }\n\n return microState\n}\n\n// delete micro app state form origin state\nexport function removeMicroState (appName: string, rawState: MicroState): MicroState {\n if (isRouterModeSearch(appName)) {\n if (isPlainObject(rawState?.microAppState)) {\n if (!isUndefined(rawState.microAppState[appName])) {\n delete rawState.microAppState[appName]\n }\n if (!Object.keys(rawState.microAppState).length) {\n delete rawState.microAppState\n }\n }\n\n return assign({}, rawState)\n }\n\n return rawState\n}\n\n// get micro app state form origin state\nexport function getMicroState (appName: string): MicroState {\n const rawState = globalEnv.rawWindow.history.state\n\n if (isRouterModeSearch(appName)) {\n return rawState?.microAppState?.[appName] || null\n }\n\n return rawState\n}\n\nconst ENC_AD_RE = /&/g // %M1\nconst ENC_EQ_RE = /=/g // %M2\nconst DEC_AD_RE = /%M1/g // &\nconst DEC_EQ_RE = /%M2/g // =\n\n// encode path with special symbol\nexport function encodeMicroPath (path: string): string {\n return encodeURIComponent(commonDecode(path).replace(ENC_AD_RE, '%M1').replace(ENC_EQ_RE, '%M2'))\n}\n\n// decode path\nexport function decodeMicroPath (path: string): string {\n return commonDecode(path).replace(DEC_AD_RE, '&').replace(DEC_EQ_RE, '=')\n}\n\n// Recursively resolve address\nfunction commonDecode (path: string): string {\n try {\n const decPath = decodeURIComponent(path)\n if (path === decPath || DEC_AD_RE.test(decPath) || DEC_EQ_RE.test(decPath)) return decPath\n return commonDecode(decPath)\n } catch {\n return path\n }\n}\n\n// Format the query parameter key to prevent conflicts with the original parameters\nfunction formatQueryAppName (appName: string) {\n // return `app-${appName}`\n return appName\n}\n\n/**\n * Get app fullPath from browser url\n * @param appName app.name\n */\nexport function getMicroPathFromURL (appName: string): string | null {\n // TODO: pure模式从state中获取地址\n if (isRouterModePure(appName)) return null\n const rawLocation = globalEnv.rawWindow.location\n if (isRouterModeSearch(appName)) {\n const queryObject = getQueryObjectFromURL(rawLocation.search, rawLocation.hash)\n const microPath = queryObject.hashQuery?.[formatQueryAppName(appName)] || queryObject.searchQuery?.[formatQueryAppName(appName)]\n return isString(microPath) ? decodeMicroPath(microPath) : null\n }\n return rawLocation.pathname + rawLocation.search + rawLocation.hash\n}\n\n/**\n * Attach child app fullPath to browser url\n * @param appName app.name\n * @param targetLocation location of child app or rawLocation of window\n */\nexport function setMicroPathToURL (appName: string, targetLocation: MicroLocation): HandleMicroPathResult {\n const targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n let isAttach2Hash = false\n if (isRouterModeSearch(appName)) {\n let { pathname, search, hash } = globalEnv.rawWindow.location\n const queryObject = getQueryObjectFromURL(search, hash)\n const encodedMicroPath = encodeMicroPath(targetFullPath)\n\n /**\n * Is parent is hash router\n * In fact, this is not true. It just means that the parameter is added to the hash\n */\n // If hash exists and search does not exist, it is considered as a hash route\n if (hash && !search) {\n isAttach2Hash = true\n if (queryObject.hashQuery) {\n queryObject.hashQuery[formatQueryAppName(appName)] = encodedMicroPath\n } else {\n queryObject.hashQuery = {\n [formatQueryAppName(appName)]: encodedMicroPath\n }\n }\n const baseHash = hash.includes('?') ? hash.slice(0, hash.indexOf('?') + 1) : hash + '?'\n hash = baseHash + stringifyQuery(queryObject.hashQuery)\n } else {\n if (queryObject.searchQuery) {\n queryObject.searchQuery[formatQueryAppName(appName)] = encodedMicroPath\n } else {\n queryObject.searchQuery = {\n [formatQueryAppName(appName)]: encodedMicroPath\n }\n }\n search = '?' + stringifyQuery(queryObject.searchQuery)\n }\n\n return {\n fullPath: pathname + search + hash,\n isAttach2Hash,\n }\n }\n\n return {\n fullPath: targetFullPath,\n isAttach2Hash,\n }\n}\n\n/**\n * Delete child app fullPath from browser url\n * @param appName app.name\n * @param targetLocation target Location, default is rawLocation\n */\nexport function removeMicroPathFromURL (appName: string, targetLocation?: MicroLocation): HandleMicroPathResult {\n let { pathname, search, hash } = targetLocation || globalEnv.rawWindow.location\n let isAttach2Hash = false\n\n if (isRouterModeSearch(appName)) {\n const queryObject = getQueryObjectFromURL(search, hash)\n if (queryObject.hashQuery?.[formatQueryAppName(appName)]) {\n isAttach2Hash = true\n delete queryObject.hashQuery?.[formatQueryAppName(appName)]\n const hashQueryStr = stringifyQuery(queryObject.hashQuery)\n hash = hash.slice(0, hash.indexOf('?') + Number(Boolean(hashQueryStr))) + hashQueryStr\n } else if (queryObject.searchQuery?.[formatQueryAppName(appName)]) {\n delete queryObject.searchQuery?.[formatQueryAppName(appName)]\n const searchQueryStr = stringifyQuery(queryObject.searchQuery)\n search = searchQueryStr ? '?' + searchQueryStr : ''\n }\n }\n\n return {\n fullPath: pathname + search + hash,\n isAttach2Hash,\n }\n}\n\n/**\n * Format search, hash to object\n */\nfunction getQueryObjectFromURL (search: string, hash: string): LocationQuery {\n const queryObject: LocationQuery = {}\n\n if (search !== '' && search !== '?') {\n queryObject.searchQuery = parseQuery(search.slice(1))\n }\n\n if (hash.includes('?')) {\n queryObject.hashQuery = parseQuery(hash.slice(hash.indexOf('?') + 1))\n }\n\n return queryObject\n}\n\n/**\n * get microApp path from browser URL without hash\n */\nexport function getNoHashMicroPathFromURL (appName: string, baseUrl: string): string {\n const microPath = getMicroPathFromURL(appName)\n if (!microPath) return ''\n const formatLocation = createURL(microPath, baseUrl)\n return formatLocation.origin + formatLocation.pathname + formatLocation.search\n}\n\n/**\n * Effect app is an app that can perform route navigation\n * NOTE: Invalid app action\n * 1. prevent update browser url, dispatch popStateEvent, reload browser\n * 2. It can update path with pushState/replaceState\n * 3. Can not update path outside (with router api)\n * 3. Can not update path by location\n */\nexport function isEffectiveApp (appName: string): boolean {\n const app = appInstanceMap.get(appName)\n /**\n * !!(app && !app.isPrefetch && !app.isHidden())\n * NOTE: 隐藏的keep-alive应用暂时不作为无效应用,原因如下\n * 1、隐藏后才执行去除浏览器上的微应用的路由信息的操作,导致微应用的路由信息无法去除\n * 2、如果保持隐藏应用内部正常跳转,阻止同步路由信息到浏览器,这样理论上是好的,但是对于location跳转改如何处理?location跳转是基于修改浏览器地址后发送popstate事件实现的,所以应该是在隐藏后不支持通过location进行跳转\n */\n return !!(app && !app.isPrefetch)\n}\n\n// router mode is search\nexport function isRouterModeSearch (appName: string): boolean {\n const app = appInstanceMap.get(appName)\n return !!(app && app.sandBox && app.routerMode === DEFAULT_ROUTER_MODE)\n}\n\n// router mode is history\nexport function isRouterModeNative (appName: string): boolean {\n const app = appInstanceMap.get(appName)\n return !!(app && app.sandBox && app.routerMode === ROUTER_MODE_NATIVE)\n}\n\n// router mode is disable\nexport function isRouterModeNativeScope (appName: string): boolean {\n const app = appInstanceMap.get(appName)\n return !!(app && app.sandBox && app.routerMode === ROUTER_MODE_NATIVE_SCOPE)\n}\n\n// router mode is pure\nexport function isRouterModePure (appName: string): boolean {\n const app = appInstanceMap.get(appName)\n return !!(app && app.sandBox && app.routerMode === ROUTER_MODE_PURE)\n}\n\n/**\n * router mode is history or disable\n */\nexport function isRouterModeCustom (appName: string): boolean {\n return isRouterModeNative(appName) || isRouterModeNativeScope(appName)\n}\n\n/**\n * get memory router mode of child app\n * NOTE:\n * 1. if microAppElement exists, it means the app render by the micro-app element\n * 2. if microAppElement not exists, it means it is prerender app\n * @param mode native config\n * @param inlineDisableMemoryRouter disable-memory-router set by micro-app element or prerender\n * @returns router mode\n */\nexport function getRouterMode (\n mode: string | null | void,\n inlineDisableMemoryRouter?: boolean,\n): string {\n /**\n * compatible with disable-memory-router in older versions\n * if disable-memory-router is true, router-mode will be disable\n * Priority:\n * inline disable-memory-router > inline router-mode > global disable-memory-router > global router-mode\n */\n const routerMode = (\n (inlineDisableMemoryRouter && ROUTER_MODE_NATIVE) ||\n mode ||\n (microApp.options['disable-memory-router'] && ROUTER_MODE_NATIVE) ||\n microApp.options['router-mode'] ||\n DEFAULT_ROUTER_MODE\n )\n return ROUTER_MODE_LIST.includes(routerMode) ? routerMode : DEFAULT_ROUTER_MODE\n}\n","import type {\n MicroLocation,\n PopStateListener,\n MicroPopStateEvent,\n microAppWindowType,\n} from '@micro-app/types'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} from '../../create_app'\nimport {\n getActiveApps,\n} from '../../micro_app'\nimport {\n getMicroPathFromURL,\n getMicroState,\n isEffectiveApp,\n} from './core'\nimport {\n updateMicroLocation,\n} from './location'\nimport {\n removeDomScope,\n isFunction,\n} from '../../libs/utils'\nimport globalEnv from '../../libs/global_env'\n\n/**\n * dispatch PopStateEvent & HashChangeEvent to child app\n * each child app will listen for popstate event when sandbox start\n * and release it when sandbox stop\n * @param appName app name\n * @returns release callback\n */\nexport function addHistoryListener (appName: string): CallableFunction {\n const rawWindow = globalEnv.rawWindow\n // handle popstate event and distribute to child app\n const popStateHandler: PopStateListener = (e: MicroPopStateEvent): void => {\n /**\n * 1. unmount app & hidden keep-alive app will not receive popstate event\n * 2. filter out onlyForBrowser\n */\n if (\n getActiveApps({\n excludeHiddenApp: true,\n excludePreRender: true,\n }).includes(appName) &&\n !e.onlyForBrowser\n ) {\n updateMicroLocationWithEvent(appName, getMicroPathFromURL(appName))\n }\n }\n\n rawWindow.addEventListener('popstate', popStateHandler)\n\n return () => {\n rawWindow.removeEventListener('popstate', popStateHandler)\n }\n}\n\n/**\n * Effect: use to trigger child app jump\n * Actions:\n * 1. update microLocation with target path\n * 2. dispatch popStateEvent & hashChangeEvent\n * @param appName app name\n * @param targetFullPath target path of child app\n */\nexport function updateMicroLocationWithEvent (\n appName: string,\n targetFullPath: string | null,\n): void {\n const app = appInstanceMap.get(appName)!\n const proxyWindow = app.sandBox!.proxyWindow\n const microAppWindow = app.sandBox!.microAppWindow\n let isHashChange = false\n // for hashChangeEvent\n const oldHref = proxyWindow.location.href\n // Do not attach micro state to url when targetFullPath is empty\n if (targetFullPath) {\n const oldHash = proxyWindow.location.hash\n updateMicroLocation(appName, targetFullPath, microAppWindow.location as MicroLocation)\n isHashChange = proxyWindow.location.hash !== oldHash\n }\n\n // dispatch formatted popStateEvent to child\n dispatchPopStateEventToMicroApp(appName, proxyWindow, microAppWindow)\n\n // dispatch formatted hashChangeEvent to child when hash change\n if (isHashChange) dispatchHashChangeEventToMicroApp(appName, proxyWindow, microAppWindow, oldHref)\n\n // clear element scope before trigger event of next app\n removeDomScope()\n}\n\n/**\n * dispatch formatted popstate event to microApp\n * @param appName app name\n * @param proxyWindow sandbox window\n * @param eventState history.state\n */\nexport function dispatchPopStateEventToMicroApp (\n appName: string,\n proxyWindow: WindowProxy,\n microAppWindow: microAppWindowType,\n): void {\n /**\n * TODO: test\n * angular14 takes e.type as type judgment\n * when e.type is popstate-appName popstate event will be invalid\n */\n // Object.defineProperty(newPopStateEvent, 'type', {\n // value: 'popstate',\n // writable: true,\n // configurable: true,\n // enumerable: true,\n // })\n // create PopStateEvent named popstate-appName with sub app state\n const newPopStateEvent = new PopStateEvent(\n 'popstate',\n { state: getMicroState(appName) }\n )\n\n microAppWindow.dispatchEvent(newPopStateEvent)\n\n if (!isIframeSandbox(appName)) {\n // call function window.onpopstate if it exists\n isFunction(proxyWindow.onpopstate) && proxyWindow.onpopstate(newPopStateEvent)\n }\n}\n\n/**\n * dispatch formatted hashchange event to microApp\n * @param appName app name\n * @param proxyWindow sandbox window\n * @param oldHref old href\n */\nexport function dispatchHashChangeEventToMicroApp (\n appName: string,\n proxyWindow: WindowProxy,\n microAppWindow: microAppWindowType,\n oldHref: string,\n): void {\n const newHashChangeEvent = new HashChangeEvent(\n 'hashchange',\n {\n newURL: proxyWindow.location.href,\n oldURL: oldHref,\n }\n )\n\n microAppWindow.dispatchEvent(newHashChangeEvent)\n\n if (!isIframeSandbox(appName)) {\n // call function window.onhashchange if it exists\n isFunction(proxyWindow.onhashchange) && proxyWindow.onhashchange(newHashChangeEvent)\n }\n}\n\n/**\n * dispatch native PopStateEvent, simulate location behavior\n * @param onlyForBrowser only dispatch PopStateEvent to browser\n */\nfunction dispatchNativePopStateEvent (onlyForBrowser: boolean): void {\n const event = new PopStateEvent('popstate', { state: null }) as MicroPopStateEvent\n if (onlyForBrowser) event.onlyForBrowser = true\n globalEnv.rawWindow.dispatchEvent(event)\n}\n\n/**\n * dispatch hashchange event to browser\n * @param oldHref old href of rawWindow.location\n */\nfunction dispatchNativeHashChangeEvent (oldHref: string): void {\n const newHashChangeEvent = new HashChangeEvent(\n 'hashchange',\n {\n newURL: globalEnv.rawWindow.location.href,\n oldURL: oldHref,\n }\n )\n\n globalEnv.rawWindow.dispatchEvent(newHashChangeEvent)\n}\n\n/**\n * dispatch popstate & hashchange event to browser\n * @param appName app.name\n * @param onlyForBrowser only dispatch event to browser\n * @param oldHref old href of rawWindow.location\n */\nexport function dispatchNativeEvent (\n appName: string,\n onlyForBrowser: boolean,\n oldHref?: string,\n): void {\n // clear element scope before dispatch global event\n removeDomScope()\n if (isEffectiveApp(appName)) {\n dispatchNativePopStateEvent(onlyForBrowser)\n if (oldHref) {\n dispatchNativeHashChangeEvent(oldHref)\n }\n }\n}\n","/* eslint-disable no-void */\nimport type {\n MicroState,\n MicroLocation,\n MicroHistory,\n HistoryProxyValue,\n HandleMicroPathResult,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport {\n isString,\n createURL,\n isPlainObject,\n isURL,\n assign,\n removeDomScope,\n} from '../../libs/utils'\nimport {\n setMicroPathToURL,\n setMicroState,\n getMicroState,\n getMicroPathFromURL,\n isEffectiveApp,\n isRouterModePure,\n isRouterModeSearch,\n} from './core'\nimport { dispatchNativeEvent } from './event'\nimport { updateMicroLocation } from './location'\nimport bindFunctionToRawTarget from '../bind_function'\nimport { getActiveApps } from '../../micro_app'\nimport { appInstanceMap, isIframeSandbox } from '../../create_app'\n\n/**\n * create proxyHistory for microApp\n * MDN https://developer.mozilla.org/en-US/docs/Web/API/History\n * @param appName app name\n * @param microLocation microApp location(with: proxyLocation iframe: iframeWindow.location)\n */\nexport function createMicroHistory (appName: string, microLocation: MicroLocation): MicroHistory {\n const rawHistory = globalEnv.rawWindow.history\n function getMicroHistoryMethod (methodName: string): CallableFunction {\n return function (...rests: any[]): void {\n // TODO: 测试iframe的URL兼容isURL的情况\n if (isString(rests[2]) || isURL(rests[2])) {\n const targetLocation = createURL(rests[2], microLocation.href)\n const targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n if (!isRouterModePure(appName)) {\n navigateWithNativeEvent(\n appName,\n methodName,\n setMicroPathToURL(appName, targetLocation),\n true,\n setMicroState(appName, rests[0]),\n rests[1],\n )\n }\n if (targetFullPath !== microLocation.fullPath) {\n updateMicroLocation(appName, targetFullPath, microLocation)\n }\n appInstanceMap.get(appName)?.sandBox.updateIframeBase?.()\n } else {\n nativeHistoryNavigate(appName, methodName, rests[2], rests[0], rests[1])\n }\n }\n }\n\n const pushState = getMicroHistoryMethod('pushState')\n const replaceState = getMicroHistoryMethod('replaceState')\n\n if (isIframeSandbox(appName)) return { pushState, replaceState } as MicroHistory\n\n return new Proxy(rawHistory, {\n get (target: History, key: PropertyKey): HistoryProxyValue {\n if (key === 'state') {\n return getMicroState(appName)\n } else if (key === 'pushState') {\n return pushState\n } else if (key === 'replaceState') {\n return replaceState\n }\n return bindFunctionToRawTarget<History, HistoryProxyValue>(Reflect.get(target, key), target, 'HISTORY')\n },\n set (target: History, key: PropertyKey, value: unknown): boolean {\n Reflect.set(target, key, value)\n /**\n * If the set() method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown.\n * e.g. history.state = {}\n * TypeError: 'set' on proxy: trap returned false for property 'state'\n */\n return true\n }\n })\n}\n\n/**\n * navigate to new path base on native method of history\n * @param appName app.name\n * @param methodName pushState/replaceState\n * @param fullPath full path\n * @param state history.state, default is null\n * @param title history.title, default is ''\n */\nexport function nativeHistoryNavigate (\n appName: string,\n methodName: string,\n fullPath: string,\n state: unknown = null,\n title: unknown = '',\n): void {\n if (isEffectiveApp(appName)) {\n const method = methodName === 'pushState' ? globalEnv.rawPushState : globalEnv.rawReplaceState\n method.call(globalEnv.rawWindow.history, state, title, fullPath)\n }\n}\n\n/**\n * Navigate to new path, and dispatch native popStateEvent/hashChangeEvent to browser\n * Use scenes:\n * 1. mount/unmount through attachRouteToBrowserURL with limited popstateEvent\n * 2. proxyHistory.pushState/replaceState with limited popstateEvent\n * 3. api microApp.router.push/replace\n * 4. proxyLocation.hash = xxx\n * NOTE:\n * 1. hidden keep-alive app can jump internally, but will not synchronize to browser\n * @param appName app.name\n * @param methodName pushState/replaceState\n * @param result result of add/remove microApp path on browser url\n * @param onlyForBrowser only dispatch event to browser\n * @param state history.state, not required\n * @param title history.title, not required\n */\nexport function navigateWithNativeEvent (\n appName: string,\n methodName: string,\n result: HandleMicroPathResult,\n onlyForBrowser: boolean,\n state?: unknown,\n title?: string,\n): void {\n if (isEffectiveApp(appName)) {\n const rawLocation = globalEnv.rawWindow.location\n const oldFullPath = rawLocation.pathname + rawLocation.search + rawLocation.hash\n // oldHref use for hashChangeEvent of base app\n const oldHref = result.isAttach2Hash && oldFullPath !== result.fullPath ? rawLocation.href : null\n // navigate with native history method\n nativeHistoryNavigate(appName, methodName, result.fullPath, state, title)\n /**\n * TODO:\n * 1. 如果所有模式统一发送popstate事件,则isRouterModeSearch(appName)要去掉\n * 2. 如果发送事件,则会导致vue router-view :key='router.path'绑定,无限卸载应用,死循环\n */\n if (oldFullPath !== result.fullPath && isRouterModeSearch(appName)) {\n dispatchNativeEvent(appName, onlyForBrowser, oldHref)\n }\n }\n}\n\n/**\n * update browser url when mount/unmount/hidden/show/attachToURL/attachAllToURL\n * just attach microRoute info to browser, dispatch event to base app(exclude child)\n * @param appName app.name\n * @param result result of add/remove microApp path on browser url\n * @param state history.state\n */\nexport function attachRouteToBrowserURL (\n appName: string,\n result: HandleMicroPathResult,\n state: MicroState,\n): void {\n navigateWithNativeEvent(appName, 'replaceState', result, true, state)\n}\n\n/**\n * When path is same, keep the microAppState in history.state\n * Fix bug of missing microAppState when base app is next.js or angular\n * @param method history.pushState/replaceState\n */\nfunction reWriteHistoryMethod (method: History['pushState' | 'replaceState']): CallableFunction {\n const rawWindow = globalEnv.rawWindow\n return function (...rests: [data: any, unused: string, url?: string]): void {\n if (\n rawWindow.history.state?.microAppState &&\n (!isPlainObject(rests[0]) || !rests[0].microAppState) &&\n (isString(rests[2]) || isURL(rests[2]))\n ) {\n const currentHref = rawWindow.location.href\n const targetLocation = createURL(rests[2], currentHref)\n if (targetLocation.href === currentHref) {\n rests[0] = assign({}, rests[0], {\n microAppState: rawWindow.history.state.microAppState,\n })\n }\n }\n\n method.apply(rawWindow.history, rests)\n /**\n * Attach child router info to browser url when base app navigate with pushState/replaceState\n * NOTE:\n * 1. Exec after apply pushState/replaceState\n * 2. Unable to catch when base app navigate with location\n * 3. When in nest app, rawPushState/rawReplaceState has been modified by parent\n */\n getActiveApps({\n excludeHiddenApp: true,\n excludePreRender: true,\n }).forEach(appName => {\n if (isRouterModeSearch(appName) && !getMicroPathFromURL(appName)) {\n const app = appInstanceMap.get(appName)!\n attachRouteToBrowserURL(\n appName,\n setMicroPathToURL(appName, app.sandBox.proxyWindow.location as MicroLocation),\n setMicroState(appName, getMicroState(appName)),\n )\n }\n })\n // fix bug for nest app\n removeDomScope()\n }\n}\n\n/**\n * rewrite history.pushState/replaceState\n * used to fix the problem that the microAppState maybe missing when mainApp navigate to same path\n * e.g: when nextjs, angular receive popstate event, they will use history.replaceState to update browser url with a new state object\n */\nexport function patchHistory (): void {\n const rawWindow = globalEnv.rawWindow\n rawWindow.history.pushState = reWriteHistoryMethod(\n globalEnv.rawPushState,\n )\n rawWindow.history.replaceState = reWriteHistoryMethod(\n globalEnv.rawReplaceState,\n )\n}\n\nexport function releasePatchHistory (): void {\n const rawWindow = globalEnv.rawWindow\n rawWindow.history.pushState = globalEnv.rawPushState\n rawWindow.history.replaceState = globalEnv.rawReplaceState\n}\n","import type {\n Func,\n Router,\n RouterTarget,\n navigationMethod,\n MicroLocation,\n RouterGuard,\n GuardLocation,\n AccurateGuard,\n SetDefaultPageOptions,\n AttachAllToURLParam,\n AppInterface,\n} from '@micro-app/types'\nimport {\n encodeMicroPath,\n decodeMicroPath,\n setMicroPathToURL,\n setMicroState,\n getMicroState,\n getMicroPathFromURL,\n isRouterModeCustom,\n isRouterModeSearch,\n isRouterModePure,\n} from './core'\nimport {\n logError,\n logWarn,\n formatAppName,\n createURL,\n isFunction,\n isPlainObject,\n useSetRecord,\n useMapRecord,\n requestIdleCallback,\n isString,\n noopFalse,\n removeDomScope,\n isObject,\n} from '../../libs/utils'\nimport { appInstanceMap } from '../../create_app'\nimport { getActiveApps } from '../../micro_app'\nimport globalEnv from '../../libs/global_env'\nimport { navigateWithNativeEvent, attachRouteToBrowserURL } from './history'\nimport bindFunctionToRawTarget from '../bind_function'\nimport { updateMicroLocationWithEvent } from './event'\n\nexport interface RouterApi {\n router: Router,\n executeNavigationGuard: (appName: string, to: GuardLocation, from: GuardLocation) => void\n clearRouterWhenUnmount: (appName: string) => void\n}\n\nexport interface CreteBaseRouter {\n setBaseAppRouter (baseRouter: unknown): void\n getBaseAppRouter(): unknown\n}\n\nexport interface CreateDefaultPage {\n setDefaultPage(options: SetDefaultPageOptions): () => boolean\n removeDefaultPage(appName: string): boolean\n getDefaultPage(key: PropertyKey): string | void\n}\n\nfunction createRouterApi (): RouterApi {\n /**\n * common handler for router.push/router.replace method\n * @param appName app name\n * @param methodName replaceState/pushState\n * @param targetLocation target location\n * @param state to.state\n */\n function navigateWithRawHistory (\n appName: string,\n methodName: string,\n targetLocation: MicroLocation,\n state: unknown,\n ): void {\n navigateWithNativeEvent(\n appName,\n methodName,\n setMicroPathToURL(\n appName,\n targetLocation,\n ),\n false,\n setMicroState(\n appName,\n state ?? null,\n ),\n )\n // clear element scope after navigate\n removeDomScope()\n }\n\n /**\n * navigation handler\n * @param appName app.name\n * @param app app instance\n * @param to router target options\n * @param replace use router.replace?\n */\n function handleNavigate (\n appName: string,\n app: AppInterface,\n to: RouterTarget,\n replace: boolean,\n ): void {\n const microLocation = app.sandBox!.proxyWindow.location as MicroLocation\n const targetLocation = createURL(to.path, microLocation.href)\n // Only get path data, even if the origin is different from microApp\n const currentFullPath = microLocation.pathname + microLocation.search + microLocation.hash\n const targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n if (currentFullPath !== targetFullPath || getMicroPathFromURL(appName) !== targetFullPath) {\n if (!isRouterModePure(appName)) {\n const methodName = (replace && to.replace !== false) || to.replace === true ? 'replaceState' : 'pushState'\n navigateWithRawHistory(appName, methodName, targetLocation, to.state)\n }\n /**\n * TODO:\n * 1. 关闭虚拟路由的跳转地址不同:baseRoute + 子应用地址,文档中要说明\n * 2. 关闭虚拟路由时跳转方式不同:1、基座跳转但不发送popstate事件 2、控制子应用更新location,内部发送popstate事件。\n * 核心思路:减小对基座的影响(子应用跳转不向基座发送popstate事件,其他操作一致),但这是必要的吗,只是多了一个触发popstate的操作\n * 路由优化方案有两种:\n * 1、减少对基座的影响,主要是解决vue循环刷新的问题\n * 2、全局发送popstate事件,解决主、子都是vue3的冲突问题\n * 两者选一个吧,如果选2,则下面这两行代码可以去掉\n * NOTE1: history和search模式采用2,这样可以解决vue3的问题,custom采用1,避免vue循环刷新的问题,这样在用户出现问题时各有解决方案。但反过来说,每种方案又分别导致另外的问题,不统一,导致复杂度增高\n * NOTE2: 关闭虚拟路由,同时发送popstate事件还是无法解决vue3的问题(毕竟history.state理论上还是会冲突),那么就没必要发送popstate事件了。\n */\n if (isRouterModeCustom(appName) || isRouterModePure(appName)) {\n updateMicroLocationWithEvent(appName, targetFullPath)\n }\n }\n }\n\n /**\n * create method of router.push/replace\n * NOTE:\n * 1. The same fullPath will be blocked\n * 2. name & path is required\n * 3. path is fullPath except for the domain (the domain can be taken, but not valid)\n * @param replace use router.replace?\n */\n function createNavigationMethod (replace: boolean): navigationMethod {\n return function (to: RouterTarget): Promise<void> {\n return new Promise((resolve, reject) => {\n const appName = formatAppName(to.name)\n if (appName && isString(to.path)) {\n /**\n * active apps, exclude prerender app or hidden keep-alive app\n * NOTE:\n * 1. prerender app or hidden keep-alive app clear and record popstate event, so we cannot control app jump through the API\n * 2. disable memory-router\n */\n /**\n * TODO: 子应用开始渲染但是还没渲染完成\n * 1、调用跳转改如何处理\n * 2、iframe的沙箱还没初始化时执行跳转报错,如何处理。。。\n * 3、hidden app 是否支持跳转\n */\n if (getActiveApps({ excludeHiddenApp: true, excludePreRender: true }).includes(appName)) {\n const app = appInstanceMap.get(appName)!\n resolve(app.sandBox.sandboxReady.then(() => handleNavigate(appName, app, to, replace)))\n } else {\n reject(logError('navigation failed, app does not exist or is inactive'))\n }\n\n // /**\n // * app not exit or unmounted, update browser URL with replaceState\n // * use base app location.origin as baseURL\n // * 应用不存在或已卸载,依然使用replaceState来更新浏览器地址 -- 不合理\n // */\n // /**\n // * TODO: 应用还没渲染或已经卸载最好不要支持跳转了,我知道这是因为解决一些特殊场景,但这么做是非常反直觉的\n // * 并且在新版本中有多种路由模式,如果应用不存在,我们根本无法知道是哪种模式,那么这里的操作就无意义了。\n // */\n // const rawLocation = globalEnv.rawWindow.location\n // const targetLocation = createURL(to.path, rawLocation.origin)\n // const targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n // if (getMicroPathFromURL(appName) !== targetFullPath) {\n // navigateWithRawHistory(\n // appName,\n // to.replace === false ? 'pushState' : 'replaceState',\n // targetLocation,\n // to.state,\n // )\n // }\n } else {\n reject(logError(`navigation failed, name & path are required when use router.${replace ? 'replace' : 'push'}`))\n }\n })\n }\n }\n\n // create method of router.go/back/forward\n function createRawHistoryMethod (methodName: string): Func {\n return function (...rests: unknown[]): void {\n return globalEnv.rawWindow.history[methodName](...rests)\n }\n }\n\n const beforeGuards = useSetRecord<RouterGuard>()\n const afterGuards = useSetRecord<RouterGuard>()\n\n /**\n * run all of beforeEach/afterEach guards\n * NOTE:\n * 1. Modify browser url first, and then run guards,\n * consistent with the browser forward & back button\n * 2. Prevent the element binding\n * @param appName app name\n * @param to target location\n * @param from old location\n * @param guards guards list\n */\n function runGuards (\n appName: string,\n to: GuardLocation,\n from: GuardLocation,\n guards: Set<RouterGuard>,\n ) {\n // clear element scope before execute function of parent\n removeDomScope()\n for (const guard of guards) {\n if (isFunction(guard)) {\n guard(to, from, appName)\n } else if (isPlainObject(guard) && isFunction((guard as AccurateGuard)[appName])) {\n guard[appName](to, from)\n }\n }\n }\n\n /**\n * global hook for router\n * update router information base on microLocation\n * @param appName app name\n * @param microLocation location of microApp\n */\n function executeNavigationGuard (\n appName: string,\n to: GuardLocation,\n from: GuardLocation,\n ): void {\n router.current.set(appName, to)\n\n runGuards(appName, to, from, beforeGuards.list())\n\n requestIdleCallback(() => {\n runGuards(appName, to, from, afterGuards.list())\n })\n }\n\n function clearRouterWhenUnmount (appName: string): void {\n router.current.delete(appName)\n }\n\n /**\n * NOTE:\n * 1. app not exits\n * 2. sandbox is disabled\n * 3. router mode is custom\n */\n function commonHandlerForAttachToURL (appName: string): void {\n if (isRouterModeSearch(appName)) {\n const app = appInstanceMap.get(appName)!\n attachRouteToBrowserURL(\n appName,\n setMicroPathToURL(appName, app.sandBox.proxyWindow.location as MicroLocation),\n setMicroState(appName, getMicroState(appName)),\n )\n }\n }\n\n /**\n * Attach specified active app router info to browser url\n * @param appName app name\n */\n function attachToURL (appName: string): void {\n appName = formatAppName(appName)\n if (appName && getActiveApps().includes(appName)) {\n commonHandlerForAttachToURL(appName)\n }\n }\n\n /**\n * Attach all active app router info to browser url\n * @param includeHiddenApp include hidden keep-alive app\n * @param includePreRender include preRender app\n */\n function attachAllToURL ({\n includeHiddenApp = false,\n includePreRender = false,\n }: AttachAllToURLParam): void {\n getActiveApps({\n excludeHiddenApp: !includeHiddenApp,\n excludePreRender: !includePreRender,\n }).forEach(appName => commonHandlerForAttachToURL(appName))\n }\n\n function createDefaultPageApi (): CreateDefaultPage {\n // defaultPage data\n const defaultPageRecord = useMapRecord<string>()\n\n /**\n * defaultPage only effect when mount, and has lower priority than query on browser url\n * SetDefaultPageOptions {\n * @param name app name\n * @param path page path\n * }\n */\n function setDefaultPage (options: SetDefaultPageOptions): () => boolean {\n const appName = formatAppName(options.name)\n if (!appName || !options.path) {\n if (__DEV__) {\n if (!appName) {\n logWarn(`setDefaultPage: invalid appName \"${appName}\"`)\n } else {\n logWarn('setDefaultPage: path is required')\n }\n }\n return noopFalse\n }\n\n return defaultPageRecord.add(appName, options.path)\n }\n\n function removeDefaultPage (appName: string): boolean {\n appName = formatAppName(appName)\n if (!appName) return false\n\n return defaultPageRecord.delete(appName)\n }\n\n return {\n setDefaultPage,\n removeDefaultPage,\n getDefaultPage: defaultPageRecord.get,\n }\n }\n\n function createBaseRouterApi (): CreteBaseRouter {\n /**\n * Record base app router, let child app control base app navigation\n */\n let baseRouterProxy: unknown = null\n function setBaseAppRouter (baseRouter: unknown): void {\n if (isObject(baseRouter)) {\n baseRouterProxy = new Proxy(baseRouter, {\n get (target: History, key: PropertyKey): unknown {\n removeDomScope()\n return bindFunctionToRawTarget(Reflect.get(target, key), target, 'BASEROUTER')\n },\n set (target: History, key: PropertyKey, value: unknown): boolean {\n Reflect.set(target, key, value)\n return true\n }\n })\n } else if (__DEV__) {\n logWarn('setBaseAppRouter: Invalid base router')\n }\n }\n\n return {\n setBaseAppRouter,\n getBaseAppRouter: () => baseRouterProxy,\n }\n }\n\n // Router API for developer\n const router: Router = {\n current: new Map<string, MicroLocation>(),\n encode: encodeMicroPath,\n decode: decodeMicroPath,\n push: createNavigationMethod(false),\n replace: createNavigationMethod(true),\n go: createRawHistoryMethod('go'),\n back: createRawHistoryMethod('back'),\n forward: createRawHistoryMethod('forward'),\n beforeEach: beforeGuards.add,\n afterEach: afterGuards.add,\n attachToURL,\n attachAllToURL,\n ...createDefaultPageApi(),\n ...createBaseRouterApi(),\n }\n\n return {\n router,\n executeNavigationGuard,\n clearRouterWhenUnmount,\n }\n}\n\nexport const {\n router,\n executeNavigationGuard,\n clearRouterWhenUnmount,\n} = createRouterApi()\n","export const escape2RawWindowKeys = [\n 'getComputedStyle',\n 'visualViewport',\n 'matchMedia',\n // 'DOMParser',\n 'ResizeObserver',\n 'IntersectionObserver',\n // 'dispatchEvent',\n]\n\nexport const escape2RawWindowRegExpKeys = [\n /animationFrame$/i,\n /mutationObserver$/i,\n /height$|width$/i,\n /offset$/i,\n // /event$/i,\n /selection$/i,\n /^range/i,\n /^screen/i,\n /^scroll/i,\n /X$|Y$/,\n // /^(?:HTML\\w*)?Element$/,\n]\n\nexport const uniqueDocumentElement = [\n 'body',\n 'head',\n 'html',\n 'title',\n]\n\nexport const hijackMicroLocationKeys = [\n 'host',\n 'hostname',\n 'port',\n 'protocol',\n 'origin',\n]\n\n// 有shadowRoot则代理到shadowRoot否则代理到原生document上 (属性)\nexport const proxy2RawDocOrShadowKeys = [\n 'childElementCount',\n 'children',\n 'firstElementChild',\n 'firstChild',\n 'lastElementChild',\n 'activeElement', // Element not has, document or shadowRoot has\n 'fullscreenElement', // Element not has, document or shadowRoot has\n 'pictureInPictureElement', // Element not has, document or shadowRoot has\n 'pointerLockElement', // Element not has, document or shadowRoot has\n 'styleSheets', // Element not has, document or shadowRoot has\n]\n\n// 有shadowRoot则代理到shadowRoot否则代理到原生document上 (方法)\nexport const proxy2RawDocOrShadowMethods = [\n 'append',\n 'contains',\n 'replaceChildren',\n 'createRange', // Element not has, document or shadowRoot has\n 'getSelection', // Element not has, document or shadowRoot has\n 'elementFromPoint', // Element not has, document or shadowRoot has\n 'elementsFromPoint', // Element not has, document or shadowRoot has\n 'getAnimations', // Element not has, document or shadowRoot has\n]\n\n// 直接代理到原生document上 (属性)\nexport const proxy2RawDocumentKeys = [\n 'characterSet',\n 'compatMode',\n 'contentType',\n 'designMode',\n 'dir',\n 'doctype',\n 'embeds',\n 'fullscreenEnabled',\n 'hidden',\n 'implementation',\n 'lastModified',\n 'pictureInPictureEnabled',\n 'plugins',\n 'readyState',\n 'referrer',\n 'visibilityState',\n 'fonts',\n]\n\n// 直接代理到原生document上 (方法)\nexport const proxy2RawDocumentMethods = [\n 'execCommand',\n 'createRange',\n 'exitFullscreen',\n 'exitPictureInPicture',\n 'getElementsByTagNameNS',\n 'hasFocus',\n 'prepend',\n // 'dispatchEvent',\n]\n","/* eslint-disable no-void */\nimport type {\n MicroLocation,\n GuardLocation,\n microAppWindowType,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n assign as oAssign,\n createURL,\n rawDefineProperty,\n} from '../../libs/utils'\nimport {\n setMicroPathToURL,\n isEffectiveApp,\n getMicroState,\n isRouterModeCustom,\n isRouterModeNative,\n isRouterModeSearch,\n} from './core'\nimport {\n dispatchNativeEvent,\n} from './event'\nimport {\n executeNavigationGuard,\n} from './api'\nimport {\n nativeHistoryNavigate,\n navigateWithNativeEvent,\n} from './history'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} from '../../create_app'\nimport {\n hijackMicroLocationKeys,\n} from '../iframe/special_key'\n\n// origin is readonly, so we ignore when updateMicroLocation\nconst locationKeys: ReadonlyArray<keyof MicroLocation> = ['href', 'pathname', 'search', 'hash', 'host', 'hostname', 'port', 'protocol', 'search']\n// origin, fullPath is necessary for guardLocation\nconst guardLocationKeys: ReadonlyArray<keyof MicroLocation> = [...locationKeys, 'origin', 'fullPath']\n\n/**\n * Create location for microApp, each microApp has only one location object, it is a reference type\n * MDN https://developer.mozilla.org/en-US/docs/Web/API/Location\n * @param appName app name\n * @param url app url\n * @param microAppWindow iframeWindow, iframe only\n * @param childStaticLocation real child location info, iframe only\n * @param browserHost host of browser, iframe only\n * @param childHost host of child app, iframe only\n */\nexport function createMicroLocation (\n appName: string,\n url: string,\n microAppWindow?: microAppWindowType,\n childStaticLocation?: MicroLocation,\n browserHost?: string,\n childHost?: string,\n): MicroLocation {\n const rawWindow = globalEnv.rawWindow\n const rawLocation = rawWindow.location\n const isIframe = !!microAppWindow\n /**\n * withLocation is microLocation for with sandbox\n * it is globally unique for child app\n */\n const withLocation = createURL(url)\n\n /**\n * In iframe, jump through raw iframeLocation will cause microAppWindow.location reset\n * So we get location dynamically\n */\n function getTarget (): MicroLocation {\n return isIframe ? microAppWindow.location : withLocation\n }\n\n /**\n * Common handler for href, assign, replace\n * It is mainly used to deal with special scenes about hash\n * @param value target path\n * @param methodName pushState/replaceState\n * @returns origin value or formatted value\n */\n function commonHandler (value: string | URL, methodName: string): string | URL | void {\n const targetLocation = createURL(value, proxyLocation.href)\n // Even if the origin is the same, developers still have the possibility of want to jump to a new page\n if (targetLocation.origin === proxyLocation.origin) {\n const setMicroPathResult = setMicroPathToURL(appName, targetLocation)\n // if disable memory-router, navigate directly through rawLocation\n if (isRouterModeSearch(appName)) {\n /**\n * change hash with location.href will not trigger the browser reload\n * so we use pushState & reload to imitate href behavior\n * NOTE:\n * 1. if child app only change hash, it should not trigger browser reload\n * 2. if address is same and has hash, it should not add route stack\n */\n if (\n targetLocation.pathname === proxyLocation.pathname &&\n targetLocation.search === proxyLocation.search\n ) {\n let oldHref = null\n if (targetLocation.hash !== proxyLocation.hash) {\n if (setMicroPathResult.isAttach2Hash) oldHref = rawLocation.href\n nativeHistoryNavigate(appName, methodName, setMicroPathResult.fullPath)\n }\n\n if (targetLocation.hash) {\n dispatchNativeEvent(appName, false, oldHref)\n } else {\n reload()\n }\n return void 0\n /**\n * when baseApp is hash router, address change of child can not reload browser\n * so we imitate behavior of browser (reload) manually\n */\n } else if (setMicroPathResult.isAttach2Hash) {\n nativeHistoryNavigate(appName, methodName, setMicroPathResult.fullPath)\n reload()\n return void 0\n }\n }\n\n return setMicroPathResult.fullPath\n }\n\n return value\n }\n\n /**\n * common handler for location.pathname & location.search\n * @param targetPath target fullPath\n * @param key pathname/search\n */\n function handleForPathNameAndSearch (targetPath: string, key: keyof Location): void {\n const targetLocation = createURL(targetPath, url)\n // When the browser url has a hash value, the same pathname/search will not refresh browser\n if (targetLocation[key] === proxyLocation[key] && proxyLocation.hash) {\n // The href has not changed, not need to dispatch hashchange event\n dispatchNativeEvent(appName, false)\n } else {\n /**\n * When the value is the same, no new route stack will be added\n * Special scenes such as:\n * pathname: /path ==> /path#hash, /path ==> /path?query\n * search: ?query ==> ?query#hash\n */\n nativeHistoryNavigate(\n appName,\n targetLocation[key] === proxyLocation[key] ? 'replaceState' : 'pushState',\n setMicroPathToURL(appName, targetLocation).fullPath,\n )\n reload()\n }\n }\n\n const createLocationMethod = (locationMethodName: string) => {\n return function (value: string | URL) {\n if (isEffectiveApp(appName)) {\n const targetPath = commonHandler(value, locationMethodName === 'assign' ? 'pushState' : 'replaceState')\n if (targetPath) {\n // Same as href, complete targetPath with browser origin in vite env\n rawLocation[locationMethodName](createURL(targetPath, rawLocation.origin).href)\n }\n }\n }\n }\n\n const assign = createLocationMethod('assign')\n const replace = createLocationMethod('replace')\n const reload = (forcedReload?: boolean): void => rawLocation.reload(forcedReload)\n\n rawDefineProperty(getTarget(), 'fullPath', {\n enumerable: true,\n configurable: true,\n get: () => proxyLocation.pathname + proxyLocation.search + proxyLocation.hash,\n })\n\n /**\n * location.assign/replace is readonly, cannot be proxy, so we use empty object as proxy target\n */\n const proxyLocation = new Proxy({} as Location, {\n get: (_: Location, key: string): unknown => {\n const target = getTarget()\n\n if (key === 'assign') return assign\n if (key === 'replace') return replace\n if (key === 'reload') return reload\n if (key === 'self') return target\n if (key === 'fullPath') return target.fullPath\n\n if (isRouterModeNative(appName)) {\n return bindFunctionToRawTarget<Location>(Reflect.get(rawLocation, key), rawLocation, 'LOCATION')\n }\n\n // src of iframe is base app address, it needs to be replaced separately\n if (isIframe) {\n // host hostname port protocol\n if (hijackMicroLocationKeys.includes(key)) {\n return childStaticLocation![key]\n }\n\n if (key === 'href') {\n // do not use target, because target may be deleted\n return target[key].replace(browserHost!, childHost!)\n }\n }\n\n return bindFunctionToRawTarget<Location>(Reflect.get(target, key), target, 'LOCATION')\n },\n set: (_: Location, key: string, value: string): boolean => {\n if (isEffectiveApp(appName)) {\n const target = getTarget()\n if (key === 'href') {\n /**\n * In vite, targetPath without origin will be completed with child origin\n * So we use browser origin to complete targetPath to avoid this problem\n * NOTE:\n * 1. history mode & value is childOrigin + path ==> jump to browserOrigin + path\n * 2. disable mode & value is childOrigin + path ==> jump to childOrigin + path\n * 3. search mode & value is browserOrigin + path ==> jump to browserOrigin + path\n */\n const targetPath = commonHandler(value, 'pushState')\n if (targetPath) {\n rawLocation.href = createURL(targetPath, rawLocation.origin).href\n }\n } else if (key === 'pathname') {\n if (isRouterModeCustom(appName)) {\n rawLocation.pathname = value\n } else {\n const targetPath = ('/' + value).replace(/^\\/+/, '/') + proxyLocation.search + proxyLocation.hash\n handleForPathNameAndSearch(targetPath, 'pathname')\n }\n } else if (key === 'search') {\n if (isRouterModeCustom(appName)) {\n rawLocation.search = value\n } else {\n const targetPath = proxyLocation.pathname + ('?' + value).replace(/^\\?+/, '?') + proxyLocation.hash\n handleForPathNameAndSearch(targetPath, 'search')\n }\n } else if (key === 'hash') {\n if (isRouterModeCustom(appName)) {\n rawLocation.hash = value\n } else {\n const targetPath = proxyLocation.pathname + proxyLocation.search + ('#' + value).replace(/^#+/, '#')\n const targetLocation = createURL(targetPath, url)\n // The same hash will not trigger popStateEvent\n if (targetLocation.hash !== proxyLocation.hash) {\n navigateWithNativeEvent(\n appName,\n 'pushState',\n setMicroPathToURL(appName, targetLocation),\n false,\n )\n }\n }\n } else {\n Reflect.set(target, key, value)\n }\n }\n return true\n },\n })\n\n return proxyLocation as MicroLocation\n}\n\n/**\n * create guardLocation by microLocation, used for router guard\n */\nexport function createGuardLocation (appName: string, microLocation: MicroLocation): GuardLocation {\n const guardLocation = oAssign({ name: appName }, microLocation) as GuardLocation\n // The prototype values on the URL needs to be manually transferred\n for (const key of guardLocationKeys) guardLocation[key] = microLocation[key]\n return guardLocation\n}\n\n// for updateBrowserURLWithLocation when initial\nexport function autoTriggerNavigationGuard (appName: string, microLocation: MicroLocation): void {\n executeNavigationGuard(appName, createGuardLocation(appName, microLocation), createGuardLocation(appName, microLocation))\n}\n\n/**\n * The following scenes will trigger location update:\n * 1. pushState/replaceState\n * 2. popStateEvent\n * 3. query on browser url when init sub app\n * 4. set defaultPage when when init sub app\n * NOTE:\n * 1. update browser URL first, and then update microLocation\n * 2. the same fullPath will not trigger router guards\n * @param appName app name\n * @param path target path\n * @param base base url\n * @param microLocation micro app location\n * @param type auto prevent\n */\nexport function updateMicroLocation (\n appName: string,\n path: string,\n microLocation: MicroLocation,\n type?: string,\n): void {\n // record old values of microLocation to `from`\n const from = createGuardLocation(appName, microLocation)\n // if is iframeSandbox, microLocation muse be rawLocation of iframe, not proxyLocation\n const newLocation = createURL(path, microLocation.href)\n if (isIframeSandbox(appName)) {\n const microAppWindow = appInstanceMap.get(appName)!.sandBox.microAppWindow\n microAppWindow.rawReplaceState?.call(microAppWindow.history, getMicroState(appName), '', newLocation.href)\n } else {\n let targetHref = newLocation.href\n if (microLocation.self.origin !== newLocation.origin) {\n targetHref = targetHref.replace(newLocation.origin, microLocation.self.origin)\n }\n microLocation.self.href = targetHref\n }\n // update latest values of microLocation to `to`\n const to = createGuardLocation(appName, microLocation)\n\n // The hook called only when fullPath changed\n if (type === 'auto' || (from.fullPath !== to.fullPath && type !== 'prevent')) {\n executeNavigationGuard(appName, to, from)\n }\n}\n","import type {\n MicroRouter,\n MicroLocation,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport {\n getMicroPathFromURL,\n setMicroPathToURL,\n removeMicroPathFromURL,\n removeMicroState,\n setMicroState,\n isRouterModeCustom,\n isRouterModePure,\n} from './core'\nimport {\n createMicroLocation,\n updateMicroLocation,\n autoTriggerNavigationGuard,\n} from './location'\nimport {\n createMicroHistory,\n attachRouteToBrowserURL,\n} from './history'\nimport {\n createURL,\n} from '../../libs/utils'\nimport {\n clearRouterWhenUnmount,\n} from './api'\nexport {\n router,\n} from './api'\nexport {\n addHistoryListener,\n} from './event'\nexport {\n getNoHashMicroPathFromURL,\n getRouterMode,\n isRouterModeCustom,\n isRouterModeSearch,\n} from './core'\nexport {\n patchHistory,\n releasePatchHistory,\n} from './history'\n\n/**\n * TODO: 关于关闭虚拟路由系统的custom、history模式\n * 1. 是否需要发送popstate事件,为了减小对基座的影响,现在不发送\n * 2. 关闭后导致的vue3路由冲突问题需要在文档中明确指出(2处:在关闭虚拟路由系统的配置那里着重说明,在vue常见问题中说明)\n */\n/**\n * The router system has two operations: read and write\n * Read through location and write through history & location\n * @param appName app name\n * @param url app url\n * @returns MicroRouter\n */\nexport function createMicroRouter (appName: string, url: string): MicroRouter {\n const microLocation = createMicroLocation(appName, url)\n return {\n microLocation,\n microHistory: createMicroHistory(appName, microLocation),\n }\n}\n\n/**\n * When the sandbox executes start, or the hidden keep-alive application is re-rendered, the location is updated according to the browser url or attach router info to browser url\n * @param appName app.name\n * @param microLocation MicroLocation for sandbox\n * @param defaultPage default page\n */\nexport function initRouteStateWithURL (\n appName: string,\n microLocation: MicroLocation,\n defaultPage?: string,\n): void {\n const microPath = getMicroPathFromURL(appName)\n if (microPath) {\n updateMicroLocation(appName, microPath, microLocation, 'auto')\n } else {\n updateBrowserURLWithLocation(appName, microLocation, defaultPage)\n }\n}\n\n/**\n * initialize browser information according to microLocation\n * Scenes:\n * 1. sandbox.start\n * 2. reshow of keep-alive app\n */\nexport function updateBrowserURLWithLocation (\n appName: string,\n microLocation: MicroLocation,\n defaultPage?: string,\n): void {\n // update microLocation with defaultPage\n if (defaultPage) updateMicroLocation(appName, defaultPage, microLocation, 'prevent')\n if (!isRouterModePure(appName)) {\n // attach microApp route info to browser URL\n attachRouteToBrowserURL(\n appName,\n setMicroPathToURL(appName, microLocation),\n setMicroState(\n appName,\n null,\n ),\n )\n }\n // trigger guards after change browser URL\n autoTriggerNavigationGuard(appName, microLocation)\n}\n\n/**\n * In any case, microPath & microState will be removed from browser, but location will be initialized only when keep-router-state is false\n * @param appName app name\n * @param url app url\n * @param microLocation location of microApp\n * @param keepRouteState keep-router-state is only used to control whether to clear the location of microApp, default is false\n */\nexport function clearRouteStateFromURL (\n appName: string,\n url: string,\n microLocation: MicroLocation,\n keepRouteState: boolean,\n): void {\n if (!isRouterModeCustom(appName)) {\n if (!keepRouteState) {\n const { pathname, search, hash } = createURL(url)\n updateMicroLocation(appName, pathname + search + hash, microLocation, 'prevent')\n }\n if (!isRouterModePure(appName)) {\n removePathFromBrowser(appName)\n }\n }\n\n clearRouterWhenUnmount(appName)\n}\n\n/**\n * remove microState from history.state and remove microPath from browserURL\n * called on sandbox.stop or hidden of keep-alive app\n */\nexport function removePathFromBrowser (appName: string): void {\n attachRouteToBrowserURL(\n appName,\n removeMicroPathFromURL(appName),\n removeMicroState(appName, globalEnv.rawWindow.history.state),\n )\n}\n","import type {\n BaseSandboxType,\n AppInterface,\n} from '@micro-app/types'\nimport globalEnv from '../libs/global_env'\nimport {\n defer,\n isNode,\n rawDefineProperties,\n} from '../libs/utils'\nimport {\n appInstanceMap,\n} from '../create_app'\n\nexport class BaseSandbox implements BaseSandboxType {\n constructor () {\n this.injectReactHMRProperty()\n }\n\n // keys that can only assigned to rawWindow\n public rawWindowScopeKeyList: PropertyKey[] = [\n 'location',\n ]\n\n // keys that can escape to rawWindow\n public staticEscapeProperties: PropertyKey[] = [\n 'System',\n '__cjsWrapper',\n ]\n\n // keys that scoped in child app\n public staticScopeProperties: PropertyKey[] = [\n 'webpackJsonp',\n 'webpackHotUpdate',\n 'Vue',\n // TODO: 是否可以和constants/SCOPE_WINDOW_ON_EVENT合并\n 'onpopstate',\n 'onhashchange',\n ]\n\n // Properties that can only get and set in microAppWindow, will not escape to rawWindow\n public scopeProperties: PropertyKey[] = Array.from(this.staticScopeProperties)\n // Properties that can be escape to rawWindow\n public escapeProperties: PropertyKey[] = []\n // Properties newly added to microAppWindow\n public injectedKeys = new Set<PropertyKey>()\n // Properties escape to rawWindow, cleared when unmount\n public escapeKeys = new Set<PropertyKey>()\n // Promise used to mark whether the sandbox is initialized\n public sandboxReady!: Promise<void>\n\n // adapter for react\n private injectReactHMRProperty (): void {\n if (__DEV__) {\n // react child in non-react env\n this.staticEscapeProperties.push('__REACT_ERROR_OVERLAY_GLOBAL_HOOK__')\n // in react parent\n if (globalEnv.rawWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__) {\n this.staticScopeProperties = this.staticScopeProperties.concat([\n '__REACT_ERROR_OVERLAY_GLOBAL_HOOK__',\n '__reactRefreshInjected',\n ])\n }\n }\n }\n}\n\n/**\n * TODO:\n * 1、将class Adapter去掉,改为CustomWindow,或者让CustomWindow继承Adapter\n * 2、with沙箱中的常量放入CustomWindow,虽然和iframe沙箱不一致,但更合理\n * 修改时机:在iframe沙箱支持插件后再修改\n */\nexport class CustomWindow {}\n\n// Fix conflict of babel-polyfill@6.x\nexport function fixBabelPolyfill6 (): void {\n if (globalEnv.rawWindow._babelPolyfill) globalEnv.rawWindow._babelPolyfill = false\n}\n\n/**\n * Fix error of hot reload when parent&child created by create-react-app in development environment\n * Issue: https://github.com/micro-zoe/micro-app/issues/382\n */\nexport function fixReactHMRConflict (app: AppInterface): void {\n if (__DEV__) {\n const rawReactErrorHook = globalEnv.rawWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__\n const childReactErrorHook = app.sandBox?.proxyWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__\n if (rawReactErrorHook && childReactErrorHook) {\n globalEnv.rawWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__ = childReactErrorHook\n defer(() => {\n globalEnv.rawWindow.__REACT_ERROR_OVERLAY_GLOBAL_HOOK__ = rawReactErrorHook\n })\n }\n }\n}\n\n/**\n * update dom tree of target dom\n * @param container target dom\n * @param appName app name\n */\nexport function patchElementTree (container: Element | ShadowRoot, appName: string): void {\n const children = Array.from(container.children)\n\n children.length && children.forEach((child) => {\n patchElementTree(child, appName)\n })\n\n for (const child of children) {\n updateElementInfo(child, appName)\n }\n}\n\n/**\n * rewrite baseURI, ownerDocument, __MICRO_APP_NAME__ of target node\n * @param node target node\n * @param appName app name\n * @returns target node\n */\nexport function updateElementInfo <T> (node: T, appName: string): T {\n const proxyWindow = appInstanceMap.get(appName)?.sandBox?.proxyWindow\n if (\n isNode(node) &&\n !node.__MICRO_APP_NAME__ &&\n !node.__PURE_ELEMENT__ &&\n proxyWindow\n ) {\n /**\n * TODO:\n * 1. 测试baseURI和ownerDocument在with沙箱中是否正确\n * 经过验证with沙箱不能重写ownerDocument,否则react点击事件会触发两次\n * 2. with沙箱所有node设置__MICRO_APP_NAME__都使用updateElementInfo\n */\n rawDefineProperties(node, {\n baseURI: {\n configurable: true,\n // if disable-memory-router or router-mode='disable', href point to base app\n get: () => proxyWindow.location.href,\n },\n __MICRO_APP_NAME__: {\n configurable: true,\n writable: true,\n value: appName,\n },\n })\n }\n\n return node\n}\n","import globalEnv from '../libs/global_env'\nimport {\n isFunction,\n isUndefined,\n isString,\n createURL,\n isURL,\n removeDomScope,\n isConstructor,\n} from '../libs/utils'\n\n/**\n * https://developer.mozilla.org/en-US/docs/Web/API/fetch\n * Promise<Response> fetch(input[, init])\n * input: string/Request\n * init?: object\n * @param url app url\n * @param target proxy target\n */\nexport function createMicroFetch (url: string, target?: Window['fetch']): Window['fetch'] {\n const rawFetch = !isUndefined(target) ? target : globalEnv.rawWindow.fetch\n if (!isFunction(rawFetch)) return rawFetch\n return function microFetch (\n input: RequestInfo | URL | string,\n init?: RequestInit,\n ...rests: unknown[]\n ): Promise<Response> {\n if (isString(input) || isURL(input)) {\n input = createURL(input, url).toString()\n }\n /**\n * When fetch rewrite by baseApp, domScope still active when exec rawWindow.fetch\n * If baseApp operate dom in fetch, it will cause error\n * The same for XMLHttpRequest, EventSource\n */\n removeDomScope()\n return rawFetch.call(globalEnv.rawWindow, input, init, ...rests)\n }\n}\n\n/**\n * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest\n * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest\n * @param url app url\n * @param target proxy target\n */\nexport function createMicroXMLHttpRequest (url: string, target?: XMLHttpRequest): any {\n const rawXMLHttpRequest = !isUndefined(target) ? target : globalEnv.rawWindow.XMLHttpRequest\n if (!isConstructor(rawXMLHttpRequest)) return rawXMLHttpRequest\n return class MicroXMLHttpRequest extends rawXMLHttpRequest {\n open (method: string, reqUrl: string, ...rests: unknown[]): void {\n if ((isString(reqUrl) && !/^f(ile|tp):\\/\\//.test(reqUrl)) || isURL(reqUrl)) {\n reqUrl = createURL(reqUrl, url).toString()\n }\n removeDomScope()\n super.open(method, reqUrl, ...rests)\n }\n }\n}\n\nexport interface EventSourceInstance {\n close(): void;\n}\n\nexport interface EventSourceApi {\n createMicroEventSource(appName: string, url: string, target?: EventSource): any\n clearMicroEventSource (appName: string): void\n}\n\nexport function useMicroEventSource (): EventSourceApi {\n let eventSourceMap: Map<string, Set<EventSourceInstance>>\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/API/EventSource\n * pc = new EventSource(url[, configuration])\n * url: string/Request\n * configuration?: object\n * @param url app url\n * @param target proxy target\n */\n function createMicroEventSource (appName: string, url: string, target?: EventSource): any {\n const rawEventSource = !isUndefined(target) ? target : globalEnv.rawWindow.EventSource\n if (!isConstructor(rawEventSource)) return rawEventSource\n return class MicroEventSource extends rawEventSource {\n constructor (\n eventSourceUrl: string | URL,\n eventSourceInitDict?: EventSourceInit,\n ...rests: unknown[]\n ) {\n if (isString(eventSourceUrl) || isURL(eventSourceUrl)) {\n eventSourceUrl = createURL(eventSourceUrl, url).toString()\n }\n removeDomScope()\n super(eventSourceUrl, eventSourceInitDict, ...rests)\n\n if (eventSourceMap) {\n const eventSourceList = eventSourceMap.get(appName)\n if (eventSourceList) {\n eventSourceList.add(this)\n } else {\n eventSourceMap.set(appName, new Set([this]))\n }\n } else {\n eventSourceMap = new Map([[appName, new Set([this])]])\n }\n }\n\n close (): void {\n super.close()\n eventSourceMap.get(appName)?.delete(this)\n }\n }\n }\n\n function clearMicroEventSource (appName: string): void {\n const eventSourceList = eventSourceMap?.get(appName)\n if (eventSourceList?.size) {\n eventSourceList.forEach(item => {\n item.close()\n })\n eventSourceList.clear()\n }\n }\n\n return {\n createMicroEventSource,\n clearMicroEventSource,\n }\n}\n","import type {\n microAppWindowType,\n WithSandBoxInterface,\n plugins,\n MicroLocation,\n SandBoxStartParams,\n SandBoxStopParams,\n CommonEffectHook,\n releaseGlobalEffectParams,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport microApp from '../../micro_app'\nimport {\n EventCenterForMicroApp,\n rebuildDataCenterSnapshot,\n recordDataCenterSnapshot,\n resetDataCenterSnapshot,\n} from '../../interact'\nimport {\n initEnvOfNestedApp,\n} from '../../libs/nest_app'\nimport {\n GLOBAL_KEY_TO_WINDOW\n} from '../../constants'\nimport {\n getEffectivePath,\n isArray,\n isPlainObject,\n removeDomScope,\n throttleDeferForSetAppName,\n rawDefineProperty,\n rawDefineProperties,\n rawHasOwnProperty,\n pureCreateElement,\n assign,\n} from '../../libs/utils'\nimport {\n patchDocument,\n} from './document'\nimport {\n patchWindow,\n} from './window'\nimport {\n patchElementAndDocument,\n releasePatchElementAndDocument,\n} from '../../source/patch'\nimport {\n router,\n createMicroRouter,\n initRouteStateWithURL,\n clearRouteStateFromURL,\n addHistoryListener,\n removePathFromBrowser,\n updateBrowserURLWithLocation,\n patchHistory,\n releasePatchHistory,\n isRouterModeCustom,\n} from '../router'\nimport {\n BaseSandbox,\n CustomWindow,\n fixBabelPolyfill6,\n patchElementTree,\n} from '../adapter'\nimport {\n createMicroFetch,\n useMicroEventSource,\n createMicroXMLHttpRequest,\n} from '../request'\n\n// TODO: 放到global.d.ts\nexport type MicroAppWindowDataType = {\n __MICRO_APP_ENVIRONMENT__: boolean,\n __MICRO_APP_NAME__: string,\n __MICRO_APP_URL__: string,\n __MICRO_APP_PUBLIC_PATH__: string,\n __MICRO_APP_BASE_URL__: string,\n __MICRO_APP_BASE_ROUTE__: string,\n __MICRO_APP_UMD_MODE__: boolean,\n __MICRO_APP_PRE_RENDER__: boolean\n __MICRO_APP_STATE__: string\n microApp: EventCenterForMicroApp,\n rawWindow: Window,\n rawDocument: Document,\n removeDomScope: () => void,\n}\n\nexport type MicroAppWindowType = Window & MicroAppWindowDataType\nexport type proxyWindow = WindowProxy & MicroAppWindowDataType\n\nconst { createMicroEventSource, clearMicroEventSource } = useMicroEventSource()\n\nexport default class WithSandBox extends BaseSandbox implements WithSandBoxInterface {\n static activeCount = 0 // number of active sandbox\n private active = false\n private windowEffect!: CommonEffectHook\n private documentEffect!: CommonEffectHook\n private removeHistoryListener!: CallableFunction\n public proxyWindow!: proxyWindow // Proxy\n public microAppWindow = new CustomWindow() as MicroAppWindowType // Proxy target\n\n constructor (appName: string, url: string) {\n super()\n this.patchWith((resolve: CallableFunction) => {\n // get scopeProperties and escapeProperties from plugins\n this.getSpecialProperties(appName)\n // create location, history for child app\n this.patchRouter(appName, url, this.microAppWindow)\n // patch window of child app\n this.windowEffect = patchWindow(appName, this.microAppWindow, this)\n // patch document of child app\n this.documentEffect = patchDocument(appName, this.microAppWindow, this)\n // properties associated with the native window\n this.setMappingPropertiesWithRawDescriptor(this.microAppWindow)\n // inject global properties\n this.initStaticGlobalKeys(appName, url, this.microAppWindow)\n resolve()\n })\n }\n\n /**\n * open sandbox and perform some initial actions\n * @param umdMode is umd mode\n * @param baseroute base route for child\n * @param defaultPage default page when mount child base on virtual router\n * @param disablePatchRequest prevent patchRequestApi\n */\n public start ({\n umdMode,\n baseroute,\n defaultPage,\n disablePatchRequest,\n }: SandBoxStartParams): void {\n if (this.active) return\n this.active = true\n\n /* --- memory router part --- start */\n // update microLocation, attach route info to browser url\n this.initRouteState(defaultPage)\n\n // unique listener of popstate event for sub app\n this.removeHistoryListener = addHistoryListener(\n this.microAppWindow.__MICRO_APP_NAME__,\n )\n\n if (isRouterModeCustom(this.microAppWindow.__MICRO_APP_NAME__)) {\n this.microAppWindow.__MICRO_APP_BASE_ROUTE__ = this.microAppWindow.__MICRO_APP_BASE_URL__ = baseroute\n }\n /* --- memory router part --- end */\n\n /**\n * Target: Ensure default mode action exactly same to first time when render again\n * 1. The following globalKey maybe modified when render, reset them when render again in default mode\n * 2. Umd mode will not delete any keys during sandBox.stop, ignore umd mode\n * 3. When sandbox.start called for the first time, it must be the default mode\n */\n if (!umdMode) {\n this.initGlobalKeysWhenStart(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.__MICRO_APP_URL__,\n this.microAppWindow,\n disablePatchRequest,\n )\n }\n\n if (++globalEnv.activeSandbox === 1) {\n patchElementAndDocument()\n patchHistory()\n }\n\n if (++WithSandBox.activeCount === 1) {\n // effectDocumentEvent()\n initEnvOfNestedApp()\n }\n\n fixBabelPolyfill6()\n }\n\n /**\n * close sandbox and perform some clean up actions\n * @param umdMode is umd mode\n * @param keepRouteState prevent reset route\n * @param destroy completely destroy, delete cache resources\n * @param clearData clear data from base app\n */\n public stop ({\n umdMode,\n keepRouteState,\n destroy,\n clearData,\n }: SandBoxStopParams): void {\n if (!this.active) return\n this.recordAndReleaseEffect({ umdMode, clearData, destroy }, !umdMode || destroy)\n\n /* --- memory router part --- start */\n // rest url and state of browser\n this.clearRouteState(keepRouteState)\n\n // release listener of popstate for child app\n this.removeHistoryListener?.()\n /* --- memory router part --- end */\n\n /**\n * NOTE:\n * 1. injectedKeys and escapeKeys must be placed at the back\n * 2. if key in initial microAppWindow, and then rewrite, this key will be delete from microAppWindow when stop, and lost when restart\n * 3. umd mode will not delete global keys\n */\n if (!umdMode || destroy) {\n clearMicroEventSource(this.microAppWindow.__MICRO_APP_NAME__)\n\n this.injectedKeys.forEach((key: PropertyKey) => {\n Reflect.deleteProperty(this.microAppWindow, key)\n })\n this.injectedKeys.clear()\n\n this.escapeKeys.forEach((key: PropertyKey) => {\n Reflect.deleteProperty(globalEnv.rawWindow, key)\n })\n this.escapeKeys.clear()\n }\n\n if (--globalEnv.activeSandbox === 0) {\n releasePatchElementAndDocument()\n releasePatchHistory()\n }\n\n if (--WithSandBox.activeCount === 0) {\n // releaseEffectDocumentEvent()\n }\n\n this.active = false\n }\n\n /**\n * inject global properties to microAppWindow\n * TODO: 设置为只读变量\n * @param appName app name\n * @param url app url\n * @param microAppWindow micro window\n */\n private initStaticGlobalKeys (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n ): void {\n microAppWindow.__MICRO_APP_ENVIRONMENT__ = true\n microAppWindow.__MICRO_APP_NAME__ = appName\n microAppWindow.__MICRO_APP_URL__ = url\n microAppWindow.__MICRO_APP_PUBLIC_PATH__ = getEffectivePath(url)\n microAppWindow.__MICRO_APP_BASE_ROUTE__ = ''\n microAppWindow.__MICRO_APP_WINDOW__ = microAppWindow\n microAppWindow.__MICRO_APP_PRE_RENDER__ = false\n microAppWindow.__MICRO_APP_UMD_MODE__ = false\n microAppWindow.__MICRO_APP_PROXY_WINDOW__ = this.proxyWindow\n microAppWindow.__MICRO_APP_SANDBOX__ = this\n microAppWindow.__MICRO_APP_SANDBOX_TYPE__ = 'with'\n microAppWindow.rawWindow = globalEnv.rawWindow\n microAppWindow.rawDocument = globalEnv.rawDocument\n microAppWindow.microApp = assign(new EventCenterForMicroApp(appName), {\n removeDomScope,\n pureCreateElement,\n router,\n })\n }\n\n /**\n * Record global effect and then release (effect: global event, timeout, data listener)\n * Scenes:\n * 1. unmount of default/umd app\n * 2. hidden keep-alive app\n * 3. after init prerender app\n * @param options {\n * @param clearData clear data from base app\n * @param isPrerender is prerender app\n * @param keepAlive is keep-alive app\n * }\n * @param preventRecord prevent record effect events\n */\n public recordAndReleaseEffect (\n options: releaseGlobalEffectParams,\n preventRecord = false,\n ): void {\n if (preventRecord) {\n this.resetEffectSnapshot()\n } else {\n this.recordEffectSnapshot()\n }\n this.releaseGlobalEffect(options)\n }\n\n /**\n * reset effect snapshot data in default mode or destroy\n * Scenes:\n * 1. unmount hidden keep-alive app manually\n * 2. unmount prerender app manually\n */\n public resetEffectSnapshot (): void {\n this.windowEffect.reset()\n this.documentEffect.reset()\n resetDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n /**\n * record umd snapshot before the first execution of umdHookMount\n * Scenes:\n * 1. exec umdMountHook in umd mode\n * 2. hidden keep-alive app\n * 3. after init prerender app\n */\n public recordEffectSnapshot (): void {\n this.windowEffect.record()\n this.documentEffect.record()\n recordDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n // rebuild umd snapshot before remount umd app\n public rebuildEffectSnapshot (): void {\n this.windowEffect.rebuild()\n this.documentEffect.rebuild()\n rebuildDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n /**\n * clear global event, timeout, data listener\n * Scenes:\n * 1. unmount of default/umd app\n * 2. hidden keep-alive app\n * 3. after init prerender app\n * @param umdMode is umd mode\n * @param clearData clear data from base app\n * @param isPrerender is prerender app\n * @param keepAlive is keep-alive app\n * @param destroy completely destroy\n */\n public releaseGlobalEffect ({\n umdMode = false,\n clearData = false,\n isPrerender = false,\n keepAlive = false,\n destroy = false,\n }: releaseGlobalEffectParams): void {\n // default mode(not keep-alive or isPrerender)\n this.windowEffect.release((!umdMode && !keepAlive && !isPrerender) || destroy)\n this.documentEffect.release()\n this.microAppWindow.microApp?.clearDataListener()\n this.microAppWindow.microApp?.clearGlobalDataListener()\n if (clearData) {\n microApp.clearData(this.microAppWindow.__MICRO_APP_NAME__)\n this.microAppWindow.microApp?.clearData()\n }\n }\n\n /**\n * get scopeProperties and escapeProperties from plugins & adapter\n * @param appName app name\n */\n private getSpecialProperties (appName: string): void {\n if (isPlainObject(microApp.options.plugins)) {\n this.commonActionForSpecialProperties(microApp.options.plugins.global)\n this.commonActionForSpecialProperties(microApp.options.plugins.modules?.[appName])\n }\n }\n\n // common action for global plugins and module plugins\n private commonActionForSpecialProperties (plugins: plugins['global']) {\n if (isArray(plugins)) {\n for (const plugin of plugins) {\n if (isPlainObject(plugin)) {\n if (isArray(plugin.scopeProperties)) {\n this.scopeProperties = this.scopeProperties.concat(plugin.scopeProperties)\n }\n if (isArray(plugin.escapeProperties)) {\n this.escapeProperties = this.escapeProperties.concat(plugin.escapeProperties)\n }\n }\n }\n }\n }\n\n // set __MICRO_APP_PRE_RENDER__ state\n public setPreRenderState (state: boolean): void {\n this.microAppWindow.__MICRO_APP_PRE_RENDER__ = state\n }\n\n public markUmdMode (state: boolean): void {\n this.microAppWindow.__MICRO_APP_UMD_MODE__ = state\n }\n\n private patchWith (cb: CallableFunction): void {\n this.sandboxReady = new Promise<void>((resolve) => cb(resolve))\n }\n\n // properties associated with the native window\n private setMappingPropertiesWithRawDescriptor (microAppWindow: microAppWindowType): void {\n let topValue: Window, parentValue: Window\n const rawWindow = globalEnv.rawWindow\n if (rawWindow === rawWindow.parent) { // not in iframe\n topValue = parentValue = this.proxyWindow\n } else { // in iframe\n topValue = rawWindow.top\n parentValue = rawWindow.parent\n }\n\n rawDefineProperties(microAppWindow, {\n top: this.createDescriptorForMicroAppWindow('top', topValue),\n parent: this.createDescriptorForMicroAppWindow('parent', parentValue),\n })\n\n GLOBAL_KEY_TO_WINDOW.forEach((key: PropertyKey) => {\n rawDefineProperty(\n microAppWindow,\n key,\n this.createDescriptorForMicroAppWindow(key, this.proxyWindow)\n )\n })\n }\n\n private createDescriptorForMicroAppWindow (key: PropertyKey, value: unknown): PropertyDescriptor {\n const { configurable = true, enumerable = true, writable, set } = Object.getOwnPropertyDescriptor(globalEnv.rawWindow, key) || { writable: true }\n const descriptor: PropertyDescriptor = {\n value,\n configurable,\n enumerable,\n writable: writable ?? !!set\n }\n\n return descriptor\n }\n\n /**\n * init global properties of microAppWindow when exec sandBox.start\n * @param microAppWindow micro window\n * @param appName app name\n * @param url app url\n * @param disablePatchRequest prevent rewrite request method of child app\n */\n private initGlobalKeysWhenStart (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n disablePatchRequest: boolean,\n ): void {\n microAppWindow.hasOwnProperty = (key: PropertyKey) => rawHasOwnProperty.call(microAppWindow, key) || rawHasOwnProperty.call(globalEnv.rawWindow, key)\n this.setHijackProperty(appName, microAppWindow)\n if (!disablePatchRequest) this.patchRequestApi(appName, url, microAppWindow)\n this.setScopeProperties(microAppWindow)\n }\n\n // set hijack Properties to microAppWindow\n private setHijackProperty (appName: string, microAppWindow: microAppWindowType): void {\n let modifiedEval: unknown, modifiedImage: unknown\n rawDefineProperties(microAppWindow, {\n eval: {\n configurable: true,\n enumerable: false,\n get () {\n throttleDeferForSetAppName(appName)\n return modifiedEval || globalEnv.rawWindow.eval\n },\n set: (value) => {\n modifiedEval = value\n },\n },\n Image: {\n configurable: true,\n enumerable: false,\n get () {\n throttleDeferForSetAppName(appName)\n return modifiedImage || globalEnv.ImageProxy\n },\n set: (value) => {\n modifiedImage = value\n },\n },\n })\n }\n\n // rewrite fetch, XMLHttpRequest, EventSource\n private patchRequestApi (appName: string, url: string, microAppWindow: microAppWindowType): void {\n let microFetch = createMicroFetch(url)\n let microXMLHttpRequest = createMicroXMLHttpRequest(url)\n let microEventSource = createMicroEventSource(appName, url)\n\n rawDefineProperties(microAppWindow, {\n fetch: {\n configurable: true,\n enumerable: true,\n get () {\n return microFetch\n },\n set (value) {\n microFetch = createMicroFetch(url, value)\n },\n },\n XMLHttpRequest: {\n configurable: true,\n enumerable: true,\n get () {\n return microXMLHttpRequest\n },\n set (value) {\n microXMLHttpRequest = createMicroXMLHttpRequest(url, value)\n },\n },\n EventSource: {\n configurable: true,\n enumerable: true,\n get () {\n return microEventSource\n },\n set (value) {\n microEventSource = createMicroEventSource(appName, url, value)\n },\n },\n })\n }\n\n /**\n * Init scope keys to microAppWindow, prevent fall to rawWindow from with(microAppWindow)\n * like: if (!xxx) {}\n * NOTE:\n * 1. Symbol.unscopables cannot affect undefined keys\n * 2. Doesn't use for window.xxx because it fall to proxyWindow\n */\n setScopeProperties (microAppWindow: microAppWindowType): void {\n this.scopeProperties.forEach((key: PropertyKey) => {\n Reflect.set(microAppWindow, key, microAppWindow[key])\n })\n }\n\n // set location & history for memory router\n private patchRouter (appName: string, url: string, microAppWindow: microAppWindowType): void {\n const { microLocation, microHistory } = createMicroRouter(appName, url)\n rawDefineProperties(microAppWindow, {\n location: {\n configurable: false,\n enumerable: true,\n get () {\n return microLocation\n },\n set: (value) => {\n globalEnv.rawWindow.location = value\n },\n },\n history: {\n configurable: true,\n enumerable: true,\n get () {\n return microHistory\n },\n },\n })\n }\n\n private initRouteState (defaultPage: string): void {\n initRouteStateWithURL(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.location as MicroLocation,\n defaultPage,\n )\n }\n\n private clearRouteState (keepRouteState: boolean): void {\n clearRouteStateFromURL(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.__MICRO_APP_URL__,\n this.microAppWindow.location as MicroLocation,\n keepRouteState,\n )\n }\n\n public setRouteInfoForKeepAliveApp (): void {\n updateBrowserURLWithLocation(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.location as MicroLocation,\n )\n }\n\n public removeRouteInfoForKeepAliveApp (): void {\n removePathFromBrowser(this.microAppWindow.__MICRO_APP_NAME__)\n }\n\n /**\n * Format all html elements when init\n * @param container micro app container\n */\n public patchStaticElement (container: Element | ShadowRoot): void {\n patchElementTree(container, this.microAppWindow.__MICRO_APP_NAME__)\n }\n\n /**\n * action before exec scripts when mount\n * Actions:\n * 1. patch static elements from html\n * @param container micro app container\n */\n public actionBeforeExecScripts (container: Element | ShadowRoot): void {\n this.patchStaticElement(container)\n }\n\n public setStaticAppState (state: string): void {\n this.microAppWindow.__MICRO_APP_STATE__ = state\n }\n}\n","import type {\n microAppWindowType,\n MicroEventListener,\n CommonEffectHook,\n} from '@micro-app/types'\nimport type IframeSandbox from './index'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n rawDefineProperty,\n isFunction,\n logWarn,\n includes,\n} from '../../libs/utils'\nimport {\n GLOBAL_KEY_TO_WINDOW,\n SCOPE_WINDOW_EVENT,\n SCOPE_WINDOW_ON_EVENT,\n} from '../../constants'\nimport {\n escape2RawWindowKeys,\n escape2RawWindowRegExpKeys,\n} from './special_key'\n\n/**\n * patch window of child app\n * @param appName app name\n * @param microAppWindow microWindow of child app\n * @param sandbox WithSandBox\n * @returns EffectHook\n */\nexport function patchWindow (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): CommonEffectHook {\n patchWindowProperty(appName, microAppWindow)\n createProxyWindow(microAppWindow, sandbox)\n return patchWindowEffect(microAppWindow)\n}\n/**\n * rewrite special properties of window\n * @param appName app name\n * @param microAppWindow child app microWindow\n */\nfunction patchWindowProperty (\n appName: string,\n microAppWindow: microAppWindowType,\n):void {\n const rawWindow = globalEnv.rawWindow\n\n escape2RawWindowKeys.forEach((key: string) => {\n microAppWindow[key] = bindFunctionToRawTarget(rawWindow[key], rawWindow)\n })\n\n Object.getOwnPropertyNames(microAppWindow)\n .filter((key: string) => {\n escape2RawWindowRegExpKeys.some((reg: RegExp) => {\n if (reg.test(key) && key in microAppWindow.parent) {\n if (isFunction(rawWindow[key])) {\n microAppWindow[key] = bindFunctionToRawTarget(rawWindow[key], rawWindow)\n } else {\n const { configurable, enumerable } = Object.getOwnPropertyDescriptor(microAppWindow, key) || {\n configurable: true,\n enumerable: true,\n }\n if (configurable) {\n rawDefineProperty(microAppWindow, key, {\n configurable,\n enumerable,\n get: () => rawWindow[key],\n set: (value) => { rawWindow[key] = value },\n })\n }\n }\n return true\n }\n return false\n })\n\n return /^on/.test(key) && !SCOPE_WINDOW_ON_EVENT.includes(key)\n })\n .forEach((eventName: string) => {\n const { enumerable, writable, set } = Object.getOwnPropertyDescriptor(microAppWindow, eventName) || {\n enumerable: true,\n writable: true,\n }\n try {\n rawDefineProperty(microAppWindow, eventName, {\n enumerable,\n configurable: true,\n get: () => rawWindow[eventName],\n set: writable ?? !!set\n ? (value) => { rawWindow[eventName] = isFunction(value) ? value.bind(microAppWindow) : value }\n : undefined,\n })\n } catch (e) {\n logWarn(e, appName)\n }\n })\n}\n\n/**\n * create proxyWindow with Proxy(microAppWindow)\n * @param microAppWindow micro app window\n * @param sandbox IframeSandbox\n */\nfunction createProxyWindow (\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): void {\n const rawWindow = globalEnv.rawWindow\n const customProperties = new Set<PropertyKey>()\n\n /**\n * proxyWindow will only take effect in certain scenes, such as window.key\n * e.g:\n * 1. window.key in normal app --> fall into proxyWindow\n * 2. window.key in module app(vite), fall into microAppWindow(iframeWindow)\n * 3. if (key)... --> fall into microAppWindow(iframeWindow)\n */\n const proxyWindow = new Proxy(microAppWindow, {\n get: (target: microAppWindowType, key: PropertyKey): unknown => {\n if (key === 'location') {\n return sandbox.proxyLocation\n }\n\n if (includes(GLOBAL_KEY_TO_WINDOW, key)) {\n return proxyWindow\n }\n\n if (customProperties.has(key)) {\n return Reflect.get(target, key)\n }\n\n /**\n * Same as proxyWindow, escapeProperties will only take effect in certain scenes\n * e.g:\n * 1. window.key in normal app --> fall into proxyWindow, escapeProperties will effect\n * 2. window.key in module app(vite), fall into microAppWindow(iframeWindow), escapeProperties will not take effect\n * 3. if (key)... --> fall into microAppWindow(iframeWindow), escapeProperties will not take effect\n */\n if (includes(sandbox.escapeProperties, key) && !Reflect.has(target, key)) {\n return bindFunctionToRawTarget(Reflect.get(rawWindow, key), rawWindow)\n }\n\n return bindFunctionToRawTarget(Reflect.get(target, key), target)\n },\n set: (target: microAppWindowType, key: PropertyKey, value: unknown): boolean => {\n if (key === 'location') {\n return Reflect.set(rawWindow, key, value)\n }\n\n if (!Reflect.has(target, key)) {\n customProperties.add(key)\n }\n\n Reflect.set(target, key, value)\n\n if (includes(sandbox.escapeProperties, key)) {\n !Reflect.has(rawWindow, key) && sandbox.escapeKeys.add(key)\n Reflect.set(rawWindow, key, value)\n }\n\n return true\n },\n has: (target: microAppWindowType, key: PropertyKey) => key in target,\n deleteProperty: (target: microAppWindowType, key: PropertyKey): boolean => {\n if (Reflect.has(target, key)) {\n sandbox.escapeKeys.has(key) && Reflect.deleteProperty(rawWindow, key)\n return Reflect.deleteProperty(target, key)\n }\n return true\n },\n })\n\n sandbox.proxyWindow = proxyWindow\n}\n\nfunction patchWindowEffect (microAppWindow: microAppWindowType): CommonEffectHook {\n const { rawWindow, rawAddEventListener, rawRemoveEventListener } = globalEnv\n const eventListenerMap = new Map<string, Set<MicroEventListener>>()\n const sstEventListenerMap = new Map<string, Set<MicroEventListener>>()\n\n function getEventTarget (type: string): Window {\n return SCOPE_WINDOW_EVENT.includes(type) ? microAppWindow : rawWindow\n }\n\n // TODO: listener 是否需要绑定microAppWindow,否则函数中的this指向原生window\n microAppWindow.addEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList) {\n listenerList.add(listener)\n } else {\n eventListenerMap.set(type, new Set([listener]))\n }\n listener && (listener.__MICRO_APP_MARK_OPTIONS__ = options)\n rawAddEventListener.call(getEventTarget(type), type, listener, options)\n }\n\n microAppWindow.removeEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList?.size && listenerList.has(listener)) {\n listenerList.delete(listener)\n }\n rawRemoveEventListener.call(getEventTarget(type), type, listener, options)\n }\n\n const reset = (): void => {\n sstEventListenerMap.clear()\n }\n\n /**\n * NOTE:\n * 1. about timer(events & properties should record & rebuild at all modes, exclude default mode)\n * 2. record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * 4 modes: default-mode、umd-mode、prerender、keep-alive\n * Solution:\n * 1. default-mode(normal): clear events & timers, not record & rebuild anything\n * 2. umd-mode(normal): not clear timers, record & rebuild events\n * 3. prerender/keep-alive(default, umd): not clear timers, record & rebuild events\n *\n * TODO: 现在的 清除、记录和恢复操作分散的太零散,sandbox、create_app中都有分散,将代码再优化一下,集中处理\n */\n const record = (): void => {\n // record window event\n eventListenerMap.forEach((listenerList, type) => {\n if (listenerList.size) {\n const cacheList = sstEventListenerMap.get(type) || []\n sstEventListenerMap.set(type, new Set([...cacheList, ...listenerList]))\n }\n })\n }\n\n // rebuild event and timer before remount app\n const rebuild = (): void => {\n // rebuild window event\n sstEventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n microAppWindow.addEventListener(type, listener, listener?.__MICRO_APP_MARK_OPTIONS__)\n }\n })\n\n reset()\n }\n\n const release = (): void => {\n // Clear window binding events\n if (eventListenerMap.size) {\n eventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n rawRemoveEventListener.call(getEventTarget(type), type, listener)\n }\n })\n eventListenerMap.clear()\n }\n }\n\n return {\n reset,\n record,\n rebuild,\n release,\n }\n}\n","import type {\n microAppWindowType,\n MicroEventListener,\n CommonEffectHook,\n} from '@micro-app/types'\nimport type IframeSandbox from './index'\nimport {\n rawDefineProperty,\n rawDefineProperties,\n isFunction,\n logWarn,\n isUniqueElement,\n isInvalidQuerySelectorKey,\n throttleDeferForSetAppName,\n} from '../../libs/utils'\nimport globalEnv from '../../libs/global_env'\nimport bindFunctionToRawTarget from '../bind_function'\nimport {\n uniqueDocumentElement,\n proxy2RawDocOrShadowKeys,\n proxy2RawDocOrShadowMethods,\n proxy2RawDocumentKeys,\n proxy2RawDocumentMethods,\n} from './special_key'\nimport {\n SCOPE_DOCUMENT_EVENT,\n SCOPE_DOCUMENT_ON_EVENT,\n} from '../../constants'\nimport {\n updateElementInfo,\n} from '../adapter'\nimport {\n appInstanceMap,\n} from '../../create_app'\n\n/**\n * TODO: 1、shadowDOM 2、结构优化\n *\n * patch document of child app\n * @param appName app name\n * @param microAppWindow microWindow of child app\n * @param sandbox IframeSandbox\n * @returns EffectHook\n */\nexport function patchDocument (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): CommonEffectHook {\n patchDocumentPrototype(appName, microAppWindow)\n patchDocumentProperty(appName, microAppWindow, sandbox)\n\n return patchDocumentEffect(appName, microAppWindow)\n}\n\nfunction patchDocumentPrototype (appName: string, microAppWindow: microAppWindowType): void {\n const rawDocument = globalEnv.rawDocument\n const microRootDocument = microAppWindow.Document\n const microDocument = microAppWindow.document\n const rawMicroCreateElement = microRootDocument.prototype.createElement\n const rawMicroCreateElementNS = microRootDocument.prototype.createElementNS\n const rawMicroCreateTextNode = microRootDocument.prototype.createTextNode\n const rawMicroCreateDocumentFragment = microRootDocument.prototype.createDocumentFragment\n const rawMicroCreateComment = microRootDocument.prototype.createComment\n const rawMicroQuerySelector = microRootDocument.prototype.querySelector\n const rawMicroQuerySelectorAll = microRootDocument.prototype.querySelectorAll\n const rawMicroGetElementById = microRootDocument.prototype.getElementById\n const rawMicroGetElementsByClassName = microRootDocument.prototype.getElementsByClassName\n const rawMicroGetElementsByTagName = microRootDocument.prototype.getElementsByTagName\n const rawMicroGetElementsByName = microRootDocument.prototype.getElementsByName\n const rawMicroElementFromPoint = microRootDocument.prototype.elementFromPoint\n const rawMicroCaretRangeFromPoint = microRootDocument.prototype.caretRangeFromPoint\n\n microRootDocument.prototype.caretRangeFromPoint = function caretRangeFromPoint (\n x: number,\n y: number,\n ): Range {\n // 这里this指向document才可以获取到子应用的document实例,range才可以被成功生成\n const element = rawMicroElementFromPoint.call(rawDocument, x, y)\n const range = rawMicroCaretRangeFromPoint.call(rawDocument, x, y)\n updateElementInfo(element, appName)\n return range\n }\n\n microRootDocument.prototype.createElement = function createElement (\n tagName: string,\n options?: ElementCreationOptions,\n ): HTMLElement {\n const element = rawMicroCreateElement.call(this, tagName, options)\n return updateElementInfo(element, appName)\n }\n\n microRootDocument.prototype.createElementNS = function createElementNS (\n namespaceURI: string,\n name: string,\n options?: string | ElementCreationOptions,\n ): HTMLElement {\n const element = rawMicroCreateElementNS.call(this, namespaceURI, name, options)\n return updateElementInfo(element, appName)\n }\n\n microRootDocument.prototype.createTextNode = function createTextNode (data: string): Text {\n const element = rawMicroCreateTextNode.call(this, data)\n return updateElementInfo<Text>(element, appName)\n }\n\n microRootDocument.prototype.createDocumentFragment = function createDocumentFragment (): DocumentFragment {\n const element = rawMicroCreateDocumentFragment.call(this)\n return updateElementInfo(element, appName)\n }\n\n microRootDocument.prototype.createComment = function createComment (data: string): Comment {\n const element = rawMicroCreateComment.call(this, data)\n return updateElementInfo<Comment>(element, appName)\n }\n\n function getDefaultRawTarget (target: Document): Document {\n return microDocument !== target ? target : rawDocument\n }\n\n // query element👇\n function querySelector (this: Document, selectors: string): any {\n if (\n !selectors ||\n isUniqueElement(selectors) ||\n microDocument !== this\n ) {\n const _this = getDefaultRawTarget(this)\n return rawMicroQuerySelector.call(_this, selectors)\n }\n\n return appInstanceMap.get(appName)?.querySelector(selectors) ?? null\n }\n\n function querySelectorAll (this: Document, selectors: string): any {\n if (\n !selectors ||\n isUniqueElement(selectors) ||\n microDocument !== this\n ) {\n const _this = getDefaultRawTarget(this)\n return rawMicroQuerySelectorAll.call(_this, selectors)\n }\n\n return appInstanceMap.get(appName)?.querySelectorAll(selectors) ?? []\n }\n\n microRootDocument.prototype.querySelector = querySelector\n microRootDocument.prototype.querySelectorAll = querySelectorAll\n\n microRootDocument.prototype.getElementById = function getElementById (key: string): HTMLElement | null {\n const _this = getDefaultRawTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementById.call(_this, key)\n }\n\n try {\n return querySelector.call(this, `#${key}`)\n } catch {\n return rawMicroGetElementById.call(_this, key)\n }\n }\n\n microRootDocument.prototype.getElementsByClassName = function getElementsByClassName (key: string): HTMLCollectionOf<Element> {\n const _this = getDefaultRawTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementsByClassName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(this, `.${key}`)\n } catch {\n return rawMicroGetElementsByClassName.call(_this, key)\n }\n }\n\n microRootDocument.prototype.getElementsByTagName = function getElementsByTagName (key: string): HTMLCollectionOf<Element> {\n const _this = getDefaultRawTarget(this)\n if (\n isUniqueElement(key) ||\n isInvalidQuerySelectorKey(key)\n ) {\n return rawMicroGetElementsByTagName.call(_this, key)\n } else if (/^script|base$/i.test(key)) {\n return rawMicroGetElementsByTagName.call(microDocument, key)\n }\n\n try {\n return querySelectorAll.call(this, key)\n } catch {\n return rawMicroGetElementsByTagName.call(_this, key)\n }\n }\n\n microRootDocument.prototype.getElementsByName = function getElementsByName (key: string): NodeListOf<HTMLElement> {\n const _this = getDefaultRawTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementsByName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(this, `[name=${key}]`)\n } catch {\n return rawMicroGetElementsByName.call(_this, key)\n }\n }\n}\n\nfunction patchDocumentProperty (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): void {\n const rawDocument = globalEnv.rawDocument\n const microRootDocument = microAppWindow.Document\n const microDocument = microAppWindow.document\n\n const getCommonDescriptor = (key: PropertyKey, getter: () => unknown): PropertyDescriptor => {\n const { enumerable } = Object.getOwnPropertyDescriptor(microRootDocument.prototype, key) || {\n enumerable: true,\n }\n return {\n configurable: true,\n enumerable,\n get: getter,\n }\n }\n\n const createDescriptors = (): PropertyDescriptorMap => {\n const result: PropertyDescriptorMap = {}\n const descList: Array<[string, () => unknown]> = [\n // if disable-memory-router or router-mode='disable', href point to base app\n ['documentURI', () => sandbox.proxyLocation.href],\n ['URL', () => sandbox.proxyLocation.href],\n ['documentElement', () => rawDocument.documentElement],\n ['scrollingElement', () => rawDocument.scrollingElement],\n ['forms', () => microRootDocument.prototype.querySelectorAll.call(microDocument, 'form')],\n ['images', () => microRootDocument.prototype.querySelectorAll.call(microDocument, 'img')],\n ['links', () => microRootDocument.prototype.querySelectorAll.call(microDocument, 'a')],\n // unique keys of micro-app\n ['microAppElement', () => appInstanceMap.get(appName)?.container],\n ['__MICRO_APP_NAME__', () => appName],\n ]\n\n descList.forEach((desc) => {\n result[desc[0]] = getCommonDescriptor(desc[0], desc[1])\n })\n\n // TODO: shadowDOM\n proxy2RawDocOrShadowKeys.forEach((key) => {\n result[key] = getCommonDescriptor(key, () => rawDocument[key])\n })\n\n // TODO: shadowDOM\n proxy2RawDocOrShadowMethods.forEach((key) => {\n result[key] = getCommonDescriptor(key, () => bindFunctionToRawTarget<Document>(rawDocument[key], rawDocument, 'DOCUMENT'))\n })\n\n proxy2RawDocumentKeys.forEach((key) => {\n result[key] = getCommonDescriptor(key, () => rawDocument[key])\n })\n\n proxy2RawDocumentMethods.forEach((key) => {\n result[key] = getCommonDescriptor(key, () => bindFunctionToRawTarget<Document>(rawDocument[key], rawDocument, 'DOCUMENT'))\n })\n\n return result\n }\n\n rawDefineProperties(microRootDocument.prototype, createDescriptors())\n\n // head, body, html, title\n uniqueDocumentElement.forEach((tagName: string) => {\n rawDefineProperty(microDocument, tagName, {\n enumerable: true,\n configurable: true,\n get: () => {\n throttleDeferForSetAppName(appName)\n return rawDocument[tagName]\n },\n set: (value: unknown) => { rawDocument[tagName] = value },\n })\n })\n}\n\nfunction patchDocumentEffect (appName: string, microAppWindow: microAppWindowType): CommonEffectHook {\n const { rawDocument, rawAddEventListener, rawRemoveEventListener } = globalEnv\n const eventListenerMap = new Map<string, Set<MicroEventListener>>()\n const sstEventListenerMap = new Map<string, Set<MicroEventListener>>()\n let onClickHandler: unknown = null\n let sstOnClickHandler: unknown = null\n const microRootDocument = microAppWindow.Document\n const microDocument = microAppWindow.document\n\n function getEventTarget (type: string, bindTarget: Document): Document {\n return SCOPE_DOCUMENT_EVENT.includes(type) ? bindTarget : rawDocument\n }\n\n microRootDocument.prototype.addEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const handler = isFunction(listener) ? (listener.__MICRO_APP_BOUND_FUNCTION__ = listener.__MICRO_APP_BOUND_FUNCTION__ || listener.bind(this)) : listener\n const listenerList = eventListenerMap.get(type)\n if (listenerList) {\n listenerList.add(listener)\n } else {\n eventListenerMap.set(type, new Set([listener]))\n }\n listener && (listener.__MICRO_APP_MARK_OPTIONS__ = options)\n rawAddEventListener.call(getEventTarget(type, this), type, handler, options)\n }\n\n microRootDocument.prototype.removeEventListener = function (\n type: string,\n listener: MicroEventListener,\n options?: boolean | AddEventListenerOptions,\n ): void {\n const listenerList = eventListenerMap.get(type)\n if (listenerList?.size && listenerList.has(listener)) {\n listenerList.delete(listener)\n }\n const handler = listener?.__MICRO_APP_BOUND_FUNCTION__ || listener\n rawRemoveEventListener.call(getEventTarget(type, this), type, handler, options)\n }\n\n // 重新定义microRootDocument.prototype 上的on开头方法\n function createSetterHandler (eventName: string): (value: unknown) => void {\n if (eventName === 'onclick') {\n return (value: unknown): void => {\n if (isFunction(onClickHandler)) {\n rawRemoveEventListener.call(rawDocument, 'click', onClickHandler, false)\n }\n if (isFunction(value)) {\n onClickHandler = value.bind(microDocument)\n rawAddEventListener.call(rawDocument, 'click', onClickHandler, false)\n } else {\n onClickHandler = value\n }\n }\n }\n return (value: unknown) => { rawDocument[eventName] = isFunction(value) ? value.bind(microDocument) : value }\n }\n\n /**\n * TODO:\n * 1、直接代理到原生document是否正确\n * 2、shadowDOM\n */\n Object.getOwnPropertyNames(microRootDocument.prototype)\n .filter((key: string) => /^on/.test(key) && !SCOPE_DOCUMENT_ON_EVENT.includes(key))\n .forEach((eventName: string) => {\n const { enumerable, writable, set } = Object.getOwnPropertyDescriptor(microRootDocument.prototype, eventName) || {\n enumerable: true,\n writable: true,\n }\n\n try {\n rawDefineProperty(microRootDocument.prototype, eventName, {\n enumerable,\n configurable: true,\n get: () => {\n if (eventName === 'onclick') return onClickHandler\n return rawDocument[eventName]\n },\n set: writable ?? !!set ? createSetterHandler(eventName) : undefined,\n })\n } catch (e) {\n logWarn(e, appName)\n }\n })\n\n const reset = (): void => {\n sstEventListenerMap.clear()\n sstOnClickHandler = null\n }\n\n /**\n * record event\n * NOTE:\n * 1.record maybe call twice when unmount prerender, keep-alive app manually with umd mode\n * Scenes:\n * 1. exec umdMountHook in umd mode\n * 2. hidden keep-alive app\n * 3. after init prerender app\n */\n const record = (): void => {\n /**\n * record onclick handler\n * onClickHandler maybe set again after prerender/keep-alive app hidden\n */\n sstOnClickHandler = onClickHandler || sstOnClickHandler\n\n // record document event\n eventListenerMap.forEach((listenerList, type) => {\n if (listenerList.size) {\n const cacheList = sstEventListenerMap.get(type) || []\n sstEventListenerMap.set(type, new Set([...cacheList, ...listenerList]))\n }\n })\n }\n\n // rebuild event and timer before remount app\n const rebuild = (): void => {\n // rebuild onclick event\n if (sstOnClickHandler && !onClickHandler) microDocument.onclick = sstOnClickHandler\n\n sstEventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n microDocument.addEventListener(type, listener, listener?.__MICRO_APP_MARK_OPTIONS__)\n }\n })\n\n reset()\n }\n\n const release = (): void => {\n // Clear the function bound by micro app through document.onclick\n if (isFunction(onClickHandler)) {\n rawRemoveEventListener.call(rawDocument, 'click', onClickHandler)\n }\n onClickHandler = null\n\n // Clear document binding event\n if (eventListenerMap.size) {\n eventListenerMap.forEach((listenerList, type) => {\n for (const listener of listenerList) {\n rawRemoveEventListener.call(\n getEventTarget(type, microDocument),\n type,\n listener?.__MICRO_APP_BOUND_FUNCTION__ || listener,\n )\n }\n })\n eventListenerMap.clear()\n }\n }\n\n return {\n reset,\n record,\n rebuild,\n release,\n }\n}\n","import type {\n microAppWindowType,\n} from '@micro-app/types'\nimport type IframeSandbox from './index'\nimport globalEnv from '../../libs/global_env'\nimport microApp from '../../micro_app'\nimport {\n rawDefineProperty,\n CompletionPath,\n isScriptElement,\n isBaseElement,\n isElement,\n isNode,\n isMicroAppBody,\n throttleDeferForSetAppName,\n} from '../../libs/utils'\nimport {\n updateElementInfo,\n} from '../adapter'\nimport {\n appInstanceMap,\n} from '../../create_app'\n\n/**\n * patch Element & Node of child app\n * @param appName app name\n * @param url app url\n * @param microAppWindow microWindow of child app\n * @param sandbox IframeSandbox\n */\nexport function patchElement (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): void {\n patchIframeNode(appName, microAppWindow, sandbox)\n patchIframeAttribute(url, microAppWindow)\n}\n\nfunction patchIframeNode (\n appName: string,\n microAppWindow: microAppWindowType,\n sandbox: IframeSandbox,\n): void {\n const rawRootElement = globalEnv.rawRootElement // native root Element\n const rawDocument = globalEnv.rawDocument\n const microDocument = microAppWindow.document\n const microRootNode = microAppWindow.Node\n const microRootElement = microAppWindow.Element\n // const rawMicroGetRootNode = microRootNode.prototype.getRootNode\n const rawMicroAppendChild = microRootNode.prototype.appendChild\n const rawMicroInsertBefore = microRootNode.prototype.insertBefore\n const rawMicroReplaceChild = microRootNode.prototype.replaceChild\n const rawMicroRemoveChild = microRootNode.prototype.removeChild\n const rawMicroAppend = microRootElement.prototype.append\n const rawMicroPrepend = microRootElement.prototype.prepend\n const rawMicroInsertAdjacentElement = microRootElement.prototype.insertAdjacentElement\n const rawMicroCloneNode = microRootNode.prototype.cloneNode\n const rawInnerHTMLDesc = Object.getOwnPropertyDescriptor(microRootElement.prototype, 'innerHTML') as PropertyDescriptor\n const rawParentNodeDesc = Object.getOwnPropertyDescriptor(microRootNode.prototype, 'parentNode') as PropertyDescriptor\n const rawOwnerDocumentDesc = Object.getOwnPropertyDescriptor(microRootNode.prototype, 'ownerDocument') as PropertyDescriptor\n\n const isPureNode = (target: unknown): boolean | void => {\n return (isScriptElement(target) || isBaseElement(target)) && target.__PURE_ELEMENT__\n }\n\n const getRawTarget = (parent: Node): Node => {\n if (parent === sandbox.microHead) {\n return rawDocument.head\n } else if (parent === sandbox.microBody) {\n return rawDocument.body\n }\n\n return parent\n }\n\n microRootNode.prototype.getRootNode = function getRootNode (): Node {\n return microDocument\n // TODO: 什么情况下返回原生document?\n // const rootNode = rawMicroGetRootNode.call(this, options)\n // if (rootNode === appInstanceMap.get(appName)?.container) return microDocument\n // return rootNode\n }\n\n microRootNode.prototype.appendChild = function appendChild <T extends Node> (node: T): T {\n // TODO: 有必要执行这么多次updateElementInfo?\n updateElementInfo(node, appName)\n if (isPureNode(node)) {\n return rawMicroAppendChild.call(this, node)\n }\n return rawRootElement.prototype.appendChild.call(getRawTarget(this), node)\n }\n\n microRootNode.prototype.insertBefore = function insertBefore <T extends Node> (node: T, child: Node | null): T {\n updateElementInfo(node, appName)\n if (isPureNode(node)) {\n return rawMicroInsertBefore.call(this, node, child)\n }\n return rawRootElement.prototype.insertBefore.call(getRawTarget(this), node, child)\n }\n\n microRootNode.prototype.replaceChild = function replaceChild <T extends Node> (node: Node, child: T): T {\n updateElementInfo(node, appName)\n if (isPureNode(node)) {\n return rawMicroReplaceChild.call(this, node, child)\n }\n return rawRootElement.prototype.replaceChild.call(getRawTarget(this), node, child)\n }\n\n microRootNode.prototype.removeChild = function removeChild<T extends Node> (oldChild: T): T {\n if (isPureNode(oldChild) || this.contains(oldChild)) {\n return rawMicroRemoveChild.call(this, oldChild)\n }\n return rawRootElement.prototype.removeChild.call(getRawTarget(this), oldChild)\n }\n\n microRootElement.prototype.append = function append (...nodes: (Node | string)[]): void {\n let i = 0; let hasPureNode = false\n while (i < nodes.length) {\n nodes[i] = isNode(nodes[i]) ? nodes[i] : microDocument.createTextNode(nodes[i])\n if (isPureNode(nodes[i])) hasPureNode = true\n i++\n }\n if (hasPureNode) {\n return rawMicroAppend.call(this, ...nodes)\n }\n return rawRootElement.prototype.append.call(getRawTarget(this), ...nodes)\n }\n\n microRootElement.prototype.prepend = function prepend (...nodes: (Node | string)[]): void {\n let i = 0; let hasPureNode = false\n while (i < nodes.length) {\n nodes[i] = isNode(nodes[i]) ? nodes[i] : microDocument.createTextNode(nodes[i])\n if (isPureNode(nodes[i])) hasPureNode = true\n i++\n }\n if (hasPureNode) {\n return rawMicroPrepend.call(this, ...nodes)\n }\n return rawRootElement.prototype.prepend.call(getRawTarget(this), ...nodes)\n }\n\n /**\n * The insertAdjacentElement method of the Element interface inserts a given element node at a given position relative to the element it is invoked upon.\n * Scenes:\n * 1. vite4 development env for style\n */\n microRootElement.prototype.insertAdjacentElement = function insertAdjacentElement (where: InsertPosition, element: Element): Element | null {\n updateElementInfo(element, appName)\n if (isPureNode(element)) {\n return rawMicroInsertAdjacentElement.call(this, where, element)\n }\n return rawRootElement.prototype.insertAdjacentElement.call(getRawTarget(this), where, element)\n }\n\n // patch cloneNode\n microRootNode.prototype.cloneNode = function cloneNode (deep?: boolean): Node {\n const clonedNode = rawMicroCloneNode.call(this, deep)\n return updateElementInfo(clonedNode, appName)\n }\n\n rawDefineProperty(microRootNode.prototype, 'ownerDocument', {\n configurable: true,\n enumerable: true,\n get () {\n return this.__PURE_ELEMENT__\n ? rawOwnerDocumentDesc.get!.call(this)\n : microDocument\n },\n })\n\n rawDefineProperty(microRootElement.prototype, 'innerHTML', {\n configurable: true,\n enumerable: true,\n get () {\n return rawInnerHTMLDesc.get!.call(this)\n },\n set (code: string) {\n rawInnerHTMLDesc.set!.call(this, code)\n Array.from(this.children).forEach((child) => {\n if (isElement(child)) {\n updateElementInfo(child, appName)\n }\n })\n }\n })\n\n // patch parentNode\n rawDefineProperty(microRootNode.prototype, 'parentNode', {\n configurable: true,\n enumerable: true,\n get () {\n /**\n * set current appName for hijack parentNode of html\n * NOTE:\n * 1. Is there a problem with setting the current appName in iframe mode\n */\n throttleDeferForSetAppName(appName)\n const result: ParentNode = rawParentNodeDesc.get!.call(this)\n /**\n * If parentNode is <micro-app-body>, return rawDocument.body\n * Scenes:\n * 1. element-ui@2/lib/utils/vue-popper.js\n * if (this.popperElm.parentNode === document.body) ...\n * WARNING:\n * Will it cause other problems ?\n * e.g. target.parentNode.remove(target)\n */\n if (isMicroAppBody(result) && appInstanceMap.get(appName)?.container) {\n return microApp.options.getRootElementParentNode?.(this, appName) || globalEnv.rawDocument.body\n }\n return result\n }\n })\n\n // Adapt to new image(...) scene\n const ImageProxy = new Proxy(microAppWindow.Image, {\n construct (Target, args): HTMLImageElement {\n const elementImage = new Target(...args)\n updateElementInfo(elementImage, appName)\n return elementImage\n },\n })\n\n rawDefineProperty(microAppWindow, 'Image', {\n configurable: true,\n writable: true,\n value: ImageProxy,\n })\n}\n\nfunction patchIframeAttribute (url: string, microAppWindow: microAppWindowType): void {\n const microRootElement = microAppWindow.Element\n const rawMicroSetAttribute = microRootElement.prototype.setAttribute\n\n microRootElement.prototype.setAttribute = function setAttribute (key: string, value: any): void {\n if (\n ((key === 'src' || key === 'srcset') && /^(img|script)$/i.test(this.tagName)) ||\n (key === 'href' && /^link$/i.test(this.tagName))\n ) {\n value = CompletionPath(value, url)\n }\n\n rawMicroSetAttribute.call(this, key, value)\n }\n\n const protoAttrList: Array<[HTMLElement, string]> = [\n [microAppWindow.HTMLImageElement.prototype, 'src'],\n [microAppWindow.HTMLScriptElement.prototype, 'src'],\n [microAppWindow.HTMLLinkElement.prototype, 'href'],\n ]\n\n /**\n * element.setAttribute does not trigger this actions:\n * 1. img.src = xxx\n * 2. script.src = xxx\n * 3. link.href = xxx\n */\n protoAttrList.forEach(([target, attr]) => {\n const { enumerable, configurable, get, set } = Object.getOwnPropertyDescriptor(target, attr) || {\n enumerable: true,\n configurable: true,\n }\n\n rawDefineProperty(target, attr, {\n enumerable,\n configurable,\n get: function () {\n return get?.call(this)\n },\n set: function (value) {\n set?.call(this, CompletionPath(value, url))\n },\n })\n })\n}\n","import type {\n microAppWindowType,\n MicroLocation,\n SandBoxStartParams,\n CommonEffectHook,\n SandBoxStopParams,\n releaseGlobalEffectParams,\n plugins,\n} from '@micro-app/types'\nimport globalEnv from '../../libs/global_env'\nimport microApp from '../../micro_app'\nimport {\n getEffectivePath,\n removeDomScope,\n pureCreateElement,\n assign,\n clearDOM,\n isPlainObject,\n isArray,\n defer,\n createURL,\n} from '../../libs/utils'\nimport {\n EventCenterForMicroApp,\n rebuildDataCenterSnapshot,\n recordDataCenterSnapshot,\n resetDataCenterSnapshot,\n} from '../../interact'\nimport {\n patchRouter,\n} from './router'\nimport {\n router,\n initRouteStateWithURL,\n clearRouteStateFromURL,\n addHistoryListener,\n removePathFromBrowser,\n updateBrowserURLWithLocation,\n patchHistory,\n releasePatchHistory,\n isRouterModeCustom,\n} from '../router'\nimport {\n patchElementAndDocument,\n releasePatchElementAndDocument,\n} from '../../source/patch'\nimport {\n patchWindow,\n} from './window'\nimport {\n patchDocument,\n} from './document'\nimport {\n patchElement,\n} from './element'\nimport {\n patchElementTree\n} from '../adapter'\n\nexport default class IframeSandbox {\n static activeCount = 0 // number of active sandbox\n private active = false\n private windowEffect!: CommonEffectHook\n private documentEffect!: CommonEffectHook\n private removeHistoryListener!: CallableFunction\n // Properties that can be escape to rawWindow\n public escapeProperties: PropertyKey[] = []\n // Properties escape to rawWindow, cleared when unmount\n public escapeKeys = new Set<PropertyKey>()\n public deleteIframeElement: () => void\n public iframe!: HTMLIFrameElement | null\n // Promise used to mark whether the sandbox is initialized\n public sandboxReady!: Promise<void>\n public proxyWindow: WindowProxy & microAppWindowType\n public microAppWindow: microAppWindowType\n public proxyLocation!: MicroLocation\n public baseElement!: HTMLBaseElement\n public microHead!: HTMLHeadElement\n public microBody!: HTMLBodyElement\n // TODO: 放到 super中定义,super(appName, url),with沙箱也需要简化\n public appName: string\n public url: string\n\n constructor (appName: string, url: string) {\n this.appName = appName\n this.url = url\n const rawLocation = globalEnv.rawWindow.location\n const browserHost = rawLocation.protocol + '//' + rawLocation.host\n\n this.deleteIframeElement = this.createIframeElement(appName, browserHost + rawLocation.pathname)\n this.microAppWindow = this.iframe!.contentWindow\n\n this.patchIframe(this.microAppWindow, (resolve: CallableFunction) => {\n // create new html to iframe\n this.createIframeTemplate(this.microAppWindow)\n // get escapeProperties from plugins\n this.getSpecialProperties(appName)\n // patch location & history of child app\n this.proxyLocation = patchRouter(appName, url, this.microAppWindow, browserHost)\n // patch window of child app\n this.windowEffect = patchWindow(appName, this.microAppWindow, this)\n // patch document of child app\n this.documentEffect = patchDocument(appName, this.microAppWindow, this)\n // patch Node & Element of child app\n patchElement(appName, url, this.microAppWindow, this)\n /**\n * create static properties\n * NOTE:\n * 1. execute as early as possible\n * 2. run after patchRouter & createProxyWindow\n */\n this.initStaticGlobalKeys(appName, url, this.microAppWindow)\n resolve()\n })\n }\n\n /**\n * create iframe for sandbox\n * @param appName app name\n * @param browserPath browser origin\n * @returns release callback\n */\n createIframeElement (\n appName: string,\n browserPath: string,\n ): () => void {\n this.iframe = pureCreateElement('iframe')\n\n const iframeAttrs: Record<string, string> = {\n src: microApp.options.iframeSrc || browserPath,\n style: 'display: none',\n id: appName,\n }\n\n Object.keys(iframeAttrs).forEach((key) => this.iframe!.setAttribute(key, iframeAttrs[key]))\n\n // effect action during construct\n globalEnv.rawDocument.body.appendChild(this.iframe)\n\n /**\n * If dom operated async when unmount, premature deletion of iframe will cause unexpected problems\n * e.g.\n * 1. antd: notification.destroy()\n * WARNING:\n * If async operation time is too long, defer cannot avoid the problem\n * TODO: more test\n */\n return () => defer(() => {\n // default mode or destroy, iframe will be deleted when unmount\n this.iframe?.parentNode?.removeChild(this.iframe)\n this.iframe = null\n })\n }\n\n public start ({\n baseroute,\n defaultPage,\n disablePatchRequest,\n }: SandBoxStartParams): void {\n if (this.active) return\n this.active = true\n /* --- memory router part --- start */\n /**\n * Sync router info to iframe when exec sandbox.start with disable or enable memory-router\n * e.g.:\n * vue-router@4.x get target path by remove the base section from rawLocation.pathname\n * code: window.location.pathname.slice(base.length) || '/'; (base is baseroute)\n * NOTE:\n * 1. iframe router and browser router are separated, we should update iframe router manually\n * 2. withSandbox location is browser location when disable memory-router, so no need to do anything\n */\n /**\n * TODO:\n * 1. iframe关闭虚拟路由系统后,default-page无法使用,推荐用户直接使用浏览器地址控制首页渲染\n * 补充:keep-router-state 也无法配置,因为keep-router-state一定为true。\n * 2. 导航拦截、current.route 可以正常使用\n * 3. 可以正常控制子应用跳转,方式还是自上而下(也可以是子应用内部跳转,这种方式更好一点,减小对基座的影响,不会导致vue的循环刷新)\n * 4. 关闭虚拟路由以后会对应 route-mode='custom' 模式,包括with沙箱也会这么做\n * 5. 关闭虚拟路由是指尽可能模拟没有虚拟路由的情况,子应用直接获取浏览器location和history,控制浏览器跳转\n */\n this.initRouteState(defaultPage)\n\n // unique listener of popstate event for child app\n this.removeHistoryListener = addHistoryListener(\n this.microAppWindow.__MICRO_APP_NAME__,\n )\n\n if (isRouterModeCustom(this.microAppWindow.__MICRO_APP_NAME__)) {\n this.microAppWindow.__MICRO_APP_BASE_ROUTE__ = this.microAppWindow.__MICRO_APP_BASE_URL__ = baseroute\n }\n /* --- memory router part --- end */\n\n /**\n * create base element to iframe\n * WARNING: This will also affect a, image, link and script\n */\n if (!disablePatchRequest) {\n this.createIframeBase()\n }\n\n if (++globalEnv.activeSandbox === 1) {\n patchElementAndDocument()\n patchHistory()\n }\n\n if (++IframeSandbox.activeCount === 1) {\n // TODO: 多层嵌套兼容\n }\n }\n\n public stop ({\n umdMode,\n keepRouteState,\n destroy,\n clearData,\n }: SandBoxStopParams): void {\n if (!this.active) return\n this.recordAndReleaseEffect({ clearData }, !umdMode || destroy)\n\n /* --- memory router part --- start */\n // if keep-route-state is true, preserve microLocation state\n this.clearRouteState(keepRouteState)\n\n // release listener of popstate for child app\n this.removeHistoryListener?.()\n /* --- memory router part --- end */\n\n if (!umdMode || destroy) {\n this.deleteIframeElement()\n\n this.escapeKeys.forEach((key: PropertyKey) => {\n Reflect.deleteProperty(globalEnv.rawWindow, key)\n })\n this.escapeKeys.clear()\n }\n\n if (--globalEnv.activeSandbox === 0) {\n releasePatchElementAndDocument()\n releasePatchHistory()\n }\n\n if (--IframeSandbox.activeCount === 0) {\n // TODO: Is there anything to put here?\n }\n\n this.active = false\n }\n\n /**\n * create static properties\n * NOTE:\n * 1. execute as early as possible\n * 2. run after patchRouter & createProxyWindow\n * TODO: 设置为只读变量\n */\n private initStaticGlobalKeys (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n ): void {\n microAppWindow.__MICRO_APP_ENVIRONMENT__ = true\n microAppWindow.__MICRO_APP_NAME__ = appName\n microAppWindow.__MICRO_APP_URL__ = url\n microAppWindow.__MICRO_APP_PUBLIC_PATH__ = getEffectivePath(url)\n microAppWindow.__MICRO_APP_BASE_ROUTE__ = ''\n microAppWindow.__MICRO_APP_WINDOW__ = microAppWindow\n microAppWindow.__MICRO_APP_PRE_RENDER__ = false\n microAppWindow.__MICRO_APP_UMD_MODE__ = false\n microAppWindow.__MICRO_APP_PROXY_WINDOW__ = this.proxyWindow\n microAppWindow.__MICRO_APP_SANDBOX__ = this\n microAppWindow.__MICRO_APP_SANDBOX_TYPE__ = 'iframe'\n microAppWindow.rawWindow = globalEnv.rawWindow\n microAppWindow.rawDocument = globalEnv.rawDocument\n microAppWindow.microApp = assign(new EventCenterForMicroApp(appName), {\n removeDomScope,\n pureCreateElement,\n location: this.proxyLocation,\n router,\n })\n }\n\n /**\n * Record global effect and then release (effect: global event, timeout, data listener)\n * Scenes:\n * 1. unmount of default/umd app\n * 2. hidden keep-alive app\n * 3. after init prerender app\n * @param options {\n * @param clearData clear data from base app\n * @param isPrerender is prerender app\n * @param keepAlive is keep-alive app\n * }\n * @param preventRecord prevent record effect events (default or destroy)\n */\n public recordAndReleaseEffect (\n options: releaseGlobalEffectParams,\n preventRecord = false,\n ): void {\n if (preventRecord) {\n this.resetEffectSnapshot()\n } else {\n this.recordEffectSnapshot()\n }\n this.releaseGlobalEffect(options)\n }\n\n /**\n * reset effect snapshot data in default mode or destroy\n * Scenes:\n * 1. unmount hidden keep-alive app manually\n * 2. unmount prerender app manually\n */\n public resetEffectSnapshot (): void {\n this.windowEffect?.reset()\n this.documentEffect?.reset()\n resetDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n /**\n * record umd snapshot before the first execution of umdHookMount\n * Scenes:\n * 1. exec umdMountHook in umd mode\n * 2. hidden keep-alive app\n * 3. after init prerender app\n */\n public recordEffectSnapshot (): void {\n this.windowEffect?.record()\n this.documentEffect?.record()\n recordDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n // rebuild umd snapshot before remount umd app\n public rebuildEffectSnapshot (): void {\n this.windowEffect?.rebuild()\n this.documentEffect?.rebuild()\n rebuildDataCenterSnapshot(this.microAppWindow.microApp)\n }\n\n /**\n * clear global event, timeout, data listener\n * Scenes:\n * 1. unmount of normal/umd app\n * 2. hidden keep-alive app\n * 3. after init prerender app\n * @param clearData clear data from base app\n * @param isPrerender is prerender app\n * @param keepAlive is keep-alive app\n */\n public releaseGlobalEffect ({ clearData = false }: releaseGlobalEffectParams): void {\n this.windowEffect?.release()\n this.documentEffect?.release()\n this.microAppWindow.microApp?.clearDataListener()\n this.microAppWindow.microApp?.clearGlobalDataListener()\n if (clearData) {\n microApp.clearData(this.microAppWindow.__MICRO_APP_NAME__)\n this.microAppWindow.microApp?.clearData()\n }\n }\n\n // set __MICRO_APP_PRE_RENDER__ state\n public setPreRenderState (state: boolean): void {\n this.microAppWindow.__MICRO_APP_PRE_RENDER__ = state\n }\n\n // record umdMode\n public markUmdMode (state: boolean): void {\n this.microAppWindow.__MICRO_APP_UMD_MODE__ = state\n }\n\n // TODO: RESTRUCTURE\n private patchIframe (microAppWindow: microAppWindowType, cb: CallableFunction): void {\n const oldMicroDocument = microAppWindow.document\n this.sandboxReady = new Promise<void>((resolve) => {\n (function iframeLocationReady () {\n setTimeout(() => {\n try {\n /**\n * NOTE:\n * 1. In browser, iframe document will be recreated after iframe initial\n * 2. In jest, iframe document is always the same\n */\n if (microAppWindow.document === oldMicroDocument && !__TEST__) {\n iframeLocationReady()\n } else {\n /**\n * NOTE:\n * 1. microAppWindow will not be recreated\n * 2. the properties of microAppWindow may be recreated, such as document\n * 3. the variables added to microAppWindow may be cleared\n */\n microAppWindow.stop()\n cb(resolve)\n }\n } catch (e) {\n iframeLocationReady()\n }\n }, 0)\n })()\n })\n }\n\n // TODO: RESTRUCTURE\n private createIframeTemplate (microAppWindow: microAppWindowType): void {\n const microDocument = microAppWindow.document\n clearDOM(microDocument)\n const html = microDocument.createElement('html')\n html.innerHTML = '<head></head><body></body>'\n microDocument.appendChild(html)\n\n // 记录iframe原生body\n this.microBody = microDocument.body\n this.microHead = microDocument.head\n }\n\n /**\n * baseElement will complete the relative address of element according to the URL\n * e.g: a image link script fetch ajax EventSource\n */\n private createIframeBase (): void {\n this.baseElement = pureCreateElement('base')\n this.updateIframeBase()\n this.microHead.appendChild(this.baseElement)\n }\n\n // 初始化和每次跳转时都要更新base的href\n public updateIframeBase = (): void => {\n // origin must be child app origin\n this.baseElement?.setAttribute('href', createURL(this.url).origin + this.proxyLocation.pathname)\n }\n\n /**\n * get escapeProperties from plugins & adapter\n * @param appName app name\n */\n private getSpecialProperties (appName: string): void {\n if (isPlainObject(microApp.options.plugins)) {\n this.commonActionForSpecialProperties(microApp.options.plugins.global)\n this.commonActionForSpecialProperties(microApp.options.plugins.modules?.[appName])\n }\n }\n\n // common action for global plugins and module plugins\n private commonActionForSpecialProperties (plugins: plugins['global']) {\n if (isArray(plugins)) {\n for (const plugin of plugins) {\n if (isPlainObject(plugin)) {\n if (isArray(plugin.escapeProperties)) {\n this.escapeProperties = this.escapeProperties.concat(plugin.escapeProperties)\n }\n }\n }\n }\n }\n\n private initRouteState (defaultPage: string): void {\n initRouteStateWithURL(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.location as MicroLocation,\n defaultPage,\n )\n }\n\n private clearRouteState (keepRouteState: boolean): void {\n clearRouteStateFromURL(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.__MICRO_APP_URL__,\n this.microAppWindow.location as MicroLocation,\n keepRouteState,\n )\n }\n\n public setRouteInfoForKeepAliveApp (): void {\n updateBrowserURLWithLocation(\n this.microAppWindow.__MICRO_APP_NAME__,\n this.microAppWindow.location as MicroLocation,\n )\n }\n\n public removeRouteInfoForKeepAliveApp (): void {\n removePathFromBrowser(this.microAppWindow.__MICRO_APP_NAME__)\n }\n\n /**\n * Format all html elements when init\n * @param container micro app container\n */\n public patchStaticElement (container: Element | ShadowRoot): void {\n patchElementTree(container, this.microAppWindow.__MICRO_APP_NAME__)\n }\n\n /**\n * action before exec scripts when mount\n * Actions:\n * 1. patch static elements from html\n * @param container micro app container\n */\n public actionBeforeExecScripts (container: Element | ShadowRoot): void {\n this.patchStaticElement(container)\n }\n\n public setStaticAppState (state: string): void {\n this.microAppWindow.__MICRO_APP_STATE__ = state\n }\n}\n","import type {\n microAppWindowType,\n MicroLocation,\n} from '@micro-app/types'\nimport {\n createMicroLocation,\n updateMicroLocation,\n} from '../router/location'\nimport {\n createMicroHistory,\n} from '../router/history'\nimport {\n assign,\n createURL,\n} from '../../libs/utils'\n\nexport function patchRouter (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n browserHost: string,\n): MicroLocation {\n const childStaticLocation = createURL(url)\n const childHost = childStaticLocation.protocol + '//' + childStaticLocation.host\n const childFullPath = childStaticLocation.pathname + childStaticLocation.search + childStaticLocation.hash\n\n // rewrite microAppWindow.history\n const microHistory = microAppWindow.history\n microAppWindow.rawReplaceState = microHistory.replaceState\n assign(microHistory, createMicroHistory(appName, microAppWindow.location))\n\n /**\n * Init microLocation before exec sandbox.start\n * NOTE:\n * 1. exec updateMicroLocation after patch microHistory\n * 2. sandbox.start will sync microLocation info to browser url\n */\n updateMicroLocation(\n appName,\n childFullPath,\n microAppWindow.location,\n 'prevent'\n )\n\n // create proxyLocation\n return createMicroLocation(\n appName,\n url,\n microAppWindow,\n childStaticLocation,\n browserHost,\n childHost,\n )\n}\n","import type {\n Func,\n AppInterface,\n sourceType,\n WithSandBoxInterface,\n MountParam,\n UnmountParam,\n OnLoadParam,\n} from '@micro-app/types'\nimport { HTMLLoader } from './source/loader/html'\nimport { extractSourceDom } from './source/index'\nimport { execScripts } from './source/scripts'\nimport WithSandBox from './sandbox/with'\nimport IframeSandbox from './sandbox/iframe'\nimport { router, isRouterModeSearch } from './sandbox/router'\nimport {\n appStates,\n lifeCycles,\n keepAliveStates,\n microGlobalEvent,\n DEFAULT_ROUTER_MODE,\n} from './constants'\nimport {\n isFunction,\n isPromise,\n logError,\n getRootContainer,\n isObject,\n execMicroAppGlobalHook,\n pureCreateElement,\n isDivElement,\n removeDomScope,\n} from './libs/utils'\nimport dispatchLifecyclesEvent, {\n dispatchCustomEventToMicroApp,\n} from './interact/lifecycles_event'\nimport globalEnv from './libs/global_env'\nimport microApp from './micro_app'\nimport sourceCenter from './source/source_center'\n\n// micro app instances\nexport const appInstanceMap = new Map<string, AppInterface>()\n\n// params of CreateApp\nexport interface CreateAppParam {\n name: string\n url: string\n scopecss: boolean\n useSandbox: boolean\n inline?: boolean\n iframe?: boolean\n container?: HTMLElement | ShadowRoot\n ssrUrl?: string\n isPrefetch?: boolean\n prefetchLevel?: number\n routerMode?: string\n}\n\nexport default class CreateApp implements AppInterface {\n private state: string = appStates.CREATED\n private keepAliveState: string | null = null\n private loadSourceLevel: -1|0|1|2 = 0\n private umdHookMount: Func | null = null\n private umdHookUnmount: Func | null = null\n private preRenderEvents?: CallableFunction[] | null\n private lifeCycleState: string | null = null\n public umdMode = false\n public source: sourceType\n // TODO: 类型优化,加上iframe沙箱\n public sandBox: WithSandBoxInterface | IframeSandbox | null = null\n public name: string\n public url: string\n public container: HTMLElement | ShadowRoot | null\n public scopecss: boolean\n public useSandbox: boolean\n public inline: boolean\n public iframe: boolean\n public ssrUrl: string\n public isPrefetch: boolean\n public isPrerender: boolean\n public prefetchLevel?: number\n public fiber = false\n public routerMode: string\n\n constructor ({\n name,\n url,\n container,\n scopecss,\n useSandbox,\n inline,\n iframe,\n ssrUrl,\n isPrefetch,\n prefetchLevel,\n routerMode,\n }: CreateAppParam) {\n appInstanceMap.set(name, this)\n // init actions\n this.name = name\n this.url = url\n this.useSandbox = useSandbox\n this.scopecss = this.useSandbox && scopecss\n // exec before getInlineModeState\n this.iframe = iframe ?? false\n this.inline = this.getInlineModeState(inline)\n /**\n * NOTE:\n * 1. Navigate after micro-app created, before mount\n */\n this.routerMode = routerMode || DEFAULT_ROUTER_MODE\n\n // not exist when prefetch 👇\n this.container = container ?? null\n this.ssrUrl = ssrUrl ?? ''\n\n // exist only prefetch 👇\n this.isPrefetch = isPrefetch ?? false\n this.isPrerender = prefetchLevel === 3\n this.prefetchLevel = prefetchLevel\n\n this.source = { html: null, links: new Set(), scripts: new Set() }\n this.loadSourceCode()\n this.createSandbox()\n }\n\n // Load resources\n public loadSourceCode (): void {\n this.setAppState(appStates.LOADING)\n HTMLLoader.getInstance().run(this, extractSourceDom)\n }\n\n /**\n * When resource is loaded, mount app if it is not prefetch or unmount\n * defaultPage disablePatchRequest routerMode baseroute is only for prerender app\n */\n public onLoad ({\n html,\n // below params is only for prerender app\n defaultPage,\n routerMode,\n baseroute,\n disablePatchRequest,\n }: OnLoadParam): void {\n if (++this.loadSourceLevel === 2) {\n this.source.html = html\n\n if (!this.isPrefetch && !this.isUnmounted()) {\n getRootContainer(this.container!).mount(this)\n } else if (this.isPrerender) {\n /**\n * PreRender is an option of prefetch, it will render app during prefetch\n * Limit:\n * 1. fiber forced on\n * 2. only virtual router support\n *\n * NOTE: (Don't update browser url, dispatch popstateEvent, reload window, dispatch lifecycle event)\n * 1. pushState/replaceState in child can update microLocation, but will not attach router info to browser url\n * 2. prevent dispatch popstate/hashchange event to browser\n * 3. all navigation actions of location are invalid (In the future, we can consider update microLocation without trigger browser reload)\n * 4. lifecycle event will not trigger when prerender\n *\n * Special scenes\n * 1. unmount prerender app when loading\n * 2. unmount prerender app when exec js\n * 2. unmount prerender app after exec js\n */\n const container = pureCreateElement('div')\n container.setAttribute('prerender', 'true')\n this.sandBox?.setPreRenderState(true)\n this.mount({\n container,\n inline: this.inline,\n fiber: true,\n defaultPage: defaultPage || '',\n disablePatchRequest: disablePatchRequest ?? false,\n routerMode: routerMode!,\n baseroute: baseroute || '',\n })\n }\n }\n }\n\n /**\n * Error loading HTML\n * @param e Error\n */\n public onLoadError (e: Error): void {\n this.loadSourceLevel = -1\n\n if (!this.isUnmounted()) {\n this.onerror(e)\n this.setAppState(appStates.LOAD_FAILED)\n }\n }\n\n /**\n * mount app\n * @param container app container\n * @param inline run js in inline mode\n * @param routerMode virtual router mode\n * @param defaultPage default page of virtual router\n * @param baseroute route prefix, default is ''\n * @param disablePatchRequest prevent rewrite request method of child app\n * @param fiber run js in fiber mode\n */\n public mount ({\n container,\n inline,\n routerMode,\n defaultPage,\n baseroute,\n disablePatchRequest,\n fiber,\n }: MountParam): void {\n if (this.loadSourceLevel !== 2) {\n /**\n * container cannot be null when load end\n * NOTE:\n * 1. render prefetch app before load end\n * 2. unmount prefetch app and mount again before load end\n */\n this.container = container\n // mount before prerender exec mount (loading source), set isPrerender to false\n this.isPrerender = false\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.LOADING\n })\n\n // reset app state to LOADING\n return this.setAppState(appStates.LOADING)\n }\n\n this.createSandbox()\n\n // place outside of nextAction, as nextAction may execute async\n this.setAppState(appStates.BEFORE_MOUNT)\n\n const nextAction = () => {\n /**\n * Special scenes:\n * 1. mount before prerender exec mount (loading source)\n * 2. mount when prerender js executing\n * 3. mount after prerender js exec end\n * 4. mount after prerender unmounted\n *\n * TODO: test shadowDOM\n */\n if (\n this.isPrerender &&\n isDivElement(this.container) &&\n this.container.hasAttribute('prerender')\n ) {\n /**\n * rebuild effect event of window, document, data center\n * explain:\n * 1. rebuild before exec mount, do nothing\n * 2. rebuild when js executing, recovery recorded effect event, because prerender fiber mode\n * 3. rebuild after js exec end, normal recovery effect event\n */\n this.sandBox?.rebuildEffectSnapshot()\n // current this.container is <div prerender='true'></div>\n this.cloneContainer(container as Element, this.container as Element, false)\n /**\n * set this.container to <micro-app></micro-app>\n * NOTE:\n * must exec before this.preRenderEvents?.forEach((cb) => cb())\n */\n this.container = container\n this.preRenderEvents?.forEach((cb) => cb())\n // reset isPrerender config\n this.isPrerender = false\n this.preRenderEvents = null\n // attach router info to browser url\n router.attachToURL(this.name)\n this.sandBox?.setPreRenderState(false)\n } else {\n this.container = container\n this.inline = this.getInlineModeState(inline)\n this.fiber = fiber\n this.routerMode = routerMode\n\n const dispatchBeforeMount = () => {\n this.setLifeCycleState(lifeCycles.BEFOREMOUNT)\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.BEFOREMOUNT,\n )\n }\n\n if (this.isPrerender) {\n (this.preRenderEvents ??= []).push(dispatchBeforeMount)\n } else {\n dispatchBeforeMount()\n }\n\n this.setAppState(appStates.MOUNTING)\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.MOUNTING\n })\n\n // TODO: 将所有cloneContainer中的'as Element'去掉,兼容shadowRoot的场景\n this.cloneContainer(this.container as Element, this.source.html as Element, !this.umdMode)\n\n this.sandBox?.start({\n umdMode: this.umdMode,\n baseroute,\n defaultPage,\n disablePatchRequest,\n })\n\n if (!this.umdMode) {\n // update element info of html\n this.sandBox?.actionBeforeExecScripts(this.container)\n // if all js are executed, param isFinished will be true\n execScripts(this, (isFinished: boolean) => {\n if (!this.umdMode) {\n const { mount, unmount } = this.getUmdLibraryHooks()\n /**\n * umdHookUnmount can works in default mode\n * register through window.unmount\n */\n // TODO: 不对,这里要改,因为unmount不一定是函数\n this.umdHookUnmount = unmount as Func\n // if mount & unmount is function, the sub app is umd mode\n if (isFunction(mount) && isFunction(unmount)) {\n this.umdHookMount = mount as Func\n // sandbox must exist\n this.sandBox!.markUmdMode(this.umdMode = true)\n try {\n this.handleMounted(this.umdHookMount(microApp.getData(this.name, true)))\n } catch (e) {\n /**\n * TODO:\n * 1. 是否应该直接抛出错误\n * 2. 是否应该触发error生命周期\n */\n logError('An error occurred in window.mount \\n', this.name, e)\n }\n } else if (isFinished === true) {\n this.handleMounted()\n }\n }\n })\n } else {\n this.sandBox?.rebuildEffectSnapshot()\n try {\n this.handleMounted(this.umdHookMount!(microApp.getData(this.name, true)))\n } catch (e) {\n logError('An error occurred in window.mount \\n', this.name, e)\n }\n }\n }\n }\n\n // TODO: 可优化?\n this.sandBox ? this.sandBox.sandboxReady.then(nextAction) : nextAction()\n }\n\n /**\n * handle for promise umdHookMount\n * @param umdHookMountResult result of umdHookMount\n */\n private handleMounted (umdHookMountResult?: unknown): void {\n const dispatchAction = () => {\n if (isPromise(umdHookMountResult)) {\n umdHookMountResult\n .then(() => this.dispatchMountedEvent())\n .catch((e) => {\n logError('An error occurred in window.mount \\n', this.name, e)\n this.dispatchMountedEvent()\n })\n } else {\n this.dispatchMountedEvent()\n }\n }\n\n if (this.isPrerender) {\n this.preRenderEvents?.push(dispatchAction)\n this.sandBox?.recordAndReleaseEffect({ isPrerender: true })\n } else {\n dispatchAction()\n }\n }\n\n /**\n * dispatch mounted event when app run finished\n */\n private dispatchMountedEvent (): void {\n if (!this.isUnmounted()) {\n this.setAppState(appStates.MOUNTED)\n // call window.onmount of child app\n execMicroAppGlobalHook(\n this.getMicroAppGlobalHook(microGlobalEvent.ONMOUNT),\n this.name,\n microGlobalEvent.ONMOUNT,\n microApp.getData(this.name, true)\n )\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.MOUNTED\n })\n\n // dispatch mounted event to micro app\n dispatchCustomEventToMicroApp(this, 'mounted')\n\n this.setLifeCycleState(lifeCycles.MOUNTED)\n\n // dispatch event mounted to parent\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.MOUNTED,\n )\n\n /**\n * Hidden Keep-alive app during resource loading, render normally to ensure their liveliness (running in the background) characteristics.\n * Actions:\n * 1. Record & release all global events after mount\n */\n if (this.isHidden()) {\n this.sandBox?.recordAndReleaseEffect({ keepAlive: true })\n }\n }\n /**\n * TODO: 这里增加一个处理,如果渲染完成时已经卸载,则进行一些操作\n * 如果是默认模式:删除所有事件和定时器\n * 如果是umd模式:重新记录和清空事件\n * 补充:非必需,优先级低\n */\n }\n\n /**\n * unmount app\n * NOTE:\n * 1. do not add any params on account of unmountApp\n * @param destroy completely destroy, delete cache resources\n * @param clearData clear data of dateCenter\n * @param keepRouteState keep route state when unmount, default is false\n * @param unmountcb callback of unmount\n */\n public unmount ({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n }: UnmountParam): void {\n destroy = destroy || this.state === appStates.LOAD_FAILED\n\n this.setAppState(appStates.UNMOUNT)\n\n let umdHookUnmountResult: unknown = null\n try {\n // call umd unmount hook before the sandbox is cleared\n umdHookUnmountResult = this.umdHookUnmount?.(microApp.getData(this.name, true))\n } catch (e) {\n logError('An error occurred in window.unmount \\n', this.name, e)\n }\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.UNMOUNT\n })\n\n // dispatch unmount event to micro app\n dispatchCustomEventToMicroApp(this, 'unmount')\n\n // call window.onunmount of child app\n execMicroAppGlobalHook(\n this.getMicroAppGlobalHook(microGlobalEvent.ONUNMOUNT),\n this.name,\n microGlobalEvent.ONUNMOUNT,\n )\n\n this.handleUnmounted({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n umdHookUnmountResult,\n })\n }\n\n /**\n * handle for promise umdHookUnmount\n * @param destroy completely destroy, delete cache resources\n * @param clearData clear data of dateCenter\n * @param keepRouteState keep route state when unmount, default is false\n * @param unmountcb callback of unmount\n * @param umdHookUnmountResult result of umdHookUnmount\n */\n private handleUnmounted ({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n umdHookUnmountResult,\n }: UnmountParam & {\n umdHookUnmountResult: unknown,\n }): void {\n const nextAction = () => this.actionsForUnmount({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n })\n\n if (isPromise(umdHookUnmountResult)) {\n // async window.unmount will cause appName bind error in nest app\n removeDomScope()\n umdHookUnmountResult.then(nextAction).catch(nextAction)\n } else {\n nextAction()\n }\n }\n\n /**\n * actions for unmount app\n * @param destroy completely destroy, delete cache resources\n * @param clearData clear data of dateCenter\n * @param keepRouteState keep route state when unmount, default is false\n * @param unmountcb callback of unmount\n */\n private actionsForUnmount ({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n }: UnmountParam): void {\n if (this.umdMode && this.container && !destroy) {\n this.cloneContainer(this.source.html as Element, this.container, false)\n }\n\n /**\n * this.container maybe contains micro-app element, stop sandbox should exec after cloneContainer\n * NOTE:\n * 1. if destroy is true, clear route state\n * 2. umd mode and keep-alive will not clear EventSource\n */\n this.sandBox?.stop({\n umdMode: this.umdMode,\n keepRouteState: keepRouteState && !destroy,\n destroy,\n clearData: clearData || destroy,\n })\n\n this.setLifeCycleState(lifeCycles.UNMOUNT)\n\n // dispatch unmount event to base app\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.UNMOUNT,\n )\n\n this.clearOptions(destroy)\n\n unmountcb?.()\n }\n\n private clearOptions (destroy: boolean): void {\n this.container!.innerHTML = ''\n this.container = null\n this.isPrerender = false\n this.preRenderEvents = null\n this.setKeepAliveState(null)\n // in iframe sandbox & default mode, delete the sandbox & iframeElement\n // TODO: with沙箱与iframe沙箱保持一致:with沙箱默认模式下删除 或者 iframe沙箱umd模式下保留\n if (this.iframe && !this.umdMode) this.sandBox = null\n if (destroy) this.actionsForCompletelyDestroy()\n removeDomScope()\n }\n\n // actions for completely destroy\n public actionsForCompletelyDestroy (): void {\n this.sandBox?.deleteIframeElement?.()\n sourceCenter.script.deleteInlineInfo(this.source.scripts)\n appInstanceMap.delete(this.name)\n }\n\n // hidden app when disconnectedCallback called with keep-alive\n public hiddenKeepAliveApp (callback?: CallableFunction): void {\n this.setKeepAliveState(keepAliveStates.KEEP_ALIVE_HIDDEN)\n /**\n * afterhidden事件需要提前发送,原因如下:\n * 1. 此时发送this.container还指向micro-app元素,而不是临时div元素\n * 2. 沙箱执行recordAndReleaseEffect后会将appstate-change方法也清空,之后再发送子应用也接受不到了\n * 3. 对于this.loadSourceLevel !== 2的情况,unmount是同步执行的,所以也会出现2的问题\n * TODO: 有可能导致的问题\n * 1. 在基座接受到afterhidden方法后立即执行unmount,彻底destroy应用时,因为unmount时同步执行,所以this.container为null后才执行cloneContainer\n */\n dispatchCustomEventToMicroApp(this, 'appstate-change', {\n appState: 'afterhidden',\n })\n\n this.setLifeCycleState(lifeCycles.AFTERHIDDEN)\n // dispatch afterHidden event to base app\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.AFTERHIDDEN,\n )\n\n if (isRouterModeSearch(this.name)) {\n // called after lifeCyclesEvent\n this.sandBox?.removeRouteInfoForKeepAliveApp()\n }\n\n /**\n * Hidden app before the resources are loaded, then unmount the app\n */\n if (this.loadSourceLevel !== 2) {\n getRootContainer(this.container!).unmount()\n } else {\n this.container = this.cloneContainer(\n pureCreateElement('div'),\n this.container as Element,\n false,\n )\n\n this.sandBox?.recordAndReleaseEffect({ keepAlive: true })\n }\n\n callback?.()\n }\n\n // show app when connectedCallback called with keep-alive\n public showKeepAliveApp (container: HTMLElement | ShadowRoot): void {\n this.sandBox?.rebuildEffectSnapshot()\n\n // dispatch beforeShow event to micro-app\n dispatchCustomEventToMicroApp(this, 'appstate-change', {\n appState: 'beforeshow',\n })\n\n // dispatch beforeShow event to base app\n dispatchLifecyclesEvent(\n container,\n this.name,\n lifeCycles.BEFORESHOW,\n )\n\n this.setKeepAliveState(keepAliveStates.KEEP_ALIVE_SHOW)\n\n this.container = this.cloneContainer(\n container,\n this.container as Element,\n false,\n )\n\n /**\n * TODO:\n * 问题:当路由模式为custom时,keep-alive应用在重新展示,是否需要根据子应用location信息更新浏览器地址?\n * 暂时不这么做吧,因为无法确定二次展示时新旧地址是否相同,是否带有特殊信息\n */\n if (isRouterModeSearch(this.name)) {\n // called before lifeCyclesEvent\n this.sandBox?.setRouteInfoForKeepAliveApp()\n }\n\n // dispatch afterShow event to micro-app\n dispatchCustomEventToMicroApp(this, 'appstate-change', {\n appState: 'aftershow',\n })\n\n this.setLifeCycleState(lifeCycles.AFTERSHOW)\n\n // dispatch afterShow event to base app\n dispatchLifecyclesEvent(\n this.container,\n this.name,\n lifeCycles.AFTERSHOW,\n )\n }\n\n /**\n * app rendering error\n * @param e Error\n */\n public onerror (e: Error): void {\n this.setLifeCycleState(lifeCycles.ERROR)\n\n // dispatch state event to micro app\n dispatchCustomEventToMicroApp(this, 'statechange', {\n appState: appStates.LOAD_FAILED\n })\n\n dispatchLifecyclesEvent(\n this.container!,\n this.name,\n lifeCycles.ERROR,\n e,\n )\n }\n\n /**\n * Parse htmlString to DOM\n * NOTE: iframe sandbox will use DOMParser of iframeWindow, with sandbox will use DOMParser of base app\n * @param htmlString DOMString\n * @returns parsed DOM\n */\n public parseHtmlString (htmlString: string): HTMLElement {\n const DOMParser = this.sandBox?.proxyWindow\n ? this.sandBox.proxyWindow.DOMParser\n : globalEnv.rawWindow.DOMParser\n return (new DOMParser()).parseFromString(htmlString, 'text/html').body\n }\n\n /**\n * clone origin elements to target\n * @param origin Cloned element\n * @param target Accept cloned elements\n * @param deep deep clone or transfer dom\n */\n private cloneContainer <T extends Element | ShadowRoot, Q extends Element | ShadowRoot> (\n target: Q,\n origin: T,\n deep: boolean,\n ): Q {\n // 在基座接受到afterhidden方法后立即执行unmount,彻底destroy应用时,因为unmount时同步执行,所以this.container为null后才执行cloneContainer\n if (origin) {\n target.innerHTML = ''\n Array.from(deep ? this.parseHtmlString(origin.innerHTML).childNodes : origin.childNodes).forEach((node) => {\n target.appendChild(node)\n })\n }\n return target\n }\n\n /**\n * Scene:\n * 1. create app\n * 2. remount of default mode with iframe sandbox\n * In default mode with iframe sandbox, unmount app will delete iframeElement & sandBox, and create sandBox when mount again, used to solve the problem that module script cannot be execute when append it again\n */\n private createSandbox (): void {\n if (this.useSandbox && !this.sandBox) {\n this.sandBox = this.iframe ? new IframeSandbox(this.name, this.url) : new WithSandBox(this.name, this.url)\n }\n }\n\n // set app state\n public setAppState (state: string): void {\n this.state = state\n\n // set window.__MICRO_APP_STATE__\n this.sandBox?.setStaticAppState(state)\n }\n\n // get app state\n public getAppState (): string {\n return this.state\n }\n\n // set app lifeCycleState\n private setLifeCycleState (state: string): void {\n this.lifeCycleState = state\n }\n\n // get app lifeCycleState\n public getLifeCycleState (): string {\n return this.lifeCycleState || ''\n }\n\n // set keep-alive state\n private setKeepAliveState (state: string | null): void {\n this.keepAliveState = state\n }\n\n // get keep-alive state\n public getKeepAliveState (): string | null {\n return this.keepAliveState\n }\n\n // is app unmounted\n public isUnmounted (): boolean {\n return appStates.UNMOUNT === this.state\n }\n\n // is app already hidden\n public isHidden (): boolean {\n return keepAliveStates.KEEP_ALIVE_HIDDEN === this.keepAliveState\n }\n\n // get umd library, if it not exist, return empty object\n private getUmdLibraryHooks (): Record<string, unknown> {\n // after execScripts, the app maybe unmounted\n if (!this.isUnmounted() && this.sandBox) {\n const libraryName = getRootContainer(this.container!).getAttribute('library') || `micro-app-${this.name}`\n\n const proxyWindow = this.sandBox.proxyWindow as Record<string, any>\n\n // compatible with pre versions\n if (isObject(proxyWindow[libraryName])) {\n return proxyWindow[libraryName]\n }\n\n return {\n mount: proxyWindow.mount,\n unmount: proxyWindow.unmount,\n }\n }\n\n return {}\n }\n\n private getMicroAppGlobalHook (eventName: string): Func | null {\n const listener = (this.sandBox?.proxyWindow as Record<string, any>)?.[eventName]\n return isFunction(listener) ? listener : null\n }\n\n public querySelector (selectors: string): Node | null {\n return this.container ? globalEnv.rawElementQuerySelector.call(this.container, selectors) : null\n }\n\n public querySelectorAll (selectors: string): NodeListOf<Node> {\n return this.container ? globalEnv.rawElementQuerySelectorAll.call(this.container, selectors) : []\n }\n\n /**\n * NOTE:\n * 1. If the iframe sandbox no longer enforces the use of inline mode in the future, the way getElementsByTagName retrieves the script from the iframe by default needs to be changed, because in non inline mode, the script in the iframe may be empty\n * @param inline inline mode config\n */\n private getInlineModeState (inline?: boolean): boolean {\n return (this.iframe || inline) ?? false\n }\n}\n\n// iframe route mode\nexport function isIframeSandbox (appName: string): boolean {\n return appInstanceMap.get(appName)?.iframe ?? false\n}\n","import type {\n Func,\n AppInterface,\n} from '@micro-app/types'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} from '../create_app'\nimport {\n CompletionPath,\n getCurrentAppName,\n pureCreateElement,\n removeDomScope,\n isInvalidQuerySelectorKey,\n isUniqueElement,\n isProxyDocument,\n isFunction,\n isElement,\n isNode,\n rawDefineProperty,\n rawDefineProperties,\n isLinkElement,\n isStyleElement,\n isScriptElement,\n isIFrameElement,\n isMicroAppBody,\n} from '../libs/utils'\nimport scopedCSS from '../sandbox/scoped_css'\nimport {\n extractLinkFromHtml,\n formatDynamicLink,\n} from './links'\nimport {\n extractScriptElement,\n runDynamicInlineScript,\n runDynamicRemoteScript,\n checkExcludeUrl,\n checkIgnoreUrl,\n} from './scripts'\nimport {\n fixReactHMRConflict,\n} from '../sandbox/adapter'\nimport microApp from '../micro_app'\nimport globalEnv from '../libs/global_env'\n\n// Record element and map element\nconst dynamicElementInMicroAppMap = new WeakMap<Node, Element | Comment>()\n\n// Get the map element\nfunction getMappingNode (node: Node): Node {\n return dynamicElementInMicroAppMap.get(node) ?? node\n}\n\n/**\n * Process the new node and format the style, link and script element\n * @param child new node\n * @param app app\n */\nfunction handleNewNode (child: Node, app: AppInterface): Node {\n if (dynamicElementInMicroAppMap.has(child)) {\n return dynamicElementInMicroAppMap.get(child)!\n } else if (isStyleElement(child)) {\n if (child.hasAttribute('exclude')) {\n const replaceComment = document.createComment('style element with exclude attribute ignored by micro-app')\n dynamicElementInMicroAppMap.set(child, replaceComment)\n return replaceComment\n } else if (app.scopecss && !child.hasAttribute('ignore')) {\n return scopedCSS(child, app)\n }\n return child\n } else if (isLinkElement(child)) {\n if (child.hasAttribute('exclude') || checkExcludeUrl(child.getAttribute('href'), app.name)) {\n const linkReplaceComment = document.createComment('link element with exclude attribute ignored by micro-app')\n dynamicElementInMicroAppMap.set(child, linkReplaceComment)\n return linkReplaceComment\n } else if (\n child.hasAttribute('ignore') ||\n checkIgnoreUrl(child.getAttribute('href'), app.name) ||\n (\n child.href &&\n isFunction(microApp.options.excludeAssetFilter) &&\n microApp.options.excludeAssetFilter(child.href)\n )\n ) {\n return child\n }\n\n const { address, linkInfo, replaceComment } = extractLinkFromHtml(\n child,\n null,\n app,\n true,\n )\n\n if (address && linkInfo) {\n const replaceStyle = formatDynamicLink(address, app, linkInfo, child)\n dynamicElementInMicroAppMap.set(child, replaceStyle)\n return replaceStyle\n } else if (replaceComment) {\n dynamicElementInMicroAppMap.set(child, replaceComment)\n return replaceComment\n }\n\n return child\n } else if (isScriptElement(child)) {\n if (\n child.src &&\n isFunction(microApp.options.excludeAssetFilter) &&\n microApp.options.excludeAssetFilter(child.src)\n ) {\n return child\n }\n\n const { replaceComment, address, scriptInfo } = extractScriptElement(\n child,\n null,\n app,\n true,\n ) || {}\n\n if (address && scriptInfo) {\n // remote script or inline script\n const replaceElement: HTMLScriptElement | Comment = scriptInfo.isExternal ? runDynamicRemoteScript(address, app, scriptInfo, child) : runDynamicInlineScript(address, app, scriptInfo)\n dynamicElementInMicroAppMap.set(child, replaceElement)\n return replaceElement\n } else if (replaceComment) {\n dynamicElementInMicroAppMap.set(child, replaceComment)\n return replaceComment\n }\n\n return child\n }\n\n return child\n}\n\n/**\n * Handle the elements inserted into head and body, and execute normally in other cases\n * @param app app\n * @param method raw method\n * @param parent parent node\n * @param targetChild target node\n * @param passiveChild second param of insertBefore and replaceChild\n */\nfunction invokePrototypeMethod (\n app: AppInterface,\n rawMethod: Func,\n parent: Node,\n targetChild: Node,\n passiveChild?: Node | null,\n): any {\n const hijackParent = getHijackParent(parent, targetChild, app)\n if (hijackParent) {\n /**\n * If parentNode is <micro-app-body>, return rawDocument.body\n * Scenes:\n * 1. element-ui@2/lib/utils/vue-popper.js\n * if (this.popperElm.parentNode === document.body) ...\n * WARNING:\n * 1. When operate child from parentNode async, may have been unmount\n * e.g. target.parentNode.remove(target)\n * ISSUE:\n * 1. https://github.com/micro-zoe/micro-app/issues/739\n * Solution: Return the true value when node not in document\n */\n if (\n !isIframeSandbox(app.name) &&\n isMicroAppBody(hijackParent) &&\n rawMethod !== globalEnv.rawRemoveChild\n ) {\n const descriptor = Object.getOwnPropertyDescriptor(targetChild, 'parentNode')\n if ((!descriptor || descriptor.configurable) && !targetChild.__MICRO_APP_HAS_DPN__) {\n rawDefineProperties(targetChild, {\n parentNode: {\n configurable: true,\n get () {\n const result: ParentNode = globalEnv.rawParentNodeDesc.get.call(this)\n if (isMicroAppBody(result) && app.container) {\n // TODO: remove getRootElementParentNode\n return microApp.options.getRootElementParentNode?.(this, app.name) || document.body\n }\n return result\n },\n },\n __MICRO_APP_HAS_DPN__: {\n configurable: true,\n get: () => true,\n }\n })\n }\n }\n\n if (\n __DEV__ &&\n isIFrameElement(targetChild) &&\n rawMethod === globalEnv.rawAppendChild\n ) {\n fixReactHMRConflict(app)\n }\n\n /**\n * 1. If passiveChild exists, it must be insertBefore or replaceChild\n * 2. When removeChild, targetChild may not be in microAppHead or head\n * NOTE:\n * 1. If passiveChild not in hijackParent, insertBefore replaceChild will be degraded to appendChild\n * E.g: document.head.replaceChild(targetChild, document.scripts[0])\n * 2. If passiveChild not in hijackParent but in parent and method is insertBefore, try insert it into the position corresponding to hijackParent\n * E.g: document.head.insertBefore(targetChild, document.head.childNodes[0])\n * ISSUE: https://github.com/micro-zoe/micro-app/issues/1071\n */\n if (passiveChild && !hijackParent.contains(passiveChild)) {\n if (rawMethod === globalEnv.rawInsertBefore && parent.contains(passiveChild)) {\n const indexOfParent = Array.from(parent.childNodes).indexOf(passiveChild as ChildNode)\n if (hijackParent.childNodes[indexOfParent]) {\n return invokeRawMethod(rawMethod, hijackParent, targetChild, hijackParent.childNodes[indexOfParent])\n }\n }\n return globalEnv.rawAppendChild.call(hijackParent, targetChild)\n } else if (rawMethod === globalEnv.rawRemoveChild && !hijackParent.contains(targetChild)) {\n if (parent.contains(targetChild)) {\n return rawMethod.call(parent, targetChild)\n }\n return targetChild\n }\n\n return invokeRawMethod(rawMethod, hijackParent, targetChild, passiveChild)\n }\n\n return invokeRawMethod(rawMethod, parent, targetChild, passiveChild)\n}\n\n// head/body map to micro-app-head/micro-app-body\nfunction getHijackParent (\n parent: Node,\n targetChild: Node,\n app: AppInterface,\n): HTMLElement | null | undefined {\n if (app) {\n if (parent === document.head) {\n if (app.iframe && isScriptElement(targetChild)) {\n return app.sandBox.microHead\n }\n return app.querySelector<HTMLElement>('micro-app-head')\n }\n if (parent === document.body || parent === document.body.parentNode) {\n if (app.iframe && isScriptElement(targetChild)) {\n return app.sandBox.microBody\n }\n return app.querySelector<HTMLElement>('micro-app-body')\n }\n if (app.iframe && isScriptElement(targetChild)) {\n return app.sandBox.microBody\n }\n }\n return null\n}\n\nfunction invokeRawMethod (\n rawMethod: Func,\n parent: Node,\n targetChild: Node,\n passiveChild?: Node | null\n) {\n if (isPendMethod(rawMethod)) {\n return rawMethod.call(parent, targetChild)\n }\n\n return rawMethod.call(parent, targetChild, passiveChild)\n}\n\nfunction isPendMethod (method: CallableFunction) {\n return method === globalEnv.rawAppend || method === globalEnv.rawPrepend\n}\n\n/**\n * Attempt to complete the static resource address again before insert the node\n * @param app app instance\n * @param newChild target node\n */\nfunction completePathDynamic (app: AppInterface, newChild: Node): void {\n if (isElement(newChild)) {\n if (/^(img|script)$/i.test(newChild.tagName)) {\n if (newChild.hasAttribute('src')) {\n globalEnv.rawSetAttribute.call(newChild, 'src', CompletionPath(newChild.getAttribute('src')!, app.url))\n }\n if (newChild.hasAttribute('srcset')) {\n globalEnv.rawSetAttribute.call(newChild, 'srcset', CompletionPath(newChild.getAttribute('srcset')!, app.url))\n }\n } else if (/^link$/i.test(newChild.tagName) && newChild.hasAttribute('href')) {\n globalEnv.rawSetAttribute.call(newChild, 'href', CompletionPath(newChild.getAttribute('href')!, app.url))\n }\n }\n}\n\n/**\n * method of handle new node\n * @param parent parent node\n * @param newChild new node\n * @param passiveChild passive node\n * @param rawMethod method\n */\nfunction commonElementHandler (\n parent: Node,\n newChild: Node,\n passiveChild: Node | null,\n rawMethod: Func,\n) {\n const currentAppName = getCurrentAppName()\n if (\n isNode(newChild) &&\n !newChild.__PURE_ELEMENT__ &&\n (\n newChild.__MICRO_APP_NAME__ ||\n currentAppName\n )\n ) {\n newChild.__MICRO_APP_NAME__ = newChild.__MICRO_APP_NAME__ || currentAppName!\n const app = appInstanceMap.get(newChild.__MICRO_APP_NAME__)\n if (isStyleElement(newChild)) {\n const isShadowNode = parent.getRootNode()\n const isShadowEnvironment = isShadowNode instanceof ShadowRoot\n isShadowEnvironment && newChild.setAttribute('ignore', 'true')\n }\n if (app?.container) {\n completePathDynamic(app, newChild)\n return invokePrototypeMethod(\n app,\n rawMethod,\n parent,\n handleNewNode(newChild, app),\n passiveChild && getMappingNode(passiveChild),\n )\n }\n }\n\n if (rawMethod === globalEnv.rawAppend || rawMethod === globalEnv.rawPrepend) {\n return rawMethod.call(parent, newChild)\n }\n\n return rawMethod.call(parent, newChild, passiveChild)\n}\n\n/**\n * Rewrite element prototype method\n */\nexport function patchElementAndDocument (): void {\n patchDocument()\n\n const rawRootElement = globalEnv.rawRootElement\n const rawRootNode = globalEnv.rawRootNode\n\n // prototype methods of add element👇\n rawRootElement.prototype.appendChild = function appendChild<T extends Node> (newChild: T): T {\n return commonElementHandler(this, newChild, null, globalEnv.rawAppendChild)\n }\n\n rawRootElement.prototype.insertBefore = function insertBefore<T extends Node> (newChild: T, refChild: Node | null): T {\n return commonElementHandler(this, newChild, refChild, globalEnv.rawInsertBefore)\n }\n\n rawRootElement.prototype.replaceChild = function replaceChild<T extends Node> (newChild: Node, oldChild: T): T {\n return commonElementHandler(this, newChild, oldChild, globalEnv.rawReplaceChild)\n }\n\n rawRootElement.prototype.append = function append (...nodes: (Node | string)[]): void {\n let i = 0\n while (i < nodes.length) {\n let node = nodes[i]\n node = isNode(node) ? node : globalEnv.rawCreateTextNode.call(globalEnv.rawDocument, node)\n commonElementHandler(this, markElement(node as Node), null, globalEnv.rawAppend)\n i++\n }\n }\n\n rawRootElement.prototype.prepend = function prepend (...nodes: (Node | string)[]): void {\n let i = nodes.length\n while (i > 0) {\n let node = nodes[i - 1]\n node = isNode(node) ? node : globalEnv.rawCreateTextNode.call(globalEnv.rawDocument, node)\n commonElementHandler(this, markElement(node as Node), null, globalEnv.rawPrepend)\n i--\n }\n }\n\n // prototype methods of delete element👇\n rawRootElement.prototype.removeChild = function removeChild<T extends Node> (oldChild: T): T {\n if (oldChild?.__MICRO_APP_NAME__) {\n const app = appInstanceMap.get(oldChild.__MICRO_APP_NAME__)\n if (app?.container) {\n return invokePrototypeMethod(\n app,\n globalEnv.rawRemoveChild,\n this,\n getMappingNode(oldChild),\n )\n }\n try {\n return globalEnv.rawRemoveChild.call(this, oldChild) as T\n } catch {\n return (oldChild?.parentNode && globalEnv.rawRemoveChild.call(oldChild.parentNode, oldChild)) as T\n }\n }\n\n return globalEnv.rawRemoveChild.call(this, oldChild) as T\n }\n\n /**\n * The insertAdjacentElement method of the Element interface inserts a given element node at a given position relative to the element it is invoked upon.\n * NOTE:\n * 1. parameter 2 of insertAdjacentElement must type 'Element'\n */\n rawRootElement.prototype.insertAdjacentElement = function (where: InsertPosition, element: Element): Element | null {\n if (element?.__MICRO_APP_NAME__ && isElement(element)) {\n const app = appInstanceMap.get(element.__MICRO_APP_NAME__)\n if (app?.container) {\n const processedEle = handleNewNode(element, app) as Element\n if (!isElement(processedEle)) return element\n const realParent = getHijackParent(this, processedEle, app) ?? this\n return globalEnv.rawInsertAdjacentElement.call(realParent, where, processedEle)\n }\n }\n return globalEnv.rawInsertAdjacentElement.call(this, where, element)\n }\n\n // patch cloneNode\n rawRootElement.prototype.cloneNode = function cloneNode (deep?: boolean): Node {\n const clonedNode = globalEnv.rawCloneNode.call(this, deep)\n this.__MICRO_APP_NAME__ && (clonedNode.__MICRO_APP_NAME__ = this.__MICRO_APP_NAME__)\n return clonedNode\n }\n\n /**\n * document.body(head).querySelector(querySelectorAll) hijack to microAppBody(microAppHead).querySelector(querySelectorAll)\n * NOTE:\n * 1. May cause some problems!\n * 2. Add config options?\n */\n function getQueryTarget (target: Node): Node | null {\n const currentAppName = getCurrentAppName()\n if ((target === document.body || target === document.head) && currentAppName) {\n const app = appInstanceMap.get(currentAppName)\n if (app?.container) {\n if (target === document.body) {\n return app.querySelector('micro-app-body')\n } else if (target === document.head) {\n return app.querySelector('micro-app-head')\n }\n }\n }\n return target\n }\n\n rawRootElement.prototype.querySelector = function querySelector (selectors: string): Node | null {\n return globalEnv.rawElementQuerySelector.call(getQueryTarget(this) ?? this, selectors)\n }\n\n rawRootElement.prototype.querySelectorAll = function querySelectorAll (selectors: string): NodeListOf<Node> {\n return globalEnv.rawElementQuerySelectorAll.call(getQueryTarget(this) ?? this, selectors)\n }\n\n // rewrite setAttribute, complete resource address\n rawRootElement.prototype.setAttribute = function setAttribute (key: string, value: any): void {\n const appName = this.__MICRO_APP_NAME__ || getCurrentAppName()\n if (\n appName &&\n appInstanceMap.has(appName) &&\n (\n ((key === 'src' || key === 'srcset') && /^(img|script|video|audio|source|embed)$/i.test(this.tagName)) ||\n (key === 'href' && /^link$/i.test(this.tagName))\n )\n ) {\n const app = appInstanceMap.get(appName)\n value = CompletionPath(value, app!.url)\n }\n\n globalEnv.rawSetAttribute.call(this, key, value)\n }\n\n /**\n * TODO: 兼容直接通过img.src等操作设置的资源\n * NOTE:\n * 1. 卸载时恢复原始值\n * 2. 循环嵌套的情况\n * 3. 放在global_env中统一处理\n * 4. 是否和completePathDynamic的作用重复?\n */\n // const protoAttrList: Array<[HTMLElement, string]> = [\n // [HTMLImageElement.prototype, 'src'],\n // [HTMLScriptElement.prototype, 'src'],\n // [HTMLLinkElement.prototype, 'href'],\n // ]\n\n // protoAttrList.forEach(([target, attr]) => {\n // const { enumerable, configurable, get, set } = Object.getOwnPropertyDescriptor(target, attr) || {\n // enumerable: true,\n // configurable: true,\n // }\n\n // rawDefineProperty(target, attr, {\n // enumerable,\n // configurable,\n // get: function () {\n // return get?.call(this)\n // },\n // set: function (value) {\n // const currentAppName = getCurrentAppName()\n // if (currentAppName && appInstanceMap.has(currentAppName)) {\n // const app = appInstanceMap.get(currentAppName)\n // value = CompletionPath(value, app!.url)\n // }\n // set?.call(this, value)\n // },\n // })\n // })\n\n rawDefineProperty(rawRootElement.prototype, 'innerHTML', {\n configurable: true,\n enumerable: true,\n get () {\n return globalEnv.rawInnerHTMLDesc.get.call(this)\n },\n set (code: string) {\n globalEnv.rawInnerHTMLDesc.set.call(this, code)\n const currentAppName = getCurrentAppName()\n Array.from(this.children).forEach((child) => {\n if (isElement(child) && currentAppName) {\n // TODO: 使用updateElementInfo进行更新\n child.__MICRO_APP_NAME__ = currentAppName\n }\n })\n }\n })\n\n rawDefineProperty(rawRootNode.prototype, 'parentNode', {\n configurable: true,\n enumerable: true,\n get () {\n /**\n * hijack parentNode of html\n * Scenes:\n * 1. element-ui@2/lib/utils/popper.js\n * // root is child app window, so root.document is proxyDocument or microDocument\n * if (element.parentNode === root.document) ...\n */\n const currentAppName = getCurrentAppName()\n if (currentAppName && this === globalEnv.rawDocument.firstElementChild) {\n const microDocument = appInstanceMap.get(currentAppName)?.sandBox?.proxyWindow?.document\n if (microDocument) return microDocument\n }\n const result = globalEnv.rawParentNodeDesc.get.call(this) as Node\n /**\n * If parentNode is <micro-app-body>, return rawDocument.body\n * Scenes:\n * 1. element-ui@2/lib/utils/vue-popper.js\n * if (this.popperElm.parentNode === document.body) ...\n * WARNING:\n * Will it cause other problems ?\n * e.g. target.parentNode.remove(target)\n * BUG:\n * 1. vue2 umdMode, throw error when render again (<div id='app'></div> will be deleted when render again ) -- Abandon this way at 2023.2.28 before v1.0.0-beta.0, it will cause vue2 throw error when render again\n */\n // if (isMicroAppBody(result) && appInstanceMap.get(this.__MICRO_APP_NAME__)?.container) {\n // return document.body\n // }\n return result\n },\n })\n}\n\n/**\n * Mark the newly created element in the micro application\n * @param element new element\n */\nfunction markElement <T extends Node> (element: T): T {\n const currentAppName = getCurrentAppName()\n if (currentAppName) element.__MICRO_APP_NAME__ = currentAppName\n return element\n}\n\n// methods of document\nfunction patchDocument () {\n const rawDocument = globalEnv.rawDocument\n const rawRootDocument = globalEnv.rawRootDocument\n\n function getBindTarget (target: Document): Document {\n return isProxyDocument(target) ? rawDocument : target\n }\n\n // create element 👇\n rawRootDocument.prototype.createElement = function createElement (\n tagName: string,\n options?: ElementCreationOptions,\n ): HTMLElement {\n const element = globalEnv.rawCreateElement.call(getBindTarget(this), tagName, options)\n return markElement(element)\n }\n\n rawRootDocument.prototype.createElementNS = function createElementNS (\n namespaceURI: string,\n name: string,\n options?: string | ElementCreationOptions,\n ): any {\n const element = globalEnv.rawCreateElementNS.call(getBindTarget(this), namespaceURI, name, options)\n return markElement(element)\n }\n\n // TODO: 放开\n // rawRootDocument.prototype.createTextNode = function createTextNode (data: string): Text {\n // const element = globalEnv.rawCreateTextNode.call(getBindTarget(this), data)\n // return markElement(element)\n // }\n\n rawRootDocument.prototype.createDocumentFragment = function createDocumentFragment (): DocumentFragment {\n const element = globalEnv.rawCreateDocumentFragment.call(getBindTarget(this))\n return markElement(element)\n }\n\n rawRootDocument.prototype.createComment = function createComment (data: string): Comment {\n const element = globalEnv.rawCreateComment.call(getBindTarget(this), data)\n return markElement(element)\n }\n\n // query element👇\n function querySelector (this: Document, selectors: string): any {\n const _this = getBindTarget(this)\n const currentAppName = getCurrentAppName()\n if (\n !currentAppName ||\n !selectors ||\n isUniqueElement(selectors) ||\n // ISSUE: https://github.com/micro-zoe/micro-app/issues/56\n rawDocument !== _this\n ) {\n return globalEnv.rawQuerySelector.call(_this, selectors)\n }\n\n return appInstanceMap.get(currentAppName)?.querySelector(selectors) ?? null\n }\n\n function querySelectorAll (this: Document, selectors: string): any {\n const _this = getBindTarget(this)\n const currentAppName = getCurrentAppName()\n if (\n !currentAppName ||\n !selectors ||\n isUniqueElement(selectors) ||\n rawDocument !== _this\n ) {\n return globalEnv.rawQuerySelectorAll.call(_this, selectors)\n }\n\n return appInstanceMap.get(currentAppName)?.querySelectorAll(selectors) ?? []\n }\n\n rawRootDocument.prototype.querySelector = querySelector\n rawRootDocument.prototype.querySelectorAll = querySelectorAll\n\n rawRootDocument.prototype.getElementById = function getElementById (key: string): HTMLElement | null {\n const _this = getBindTarget(this)\n if (!getCurrentAppName() || isInvalidQuerySelectorKey(key)) {\n return globalEnv.rawGetElementById.call(_this, key)\n }\n\n try {\n return querySelector.call(_this, `#${key}`)\n } catch {\n return globalEnv.rawGetElementById.call(_this, key)\n }\n }\n\n rawRootDocument.prototype.getElementsByClassName = function getElementsByClassName (key: string): HTMLCollectionOf<Element> {\n const _this = getBindTarget(this)\n if (!getCurrentAppName() || isInvalidQuerySelectorKey(key)) {\n return globalEnv.rawGetElementsByClassName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(_this, `.${key}`)\n } catch {\n return globalEnv.rawGetElementsByClassName.call(_this, key)\n }\n }\n\n rawRootDocument.prototype.getElementsByTagName = function getElementsByTagName (key: string): HTMLCollectionOf<Element> {\n const _this = getBindTarget(this)\n const currentAppName = getCurrentAppName()\n if (\n !currentAppName ||\n isUniqueElement(key) ||\n isInvalidQuerySelectorKey(key) ||\n (!appInstanceMap.get(currentAppName)?.inline && /^script$/i.test(key))\n ) {\n return globalEnv.rawGetElementsByTagName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(_this, key)\n } catch {\n return globalEnv.rawGetElementsByTagName.call(_this, key)\n }\n }\n\n rawRootDocument.prototype.getElementsByName = function getElementsByName (key: string): NodeListOf<HTMLElement> {\n const _this = getBindTarget(this)\n if (!getCurrentAppName() || isInvalidQuerySelectorKey(key)) {\n return globalEnv.rawGetElementsByName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(_this, `[name=${key}]`)\n } catch {\n return globalEnv.rawGetElementsByName.call(_this, key)\n }\n }\n}\n\nfunction releasePatchDocument (): void {\n const rawRootDocument = globalEnv.rawRootDocument\n rawRootDocument.prototype.createElement = globalEnv.rawCreateElement\n rawRootDocument.prototype.createElementNS = globalEnv.rawCreateElementNS\n rawRootDocument.prototype.createDocumentFragment = globalEnv.rawCreateDocumentFragment\n rawRootDocument.prototype.querySelector = globalEnv.rawQuerySelector\n rawRootDocument.prototype.querySelectorAll = globalEnv.rawQuerySelectorAll\n rawRootDocument.prototype.getElementById = globalEnv.rawGetElementById\n rawRootDocument.prototype.getElementsByClassName = globalEnv.rawGetElementsByClassName\n rawRootDocument.prototype.getElementsByTagName = globalEnv.rawGetElementsByTagName\n rawRootDocument.prototype.getElementsByName = globalEnv.rawGetElementsByName\n}\n\n// release patch\nexport function releasePatchElementAndDocument (): void {\n removeDomScope()\n releasePatchDocument()\n\n const rawRootElement = globalEnv.rawRootElement\n const rawRootNode = globalEnv.rawRootNode\n rawRootElement.prototype.appendChild = globalEnv.rawAppendChild\n rawRootElement.prototype.insertBefore = globalEnv.rawInsertBefore\n rawRootElement.prototype.replaceChild = globalEnv.rawReplaceChild\n rawRootElement.prototype.removeChild = globalEnv.rawRemoveChild\n rawRootElement.prototype.append = globalEnv.rawAppend\n rawRootElement.prototype.prepend = globalEnv.rawPrepend\n rawRootElement.prototype.cloneNode = globalEnv.rawCloneNode\n rawRootElement.prototype.querySelector = globalEnv.rawElementQuerySelector\n rawRootElement.prototype.querySelectorAll = globalEnv.rawElementQuerySelectorAll\n rawRootElement.prototype.setAttribute = globalEnv.rawSetAttribute\n rawDefineProperty(rawRootElement.prototype, 'innerHTML', globalEnv.rawInnerHTMLDesc)\n rawDefineProperty(rawRootNode.prototype, 'parentNode', globalEnv.rawParentNodeDesc)\n}\n\n// Set the style of micro-app-head and micro-app-body\nlet hasRejectMicroAppStyle = false\nexport function rejectMicroAppStyle (): void {\n if (!hasRejectMicroAppStyle) {\n hasRejectMicroAppStyle = true\n const style = pureCreateElement('style')\n globalEnv.rawSetAttribute.call(style, 'type', 'text/css')\n style.textContent = `\\n${microApp.tagName}, micro-app-body { display: block; } \\nmicro-app-head { display: none; }`\n globalEnv.rawDocument.head.appendChild(style)\n }\n}\n","import type {\n AppInterface,\n RequestIdleCallbackInfo,\n RequestIdleCallbackOptions,\n} from '@micro-app/types'\nimport {\n isSupportModuleScript,\n isBrowser,\n getCurrentAppName,\n assign,\n} from './utils'\nimport {\n rejectMicroAppStyle,\n} from '../source/patch'\n\ndeclare global {\n interface Node {\n __MICRO_APP_NAME__?: string | null\n __PURE_ELEMENT__?: boolean\n __MICRO_APP_HAS_DPN__?: boolean\n data?: unknown\n rawParentNode?: ParentNode | null\n }\n\n interface HTMLStyleElement {\n __MICRO_APP_HAS_SCOPED__?: boolean\n }\n\n interface HTMLElement {\n reload(destroy?: boolean): Promise<boolean>\n mount(app: AppInterface): void\n unmount (destroy?: boolean, unmountcb?: CallableFunction): void\n }\n\n interface Window {\n requestIdleCallback (\n callback: (info: RequestIdleCallbackInfo) => void,\n opts?: RequestIdleCallbackOptions,\n ): number\n _babelPolyfill: boolean\n __MICRO_APP_ENVIRONMENT__?: boolean\n __MICRO_APP_UMD_MODE__?: boolean\n __MICRO_APP_BASE_APPLICATION__?: boolean\n __REACT_ERROR_OVERLAY_GLOBAL_HOOK__: boolean\n rawLocation: Location\n rawWindow: Window\n rawDocument: Document\n Document: any\n Element: any,\n Node: any,\n EventTarget: any,\n HTMLElement: HTMLElement,\n }\n}\n\nconst globalEnv: Record<string, any> = {\n // active sandbox count\n activeSandbox: 0,\n}\n\n/**\n * Note loop nesting\n * Only prototype or unique values can be put here\n */\nexport function initGlobalEnv (): void {\n if (isBrowser) {\n const rawWindow = window.rawWindow || Function('return window')()\n const rawDocument = window.rawDocument || Function('return document')()\n const rawRootDocument = rawWindow.Document || Function('return Document')()\n const rawRootElement = rawWindow.Element\n const rawRootNode = rawWindow.Node\n const rawRootEventTarget = rawWindow.EventTarget\n\n // save patch raw methods, pay attention to this binding\n const rawSetAttribute = rawRootElement.prototype.setAttribute\n const rawAppendChild = rawRootElement.prototype.appendChild\n const rawInsertBefore = rawRootElement.prototype.insertBefore\n const rawReplaceChild = rawRootElement.prototype.replaceChild\n const rawRemoveChild = rawRootElement.prototype.removeChild\n const rawAppend = rawRootElement.prototype.append\n const rawPrepend = rawRootElement.prototype.prepend\n const rawCloneNode = rawRootElement.prototype.cloneNode\n const rawElementQuerySelector = rawRootElement.prototype.querySelector\n const rawElementQuerySelectorAll = rawRootElement.prototype.querySelectorAll\n const rawInsertAdjacentElement = rawRootElement.prototype.insertAdjacentElement\n const rawInnerHTMLDesc = Object.getOwnPropertyDescriptor(rawRootElement.prototype, 'innerHTML')\n const rawParentNodeDesc = Object.getOwnPropertyDescriptor(rawRootNode.prototype, 'parentNode')\n\n // Document proto methods\n const rawCreateElement = rawRootDocument.prototype.createElement\n const rawCreateElementNS = rawRootDocument.prototype.createElementNS\n const rawCreateTextNode = rawRootDocument.prototype.createTextNode\n const rawCreateDocumentFragment = rawRootDocument.prototype.createDocumentFragment\n const rawCreateComment = rawRootDocument.prototype.createComment\n const rawQuerySelector = rawRootDocument.prototype.querySelector\n const rawQuerySelectorAll = rawRootDocument.prototype.querySelectorAll\n const rawGetElementById = rawRootDocument.prototype.getElementById\n const rawGetElementsByClassName = rawRootDocument.prototype.getElementsByClassName\n const rawGetElementsByTagName = rawRootDocument.prototype.getElementsByTagName\n const rawGetElementsByName = rawRootDocument.prototype.getElementsByName\n\n const ImageProxy = new Proxy(Image, {\n construct (Target, args): HTMLImageElement {\n const elementImage = new Target(...args)\n const currentAppName = getCurrentAppName()\n if (currentAppName) elementImage.__MICRO_APP_NAME__ = currentAppName\n return elementImage\n },\n })\n\n /**\n * save effect raw methods\n * pay attention to this binding, especially setInterval, setTimeout, clearInterval, clearTimeout\n */\n const rawSetInterval = rawWindow.setInterval\n const rawSetTimeout = rawWindow.setTimeout\n const rawClearInterval = rawWindow.clearInterval\n const rawClearTimeout = rawWindow.clearTimeout\n const rawPushState = rawWindow.history.pushState\n const rawReplaceState = rawWindow.history.replaceState\n const rawAddEventListener = rawRootEventTarget.prototype.addEventListener\n const rawRemoveEventListener = rawRootEventTarget.prototype.removeEventListener\n const rawDispatchEvent = rawRootEventTarget.prototype.dispatchEvent\n\n // mark current application as base application\n window.__MICRO_APP_BASE_APPLICATION__ = true\n\n assign(globalEnv, {\n supportModuleScript: isSupportModuleScript(),\n\n // common global vars\n rawWindow,\n rawDocument,\n rawRootDocument,\n rawRootElement,\n rawRootNode,\n\n // source/patch\n rawSetAttribute,\n rawAppendChild,\n rawInsertBefore,\n rawReplaceChild,\n rawRemoveChild,\n rawAppend,\n rawPrepend,\n rawCloneNode,\n rawElementQuerySelector,\n rawElementQuerySelectorAll,\n rawInsertAdjacentElement,\n rawInnerHTMLDesc,\n rawParentNodeDesc,\n\n rawCreateElement,\n rawCreateElementNS,\n rawCreateDocumentFragment,\n rawCreateTextNode,\n rawCreateComment,\n rawQuerySelector,\n rawQuerySelectorAll,\n rawGetElementById,\n rawGetElementsByClassName,\n rawGetElementsByTagName,\n rawGetElementsByName,\n ImageProxy,\n\n // sandbox/effect\n rawSetInterval,\n rawSetTimeout,\n rawClearInterval,\n rawClearTimeout,\n rawPushState,\n rawReplaceState,\n rawAddEventListener,\n rawRemoveEventListener,\n rawDispatchEvent,\n\n // iframe\n })\n\n // global effect\n rejectMicroAppStyle()\n }\n}\n\nexport default globalEnv\n","/* eslint-disable no-new */\nimport type {\n AttrType,\n MicroAppElementType,\n AppInterface,\n OptionsType,\n NormalKey,\n} from '@micro-app/types'\nimport microApp from './micro_app'\nimport dispatchLifecyclesEvent from './interact/lifecycles_event'\nimport globalEnv from './libs/global_env'\nimport {\n defer,\n formatAppName,\n formatAppURL,\n version,\n logError,\n logWarn,\n isString,\n isFunction,\n CompletionPath,\n createURL,\n isPlainObject,\n getEffectivePath,\n getBaseHTMLElement,\n} from './libs/utils'\nimport {\n ObservedAttrName,\n lifeCycles,\n appStates,\n} from './constants'\nimport CreateApp, {\n appInstanceMap,\n} from './create_app'\nimport {\n router,\n getNoHashMicroPathFromURL,\n getRouterMode,\n} from './sandbox/router'\n\n/**\n * define element\n * @param tagName element name\n*/\nexport function defineElement (tagName: string): void {\n class MicroAppElement extends getBaseHTMLElement() implements MicroAppElementType {\n static get observedAttributes (): string[] {\n return ['name', 'url']\n }\n\n private isWaiting = false\n private cacheData: Record<PropertyKey, unknown> | null = null\n private connectedCount = 0\n private connectStateMap: Map<number, boolean> = new Map()\n public appName = '' // app name\n public appUrl = '' // app url\n public ssrUrl = '' // html path in ssr mode\n public version = version\n\n // 👇 Configuration\n // name: app name\n // url: html address\n // shadowDom: use shadowDOM, default is false\n // destroy: whether delete cache resources when unmount, default is false\n // inline: whether js runs in inline script mode, default is false\n // disableScopecss: whether disable css scoped, default is false\n // disableSandbox: whether disable sandbox, default is false\n // baseRoute: route prefix, default is ''\n // keep-alive: open keep-alive mode\n\n public connectedCallback (): void {\n const cacheCount = ++this.connectedCount\n this.connectStateMap.set(cacheCount, true)\n /**\n * In some special scenes, such as vue's keep-alive, the micro-app will be inserted and deleted twice in an instant\n * So we execute the mount method async and record connectState to prevent repeated rendering\n */\n const effectiveApp = this.appName && this.appUrl\n defer(() => {\n if (this.connectStateMap.get(cacheCount)) {\n dispatchLifecyclesEvent(\n this,\n this.appName,\n lifeCycles.CREATED,\n )\n /**\n * If insert micro-app element without name or url, and set them in next action like angular,\n * handleConnected will be executed twice, causing the app render repeatedly,\n * so we only execute handleConnected() if url and name exist when connectedCallback\n */\n effectiveApp && this.handleConnected()\n }\n })\n }\n\n public disconnectedCallback (): void {\n this.connectStateMap.set(this.connectedCount, false)\n this.handleDisconnected()\n }\n\n /**\n * Re render app from the command line\n * MicroAppElement.reload(destroy)\n */\n public reload (destroy?: boolean): Promise<boolean> {\n return new Promise((resolve) => {\n const handleAfterReload = () => {\n this.removeEventListener(lifeCycles.MOUNTED, handleAfterReload)\n this.removeEventListener(lifeCycles.AFTERSHOW, handleAfterReload)\n resolve(true)\n }\n this.addEventListener(lifeCycles.MOUNTED, handleAfterReload)\n this.addEventListener(lifeCycles.AFTERSHOW, handleAfterReload)\n this.handleDisconnected(destroy, () => {\n this.handleConnected()\n })\n })\n }\n\n /**\n * common action for unmount\n * @param destroy reload param\n */\n private handleDisconnected (destroy = false, callback?: CallableFunction): void {\n const app = appInstanceMap.get(this.appName)\n if (app && !app.isUnmounted() && !app.isHidden()) {\n // keep-alive\n if (this.getKeepAliveModeResult() && !destroy) {\n this.handleHiddenKeepAliveApp(callback)\n } else {\n this.unmount(destroy, callback)\n }\n }\n }\n\n public attributeChangedCallback (attr: ObservedAttrName, _oldVal: string, newVal: string): void {\n if (\n this.legalAttribute(attr, newVal) &&\n this[attr === ObservedAttrName.NAME ? 'appName' : 'appUrl'] !== newVal\n ) {\n if (\n attr === ObservedAttrName.URL && (\n !this.appUrl ||\n !this.connectStateMap.get(this.connectedCount) // TODO: 这里的逻辑可否再优化一下\n )\n ) {\n newVal = formatAppURL(newVal, this.appName)\n if (!newVal) {\n return logError(`Invalid attribute url ${newVal}`, this.appName)\n }\n this.appUrl = newVal\n this.handleInitialNameAndUrl()\n } else if (\n attr === ObservedAttrName.NAME && (\n !this.appName ||\n !this.connectStateMap.get(this.connectedCount) // TODO: 这里的逻辑可否再优化一下\n )\n ) {\n const formatNewName = formatAppName(newVal)\n\n if (!formatNewName) {\n return logError(`Invalid attribute name ${newVal}`, this.appName)\n }\n\n // TODO: 当micro-app还未插入文档中就修改name,逻辑可否再优化一下\n if (this.cacheData) {\n microApp.setData(formatNewName, this.cacheData)\n this.cacheData = null\n }\n\n this.appName = formatNewName\n if (formatNewName !== newVal) {\n this.setAttribute('name', this.appName)\n }\n this.handleInitialNameAndUrl()\n } else if (!this.isWaiting) {\n this.isWaiting = true\n defer(this.handleAttributeUpdate)\n }\n }\n }\n\n // handle for connectedCallback run before attributeChangedCallback\n private handleInitialNameAndUrl (): void {\n this.connectStateMap.get(this.connectedCount) && this.handleConnected()\n }\n\n /**\n * first mount of this app\n */\n private handleConnected (): void {\n if (!this.appName || !this.appUrl) return\n\n if (this.getDisposeResult('shadowDOM') && !this.shadowRoot && isFunction(this.attachShadow)) {\n this.attachShadow({ mode: 'open' })\n }\n\n this.updateSsrUrl(this.appUrl)\n if (appInstanceMap.has(this.appName)) {\n const oldApp = appInstanceMap.get(this.appName)!\n const oldAppUrl = oldApp.ssrUrl || oldApp.url\n const targetUrl = this.ssrUrl || this.appUrl\n /**\n * NOTE:\n * 1. keep-alive don't care about ssrUrl\n * 2. Even if the keep-alive app is pushed into the background, it is still active and cannot be replaced. Otherwise, it is difficult for developers to troubleshoot in case of conflict and will leave developers at a loss\n * 3. When scopecss, useSandbox of prefetch app different from target app, delete prefetch app and create new one\n */\n if (\n oldApp.isHidden() &&\n oldApp.url === this.appUrl\n ) {\n this.handleShowKeepAliveApp(oldApp)\n } else if (\n oldAppUrl === targetUrl && (\n oldApp.isUnmounted() ||\n (\n oldApp.isPrefetch &&\n this.sameCoreOptions(oldApp)\n )\n )\n ) {\n this.handleMount(oldApp)\n } else if (oldApp.isPrefetch || oldApp.isUnmounted()) {\n if (__DEV__ && this.sameCoreOptions(oldApp)) {\n /**\n * url is different & old app is unmounted or prefetch, create new app to replace old one\n */\n logWarn(`the ${oldApp.isPrefetch ? 'prefetch' : 'unmounted'} app with url: ${oldAppUrl} replaced by a new app with url: ${targetUrl}`, this.appName)\n }\n this.handleCreateApp()\n } else {\n logError(`app name conflict, an app named: ${this.appName} with url: ${oldAppUrl} is running`)\n }\n } else {\n this.handleCreateApp()\n }\n }\n\n /**\n * handle for change of name an url after element init\n */\n private handleAttributeUpdate = (): void => {\n this.isWaiting = false\n const formatAttrName = formatAppName(this.getAttribute('name'))\n const formatAttrUrl = formatAppURL(this.getAttribute('url'), this.appName)\n if (this.legalAttribute('name', formatAttrName) && this.legalAttribute('url', formatAttrUrl)) {\n const oldApp = appInstanceMap.get(formatAttrName)\n /**\n * If oldApp exist & appName is different, determine whether oldApp is running\n */\n if (formatAttrName !== this.appName && oldApp) {\n if (!oldApp.isUnmounted() && !oldApp.isHidden() && !oldApp.isPrefetch) {\n this.setAttribute('name', this.appName)\n return logError(`app name conflict, an app named ${formatAttrName} is running`)\n }\n }\n\n if (formatAttrName !== this.appName || formatAttrUrl !== this.appUrl) {\n if (formatAttrName === this.appName) {\n this.unmount(true, () => {\n this.actionsForAttributeChange(formatAttrName, formatAttrUrl, oldApp)\n })\n } else if (this.getKeepAliveModeResult()) {\n this.handleHiddenKeepAliveApp()\n this.actionsForAttributeChange(formatAttrName, formatAttrUrl, oldApp)\n } else {\n this.unmount(false, () => {\n this.actionsForAttributeChange(formatAttrName, formatAttrUrl, oldApp)\n })\n }\n }\n } else if (formatAttrName !== this.appName) {\n this.setAttribute('name', this.appName)\n }\n }\n\n // remount app or create app if attribute url or name change\n private actionsForAttributeChange (\n formatAttrName: string,\n formatAttrUrl: string,\n oldApp: AppInterface | void,\n ): void {\n /**\n * do not add judgment of formatAttrUrl === this.appUrl\n */\n this.updateSsrUrl(formatAttrUrl)\n\n this.appName = formatAttrName\n this.appUrl = formatAttrUrl\n ;(this.shadowRoot ?? this).innerHTML = ''\n if (formatAttrName !== this.getAttribute('name')) {\n this.setAttribute('name', this.appName)\n }\n\n /**\n * when oldApp not null: this.appName === oldApp.name\n * scene1: if formatAttrName and this.appName are equal: exitApp is the current app, the url must be different, oldApp has been unmounted\n * scene2: if formatAttrName and this.appName are different: oldApp must be prefetch or unmounted, if url is equal, then just mount, if url is different, then create new app to replace oldApp\n * scene3: url is different but ssrUrl is equal\n * scene4: url is equal but ssrUrl is different, if url is equal, name must different\n * scene5: if oldApp is KEEP_ALIVE_HIDDEN, name must different\n */\n if (oldApp) {\n if (oldApp.isHidden()) {\n if (oldApp.url === this.appUrl) {\n this.handleShowKeepAliveApp(oldApp)\n } else {\n // the hidden keep-alive app is still active\n logError(`app name conflict, an app named ${this.appName} is running`)\n }\n /**\n * TODO:\n * 1. oldApp必是unmountApp或preFetchApp,这里还应该考虑沙箱、iframe、样式隔离不一致的情况\n * 2. unmountApp要不要判断样式隔离、沙箱、iframe,然后彻底删除并再次渲染?(包括handleConnected里的处理,先不改?)\n * 推荐:if (\n * oldApp.url === this.appUrl &&\n * oldApp.ssrUrl === this.ssrUrl && (\n * oldApp.isUnmounted() ||\n * (oldApp.isPrefetch && this.sameCoreOptions(oldApp))\n * )\n * )\n */\n } else if (oldApp.url === this.appUrl && oldApp.ssrUrl === this.ssrUrl) {\n // mount app\n this.handleMount(oldApp)\n } else {\n this.handleCreateApp()\n }\n } else {\n this.handleCreateApp()\n }\n }\n\n /**\n * judge the attribute is legal\n * @param name attribute name\n * @param val attribute value\n */\n private legalAttribute (name: string, val: AttrType): boolean {\n if (!isString(val) || !val) {\n logError(`unexpected attribute ${name}, please check again`, this.appName)\n return false\n }\n\n return true\n }\n\n // create app instance\n private handleCreateApp (): void {\n const createAppInstance = () => new CreateApp({\n name: this.appName,\n url: this.appUrl,\n container: this.shadowRoot ?? this,\n scopecss: this.useScopecss(),\n useSandbox: this.useSandbox(),\n inline: this.getDisposeResult('inline'),\n iframe: this.getDisposeResult('iframe'),\n ssrUrl: this.ssrUrl,\n routerMode: this.getMemoryRouterMode(),\n })\n\n /**\n * Actions for destroy old app\n * If oldApp exist, it must be 3 scenes:\n * 1. oldApp is unmounted app (url is is different)\n * 2. oldApp is prefetch, not prerender (url, scopecss, useSandbox, iframe is different)\n * 3. oldApp is prerender (url, scopecss, useSandbox, iframe is different)\n */\n const oldApp = appInstanceMap.get(this.appName)\n if (oldApp) {\n if (oldApp.isPrerender) {\n this.unmount(true, createAppInstance)\n } else {\n oldApp.actionsForCompletelyDestroy()\n createAppInstance()\n }\n } else {\n createAppInstance()\n }\n }\n\n /**\n * mount app\n * some serious note before mount:\n * 1. is prefetch ?\n * 2. is remount in another container ?\n * 3. is remount with change properties of the container ?\n */\n private handleMount (app: AppInterface): void {\n app.isPrefetch = false\n /**\n * Fix error when navigate before app.mount by microApp.router.push(...)\n * Issue: https://github.com/micro-zoe/micro-app/issues/908\n */\n app.setAppState(appStates.BEFORE_MOUNT)\n // exec mount async, simulate the first render scene\n defer(() => this.mount(app))\n }\n\n /**\n * public mount action for micro_app_element & create_app\n */\n public mount (app: AppInterface): void {\n app.mount({\n container: this.shadowRoot ?? this,\n inline: this.getDisposeResult('inline'),\n routerMode: this.getMemoryRouterMode(),\n baseroute: this.getBaseRouteCompatible(),\n defaultPage: this.getDefaultPage(),\n disablePatchRequest: this.getDisposeResult('disable-patch-request'),\n fiber: this.getDisposeResult('fiber'),\n })\n }\n\n /**\n * unmount app\n * @param destroy delete cache resources when unmount\n * @param unmountcb callback\n */\n public unmount (destroy?: boolean, unmountcb?: CallableFunction): void {\n const app = appInstanceMap.get(this.appName)\n if (app && !app.isUnmounted()) {\n app.unmount({\n destroy: destroy || this.getDestroyCompatibleResult(),\n clearData: this.getDisposeResult('clear-data'),\n keepRouteState: this.getDisposeResult('keep-router-state'),\n unmountcb,\n })\n }\n }\n\n // hidden app when disconnectedCallback called with keep-alive\n private handleHiddenKeepAliveApp (callback?: CallableFunction): void {\n const app = appInstanceMap.get(this.appName)\n if (app && !app.isUnmounted() && !app.isHidden()) {\n app.hiddenKeepAliveApp(callback)\n }\n }\n\n // show app when connectedCallback called with keep-alive\n private handleShowKeepAliveApp (app: AppInterface): void {\n // must be async\n defer(() => app.showKeepAliveApp(this.shadowRoot ?? this))\n }\n\n /**\n * Get configuration\n * Global setting is lowest priority\n * @param name Configuration item name\n */\n private getDisposeResult <T extends keyof OptionsType> (name: T): boolean {\n return (this.compatibleProperties(name) || !!microApp.options[name]) && this.compatibleDisableProperties(name)\n }\n\n // compatible of disableScopecss & disableSandbox\n private compatibleProperties (name: string): boolean {\n if (name === 'disable-scopecss') {\n return this.hasAttribute('disable-scopecss') || this.hasAttribute('disableScopecss')\n } else if (name === 'disable-sandbox') {\n return this.hasAttribute('disable-sandbox') || this.hasAttribute('disableSandbox')\n }\n return this.hasAttribute(name)\n }\n\n // compatible of disableScopecss & disableSandbox\n private compatibleDisableProperties (name: string): boolean {\n if (name === 'disable-scopecss') {\n return this.getAttribute('disable-scopecss') !== 'false' && this.getAttribute('disableScopecss') !== 'false'\n } else if (name === 'disable-sandbox') {\n return this.getAttribute('disable-sandbox') !== 'false' && this.getAttribute('disableSandbox') !== 'false'\n }\n return this.getAttribute(name) !== 'false'\n }\n\n private useScopecss (): boolean {\n return !(this.getDisposeResult('disable-scopecss') || this.getDisposeResult('shadowDOM'))\n }\n\n private useSandbox (): boolean {\n return !this.getDisposeResult('disable-sandbox')\n }\n\n /**\n * Determine whether the core options of the existApp is consistent with the new one\n */\n private sameCoreOptions (app: AppInterface): boolean {\n return (\n app.scopecss === this.useScopecss() &&\n app.useSandbox === this.useSandbox() &&\n app.iframe === this.getDisposeResult('iframe')\n )\n }\n\n /**\n * 2021-09-08\n * get baseRoute\n * getAttribute('baseurl') is compatible writing of versions below 0.3.1\n */\n private getBaseRouteCompatible (): string {\n return this.getAttribute('baseroute') ?? this.getAttribute('baseurl') ?? ''\n }\n\n // compatible of destroy\n private getDestroyCompatibleResult (): boolean {\n return this.getDisposeResult('destroy') || this.getDisposeResult('destory')\n }\n\n /**\n * destroy has priority over destroy keep-alive\n */\n private getKeepAliveModeResult (): boolean {\n return this.getDisposeResult('keep-alive') && !this.getDestroyCompatibleResult()\n }\n\n /**\n * change ssrUrl in ssr mode\n */\n private updateSsrUrl (baseUrl: string): void {\n if (this.getDisposeResult('ssr')) {\n // TODO: disable-memory-router不存在了,这里需要更新一下\n if (this.getDisposeResult('disable-memory-router') || this.getDisposeResult('disableSandbox')) {\n const rawLocation = globalEnv.rawWindow.location\n this.ssrUrl = CompletionPath(rawLocation.pathname + rawLocation.search, baseUrl)\n } else {\n // get path from browser URL\n let targetPath = getNoHashMicroPathFromURL(this.appName, baseUrl)\n const defaultPagePath = this.getDefaultPage()\n if (!targetPath && defaultPagePath) {\n const targetLocation = createURL(defaultPagePath, baseUrl)\n targetPath = targetLocation.origin + targetLocation.pathname + targetLocation.search\n }\n this.ssrUrl = targetPath\n }\n } else if (this.ssrUrl) {\n this.ssrUrl = ''\n }\n }\n\n /**\n * get config of default page\n */\n private getDefaultPage (): string {\n return (\n router.getDefaultPage(this.appName) ||\n this.getAttribute('default-page') ||\n this.getAttribute('defaultPage') ||\n ''\n )\n }\n\n /**\n * get config of router-mode\n * @returns router-mode\n */\n private getMemoryRouterMode () : string {\n return getRouterMode(\n this.getAttribute('router-mode'),\n // is micro-app element set disable-memory-router, like <micro-app disable-memory-router></micro-app>\n this.compatibleProperties('disable-memory-router') && this.compatibleDisableProperties('disable-memory-router'),\n )\n }\n\n /**\n * rewrite micro-app.setAttribute, process attr data\n * @param key attr name\n * @param value attr value\n */\n public setAttribute (key: string, value: any): void {\n if (key === 'data') {\n if (isPlainObject(value)) {\n const cloneValue: Record<NormalKey, unknown> = {}\n Object.getOwnPropertyNames(value).forEach((ownKey: NormalKey) => {\n if (!(isString(ownKey) && ownKey.indexOf('__') === 0)) {\n cloneValue[ownKey] = value[ownKey]\n }\n })\n this.data = cloneValue\n } else if (value !== '[object Object]') {\n logWarn('property data must be an object', this.appName)\n }\n } else {\n globalEnv.rawSetAttribute.call(this, key, value)\n }\n }\n\n /**\n * Data from the base application\n */\n set data (value: Record<PropertyKey, unknown> | null) {\n if (this.appName) {\n microApp.setData(this.appName, value as Record<PropertyKey, unknown>)\n } else {\n this.cacheData = value\n }\n }\n\n /**\n * get data only used in jsx-custom-event once\n */\n get data (): Record<PropertyKey, unknown> | null {\n if (this.appName) {\n return microApp.getData(this.appName, true)\n } else if (this.cacheData) {\n return this.cacheData\n }\n return null\n }\n\n /**\n * get publicPath from a valid address,it can used in micro-app-devtools\n */\n get publicPath (): string {\n return getEffectivePath(this.appUrl)\n }\n\n /**\n * get baseRoute from attribute,it can used in micro-app-devtools\n */\n get baseRoute (): string {\n return this.getBaseRouteCompatible()\n }\n }\n\n globalEnv.rawWindow.customElements.define(tagName, MicroAppElement)\n}\n","import type {\n prefetchParamList,\n prefetchParam,\n globalAssetsType,\n OnLoadParam,\n} from '@micro-app/types'\nimport type {\n SourceCenter as SourceCenterType,\n} from './source/source_center'\nimport microApp from './micro_app'\nimport sourceCenter from './source/source_center'\nimport {\n PREFETCH_LEVEL,\n} from './constants'\nimport CreateApp, {\n appInstanceMap,\n} from './create_app'\nimport {\n requestIdleCallback,\n formatAppURL,\n formatAppName,\n promiseStream,\n logError,\n isBrowser,\n isArray,\n isPlainObject,\n isString,\n isFunction,\n promiseRequestIdle,\n isNumber,\n assign,\n} from './libs/utils'\nimport {\n fetchSource,\n} from './source/fetch'\nimport {\n getRouterMode,\n} from './sandbox/router'\n\n/**\n * preFetch([\n * {\n * name: string,\n * url: string,\n * iframe: boolean,\n * inline: boolean,\n * 'disable-scopecss': boolean,\n * 'disable-sandbox': boolean,\n * level: number,\n * 'default-page': string,\n * 'disable-patch-request': boolean,\n * },\n * ...\n * ])\n * Note:\n * 1: preFetch is async and is performed only when the browser is idle\n * 2: options of prefetch preferably match the config of the micro-app element, although this is not required\n * @param apps micro app options\n * @param delay delay time\n */\nexport default function preFetch (apps: prefetchParamList, delay?: number): void {\n if (!isBrowser) {\n return logError('preFetch is only supported in browser environment')\n }\n\n requestIdleCallback(() => {\n const delayTime = isNumber(delay) ? delay : microApp.options.prefetchDelay\n\n /**\n * TODO: remove setTimeout\n * Is there a better way?\n */\n setTimeout(() => {\n // releasePrefetchEffect()\n preFetchInSerial(apps)\n }, isNumber(delayTime) ? delayTime : 3000)\n })\n\n // const handleOnLoad = (): void => {\n // releasePrefetchEffect()\n // requestIdleCallback(() => {\n // preFetchInSerial(apps)\n // })\n // }\n\n // const releasePrefetchEffect = (): void => {\n // window.removeEventListener('load', handleOnLoad)\n // clearTimeout(preFetchTime)\n // }\n\n // window.addEventListener('load', handleOnLoad)\n}\n\nfunction preFetchInSerial (apps: prefetchParamList): void {\n isFunction(apps) && (apps = apps())\n\n if (isArray(apps)) {\n apps.reduce((pre, next) => pre.then(() => preFetchAction(next)), Promise.resolve())\n }\n}\n\n// sequential preload app\nfunction preFetchAction (options: prefetchParam): Promise<void> {\n return promiseRequestIdle((resolve: PromiseConstructor['resolve']) => {\n if (isPlainObject(options) && navigator.onLine) {\n options.name = formatAppName(options.name)\n options.url = formatAppURL(options.url, options.name)\n if (options.name && options.url && !appInstanceMap.has(options.name)) {\n const app = new CreateApp({\n name: options.name,\n url: options.url,\n isPrefetch: true,\n scopecss: !(options['disable-scopecss'] ?? options.disableScopecss ?? microApp.options['disable-scopecss']),\n useSandbox: !(options['disable-sandbox'] ?? options.disableSandbox ?? microApp.options['disable-sandbox']),\n inline: options.inline ?? microApp.options.inline,\n iframe: options.iframe ?? microApp.options.iframe,\n prefetchLevel: options.level && PREFETCH_LEVEL.includes(options.level) ? options.level : microApp.options.prefetchLevel && PREFETCH_LEVEL.includes(microApp.options.prefetchLevel) ? microApp.options.prefetchLevel : 2,\n })\n\n const oldOnload = app.onLoad\n const oldOnLoadError = app.onLoadError\n app.onLoad = (onLoadParam: OnLoadParam): void => {\n if (app.isPrerender) {\n assign(onLoadParam, {\n defaultPage: options['default-page'],\n /**\n * TODO: 预渲染支持disable-memory-router,默认渲染首页即可,文档中也要保留\n * 问题:\n * 1、如何确保子应用进行跳转时不影响到浏览器地址??pure??\n */\n routerMode: getRouterMode(options['router-mode']),\n baseroute: options.baseroute,\n disablePatchRequest: options['disable-patch-request'],\n })\n }\n resolve()\n oldOnload.call(app, onLoadParam)\n }\n\n app.onLoadError = (...rests): void => {\n resolve()\n oldOnLoadError.call(app, ...rests)\n }\n } else {\n resolve()\n }\n } else {\n resolve()\n }\n })\n}\n\n/**\n * load global assets into cache\n * @param assets global assets of js, css\n */\nexport function getGlobalAssets (assets: globalAssetsType): void {\n if (isPlainObject(assets)) {\n requestIdleCallback(() => {\n fetchGlobalResources(assets.js, 'js', sourceCenter.script)\n fetchGlobalResources(assets.css, 'css', sourceCenter.link)\n })\n }\n}\n\n// TODO: requestIdleCallback for every file\nfunction fetchGlobalResources (resources: string[] | void, suffix: string, sourceHandler: SourceCenterType['link'] | SourceCenterType['script']) {\n if (isArray(resources)) {\n const effectiveResource = resources!.filter((path) => isString(path) && path.includes(`.${suffix}`) && !sourceHandler.hasInfo(path))\n\n const fetchResourcePromise = effectiveResource.map((path) => fetchSource(path))\n\n // fetch resource with stream\n promiseStream<string>(fetchResourcePromise, (res: {data: string, index: number}) => {\n const path = effectiveResource[res.index]\n if (suffix === 'js') {\n if (!sourceHandler.hasInfo(path)) {\n sourceHandler.setInfo(path, {\n code: res.data,\n isExternal: false,\n appSpace: {},\n })\n }\n } else {\n if (!sourceHandler.hasInfo(path)) {\n (sourceHandler as SourceCenterType['link']).setInfo(path, {\n code: res.data,\n appSpace: {}\n })\n }\n }\n }, (err: {error: Error, index: number}) => {\n logError(err)\n })\n }\n}\n","import type {\n OptionsType,\n MicroAppBaseType,\n AppInterface,\n Router,\n AppName,\n Func,\n lifeCyclesType,\n MicroAppConfig,\n GetActiveAppsParam,\n} from '@micro-app/types'\nimport { defineElement } from './micro_app_element'\nimport preFetch, { getGlobalAssets } from './prefetch'\nimport {\n logError,\n logWarn,\n isBrowser,\n isPlainObject,\n formatAppName,\n getRootContainer,\n isString,\n pureCreateElement,\n isElement,\n isFunction,\n} from './libs/utils'\nimport { EventCenterForBaseApp } from './interact'\nimport globalEnv, { initGlobalEnv } from './libs/global_env'\nimport { appInstanceMap } from './create_app'\nimport { lifeCycles } from './constants'\nimport { router } from './sandbox/router'\n\n/**\n * if app not prefetch & not unmount, then app is active\n * @param excludeHiddenApp exclude hidden keep-alive app, default is false\n * @param excludePreRender exclude pre render app\n * @returns active apps\n */\nexport function getActiveApps ({\n excludeHiddenApp = false,\n excludePreRender = false,\n}: GetActiveAppsParam = {}): AppName[] {\n const activeApps: AppName[] = []\n appInstanceMap.forEach((app: AppInterface, appName: AppName) => {\n if (\n !app.isUnmounted() &&\n (\n !app.isPrefetch || (\n app.isPrerender && !excludePreRender\n )\n ) &&\n (\n !excludeHiddenApp ||\n !app.isHidden()\n )\n ) {\n activeApps.push(appName)\n }\n })\n\n return activeApps\n}\n\n// get all registered apps\nexport function getAllApps (): string[] {\n return Array.from(appInstanceMap.keys())\n}\n\ntype unmountAppOptions = {\n destroy?: boolean // destroy app, default is false\n clearAliveState?: boolean // clear keep-alive app state, default is false\n clearData?: boolean // clear data from base app & child app\n}\n\n/**\n * unmount app by appName\n * @param appName\n * @param options unmountAppOptions\n * @returns Promise<void>\n */\nexport function unmountApp (appName: string, options?: unmountAppOptions): Promise<boolean> {\n const app = appInstanceMap.get(formatAppName(appName))\n return new Promise((resolve) => {\n if (app) {\n if (app.isUnmounted() || app.isPrefetch) {\n if (app.isPrerender) {\n app.unmount({\n destroy: !!options?.destroy,\n clearData: !!options?.clearData,\n keepRouteState: false,\n unmountcb: resolve.bind(null, true)\n })\n } else {\n if (options?.destroy) app.actionsForCompletelyDestroy()\n resolve(true)\n }\n } else if (app.isHidden()) {\n if (options?.destroy) {\n app.unmount({\n destroy: true,\n clearData: true,\n keepRouteState: true,\n unmountcb: resolve.bind(null, true)\n })\n } else if (options?.clearAliveState) {\n app.unmount({\n destroy: false,\n clearData: !!options.clearData,\n keepRouteState: true,\n unmountcb: resolve.bind(null, true)\n })\n } else {\n resolve(true)\n }\n } else {\n const container = getRootContainer(app.container!)\n const unmountHandler = () => {\n container.removeEventListener(lifeCycles.UNMOUNT, unmountHandler)\n container.removeEventListener(lifeCycles.AFTERHIDDEN, afterhiddenHandler)\n resolve(true)\n }\n\n const afterhiddenHandler = () => {\n container.removeEventListener(lifeCycles.UNMOUNT, unmountHandler)\n container.removeEventListener(lifeCycles.AFTERHIDDEN, afterhiddenHandler)\n resolve(true)\n }\n\n container.addEventListener(lifeCycles.UNMOUNT, unmountHandler)\n container.addEventListener(lifeCycles.AFTERHIDDEN, afterhiddenHandler)\n\n if (options?.destroy) {\n let destroyAttrValue, destoryAttrValue\n container.hasAttribute('destroy') && (destroyAttrValue = container.getAttribute('destroy'))\n container.hasAttribute('destory') && (destoryAttrValue = container.getAttribute('destory'))\n\n container.setAttribute('destroy', 'true')\n container.parentNode!.removeChild(container)\n\n container.removeAttribute('destroy')\n\n isString(destroyAttrValue) && container.setAttribute('destroy', destroyAttrValue)\n isString(destoryAttrValue) && container.setAttribute('destory', destoryAttrValue)\n } else if (options?.clearAliveState && container.hasAttribute('keep-alive')) {\n const keepAliveAttrValue = container.getAttribute('keep-alive')!\n container.removeAttribute('keep-alive')\n\n let clearDataAttrValue = null\n if (options.clearData) {\n clearDataAttrValue = container.getAttribute('clear-data')\n container.setAttribute('clear-data', 'true')\n }\n\n container.parentNode!.removeChild(container)\n\n container.setAttribute('keep-alive', keepAliveAttrValue)\n isString(clearDataAttrValue) && container.setAttribute('clear-data', clearDataAttrValue)\n } else {\n let clearDataAttrValue = null\n if (options?.clearData) {\n clearDataAttrValue = container.getAttribute('clear-data')\n container.setAttribute('clear-data', 'true')\n }\n\n container.parentNode!.removeChild(container)\n\n isString(clearDataAttrValue) && container.setAttribute('clear-data', clearDataAttrValue)\n }\n }\n } else {\n logWarn(`app ${appName} does not exist`)\n resolve(false)\n }\n })\n}\n\n// unmount all apps in turn\nexport function unmountAllApps (options?: unmountAppOptions): Promise<boolean> {\n return Array.from(appInstanceMap.keys()).reduce((pre, next) => pre.then(() => unmountApp(next, options)), Promise.resolve(true))\n}\n\n/**\n * Re render app from the command line\n * microApp.reload(destroy)\n * @param appName app.name\n * @param destroy unmount app with destroy mode\n * @returns Promise<boolean>\n */\nexport function reload (appName: string, destroy?: boolean): Promise<boolean> {\n return new Promise((resolve) => {\n const app = appInstanceMap.get(formatAppName(appName))\n if (app) {\n const rootContainer = app.container && getRootContainer(app.container)\n if (rootContainer) {\n resolve(rootContainer.reload(destroy))\n } else {\n logWarn(`app ${appName} is not rendered, cannot use reload`)\n resolve(false)\n }\n } else {\n logWarn(`app ${appName} does not exist`)\n resolve(false)\n }\n })\n}\n\ninterface RenderAppOptions extends MicroAppConfig {\n name: string,\n url: string,\n container: string | Element,\n baseroute?: string,\n 'default-page'?: string,\n data?: Record<PropertyKey, unknown>,\n onDataChange?: Func,\n lifeCycles?: lifeCyclesType,\n [key: string]: unknown,\n}\n\n/**\n * Manually render app\n * @param options RenderAppOptions\n * @returns Promise<boolean>\n */\nexport function renderApp (options: RenderAppOptions): Promise<boolean> {\n return new Promise((resolve) => {\n if (!isPlainObject<RenderAppOptions>(options)) return logError('renderApp options must be an object')\n const container: Element | null = isElement(options.container) ? options.container : isString(options.container) ? document.querySelector(options.container) : null\n if (!isElement(container)) return logError('Target container is not a DOM element.')\n\n const microAppElement = pureCreateElement<any>(microApp.tagName)\n\n for (const attr in options) {\n if (attr === 'onDataChange') {\n if (isFunction(options[attr])) {\n microAppElement.addEventListener('datachange', options[attr])\n }\n } else if (attr === 'lifeCycles') {\n const lifeCycleConfig = options[attr]\n if (isPlainObject(lifeCycleConfig)) {\n for (const lifeName in lifeCycleConfig) {\n if (lifeName.toUpperCase() in lifeCycles && isFunction(lifeCycleConfig[lifeName])) {\n microAppElement.addEventListener(lifeName.toLowerCase(), lifeCycleConfig[lifeName])\n }\n }\n }\n } else if (attr !== 'container') {\n microAppElement.setAttribute(attr, options[attr])\n }\n }\n\n const handleMount = () => {\n releaseListener()\n resolve(true)\n }\n\n const handleError = () => {\n releaseListener()\n resolve(false)\n }\n\n const releaseListener = () => {\n microAppElement.removeEventListener(lifeCycles.MOUNTED, handleMount)\n microAppElement.removeEventListener(lifeCycles.ERROR, handleError)\n }\n\n microAppElement.addEventListener(lifeCycles.MOUNTED, handleMount)\n microAppElement.addEventListener(lifeCycles.ERROR, handleError)\n\n container.appendChild(microAppElement)\n })\n}\n\n/**\n * get app state\n * @param appName app.name\n * @returns app.state\n */\nexport function getAppStatus (appName: string): string | void {\n const app = appInstanceMap.get(formatAppName(appName))\n if (app) {\n return app.getLifeCycleState()\n } else {\n logWarn(`app ${appName} does not exist`)\n }\n}\n\nexport class MicroApp extends EventCenterForBaseApp implements MicroAppBaseType {\n tagName = 'micro-app'\n hasInit = false\n options: OptionsType = {}\n router: Router = router\n preFetch = preFetch\n unmountApp = unmountApp\n unmountAllApps = unmountAllApps\n getActiveApps = getActiveApps\n getAllApps = getAllApps\n reload = reload\n renderApp = renderApp\n getAppStatus = getAppStatus\n start (options?: OptionsType): void {\n if (!isBrowser || !window.customElements) {\n return logError('micro-app is not supported in this environment')\n }\n\n /**\n * TODO: 优化代码和逻辑\n * 1、同一个基座中initGlobalEnv不能被多次执行,否则会导致死循环\n * 2、判断逻辑是否放在initGlobalEnv中合适?--- 不合适\n */\n if (this.hasInit) {\n return logError('microApp.start executed repeatedly')\n }\n\n this.hasInit = true\n\n if (options?.tagName) {\n if (/^micro-app(-\\S+)?/.test(options.tagName)) {\n this.tagName = options.tagName\n } else {\n return logError(`${options.tagName} is invalid tagName`)\n }\n }\n\n initGlobalEnv()\n\n if (globalEnv.rawWindow.customElements.get(this.tagName)) {\n return logWarn(`element ${this.tagName} is already defined`)\n }\n\n if (isPlainObject<OptionsType>(options)) {\n this.options = options\n options['disable-scopecss'] = options['disable-scopecss'] ?? options.disableScopecss\n options['disable-sandbox'] = options['disable-sandbox'] ?? options.disableSandbox\n\n // load app assets when browser is idle\n options.preFetchApps && preFetch(options.preFetchApps)\n\n // load global assets when browser is idle\n options.globalAssets && getGlobalAssets(options.globalAssets)\n\n if (isPlainObject(options.plugins)) {\n const modules = options.plugins.modules\n if (isPlainObject(modules)) {\n for (const appName in modules) {\n const formattedAppName = formatAppName(appName)\n if (formattedAppName && appName !== formattedAppName) {\n modules[formattedAppName] = modules[appName]\n delete modules[appName]\n }\n }\n }\n }\n }\n\n // define customElement after init\n defineElement(this.tagName)\n }\n}\n\nconst microApp = new MicroApp()\n\nexport default microApp\n"],"names":["version","isBrowser","window","globalThis","global","self","Function","noopFalse","isArray","Array","assign","Object","rawDefineProperty","defineProperty","rawDefineProperties","defineProperties","rawToString","prototype","toString","rawHasOwnProperty","hasOwnProperty","toTypeString","value","call","isUndefined","target","undefined","isNull","isString","isBoolean","isNumber","isFunction","isPlainObject","isObject","isPromise","isConstructor","targetStr","constructor","getOwnPropertyNames","length","test","isURL","URL","href","isElement","Element","tagName","isNode","Node","nodeType","isLinkElement","isStyleElement","isScriptElement","isMicroAppBody","toUpperCase","includes","searchElement","fromIndex","TypeError","O","len","parseInt","i","Math","max","logError","msg","appName","rest","appNameTip","console","error","logWarn","warn","defer","fn","args","Promise","resolve","then","bind","createURL","Location","path","base","addProtocol","url","startsWith","location","protocol","formatAppURL","origin","pathname","search","rawWindow","fullPath","replace","e","formatAppName","name","getEffectivePath","pathArr","split","pop","join","CompletionPath","baseURI","promiseStream","promiseList","successCb","errorCb","finallyCb","finishedNum","isFinished","forEach","p","res","data","index","catch","err","requestIdleCallback","lastTime","Date","now","setTimeout","didTimeout","timeRemaining","promiseRequestIdle","callback","currentMicroAppName","setCurrentAppName","getCurrentAppName","preventSetAppName","removeDomScope","force","throttleDeferForSetAppName","pureCreateElement","options","element","rawDocument","document","createElement","__MICRO_APP_NAME__","__PURE_ELEMENT__","isInvalidQuerySelectorKey","key","isUniqueElement","getRootContainer","ShadowRoot","isShadowRoot","host","trim","str","isFireFox","navigator","userAgent","indexOf","parseQuery","result","queryList","queryItem","eqPos","slice","currentValue","push","stringifyQuery","queryObject","useSetRecord","handlers","Set","add","handler","has","delete","list","getAttributes","attr","attributes","attrMap","Map","set","injectFiberTask","fiberTasks","serialExecFiberTasks","tasks","reduce","pre","next","isInlineScript","address","execMicroAppGlobalHook","hookName","dispatchLifecyclesEvent","lifecycleName","detail","container","event","CustomEvent","currentTarget","get","formatEventInfo","microApp","lifeCycles","dispatchEvent","dispatchCustomEventToMicroApp","app","eventName","sandBox","microAppWindow","fetchSource","fetch","text","HTMLLoader","getInstance","this","instance","run","htmlUrl","ssrUrl","cache","htmlStr","onerror","Error","formatHTML","onLoadError","processHtml","plugins","match","code","mergedPlugins","modules","preCode","plugin","rootSelectorREG","bodySelectorREG","parseError","linkPath","reason","filename","CSSParser","createMatcherForRuleWithChildRule","createMatcherForNoneBraceAtRule","exec","cssText","prefix","matchRules","decodeURIComponent","reset","scopecssDisable","scopecssDisableNextLine","scopecssDisableSelectors","matchLeadingSpaces","matchComments","charAt","matchAtRule","matchStyleRule","selectors","formatSelector","recordResult","styleDeclarations","skip","m","commonMatch","_","separator","selector","matchOpenBrace","matchAllDeclarations","matchCloseBrace","nesting","cssValue","all","$1","getLinkFileDir","keyframesRule","mediaRule","customMediaRule","supportsRule","importRule","charsetRule","namespaceRule","containerRule","documentRule","pageRule","hostRule","fontFaceRule","keyframeRule","r","valList","commonHandlerForAtRuleWithSelfRule","reg","RegExp","matchComment","commentText","rule","matchArray","matchStr","strFragment","encodeURIComponent","commonAction","styleElement","__MICRO_APP_HAS_SCOPED__","parser","textContent","scopedCSS","scopecss","createPrefix","observer","MutationObserver","disconnect","hasAttribute","observe","childList","regCharacter","eventHandler","srcElement","dispatchOnLoadEvent","onload","dispatchOnErrorEvent","ObservedAttrName","appStates","microGlobalEvent","keepAliveStates","MicroAppConfig","linkList","scriptList","createSourceHandler","targetList","setInfo","info","getInfo","hasInfo","deleteInfo","link","script","deleteInlineInfo","addressList","createSourceCenter","extractLinkFromHtml","parent","isDynamic","rel","getAttribute","replaceComment","linkInfo","sourceCenter","appSpaceData","attrs","appSpace","source","links","createComment","placeholder","removeChild","globalEnv","rawSetAttribute","replaceChild","fetchLinksFromHtml","wrapElement","microAppHead","fiberStyleResult","styleList","from","fetchLinkPromise","map","fiberLinkTasks","convertStyle","handleConvertStyle","parentNode","appendChild","fetchLinkSuccess","onLoad","html","parsedCode","existParsedCode","item","getExistParseCode","setConvertStyleAttr","PREFETCH_LEVEL","DEFAULT_ROUTER_MODE","ROUTER_MODE_NATIVE","ROUTER_MODE_NATIVE_SCOPE","ROUTER_MODE_PURE","ROUTER_MODE_LIST","SCOPE_WINDOW_EVENT","SCOPE_WINDOW_ON_EVENT","SCOPE_DOCUMENT_EVENT","SCOPE_DOCUMENT_ON_EVENT","GLOBAL_KEY_TO_WINDOW","RAW_GLOBAL_TARGET","GLOBAL_CACHED_KEY","scriptTypes","isTypeModule","scriptInfo","module","useSandbox","iframe","isInlineMode","inline","isSpecialScript","getEffectWindow","getParsedFunction","currentCode","parsedFunction","getExistParseResult","code2Function","getUniqueNonceSrc","nonceStr","random","substr","isWrapInSandBox","getSandboxType","extractScriptElement","src","checkExcludeUrl","type","checkIgnoreUrl","currentScript","supportModuleScript","noModule","async","pure","isExternal","scripts","getAssetsPlugins","some","excludeChecker","ignoreChecker","fetchScriptsFromHtml","fetchScriptPromise","fetchScriptPromiseInfo","isPrefetch","isPrerender","fiberScriptTasks","fiber","prefetchLevel","bindScope","sandboxType","fetchScriptSuccess","runScript","replaceElement","__MICRO_APP_PROXY_WINDOW__","proxyWindow","setActiveProxyWindow","actionsBeforeRunScript","scriptElement","onloadHandler","moduleCount","convertScript","setConvertScriptAttr","runCode2InlineScript","microBody","querySelector","runParsedFunction","newCode","processCode","usePlugins","configs","config","loader","flatChildren","fiberStyleTasks","children","child","dom","extractSourceDom","parseHtmlString","rawElementQuerySelector","microAppBody","size","eventCenter","temRecordStep","recordStep","queue","shift","eventInfo","eventList","tempData","resArr","isEqual","f","callbacks","dispatchDataEvent","nextStepList","nextStep","isLegalName","enqueue","process","oldData","newData","keys","on","autoTrigger","off","clear","clearData","dispatch","getData","createEventName","fromBaseApp","EventCenterForGlobal","addGlobalDataListener","cb","__APP_NAME__","__AUTO_TRIGGER__","removeGlobalDataListener","setGlobalData","forceSetGlobalData","getGlobalData","clearGlobalData","clearGlobalDataListener","EventCenterForBaseApp","addDataListener","removeDataListener","setData","forceSetData","clearDataListener","EventCenterForMicroApp","super","appInstanceMap","forceDispatch","recordDataCenterSnapshot","microAppEventCenter","umdDataListeners","normal","globalEventInfo","subAppEventInfo","rebuildDataCenterSnapshot","resetDataCenterSnapshot","AppManager","getAll","values","unmountNestedApp","releaseUnmountOfNestedApp","disconnectedCallback","__MICRO_APP_UMD_MODE__","__MICRO_APP_ENVIRONMENT__","removeEventListener","isBoundedFunction","__MICRO_APP_IS_BOUND_FUNCTION__","bindFunctionToRawTarget","rawTarget","__MICRO_APP_IS_CONSTRUCTOR__","isConstructorFunction","cacheKey","bindRawObjectValue","configurable","enumerable","writable","patchDocument","sandbox","proxyDocument","documentEffect","eventListenerMap","sstEventListenerMap","onClickHandler","sstOnClickHandler","rawCreateElement","rawCreateElementNS","rawAddEventListener","rawRemoveEventListener","createElementNS","namespaceURI","addEventListener","listener","listenerList","__MICRO_APP_MARK_OPTIONS__","record","cacheList","rebuild","onclick","release","mergedProxyDocumentProps","builtInProxyProps","customProxyDocumentProps","genProxyDocumentProps","Proxy","Symbol","toStringTag","Reflect","proxyCallback","createProxyDocument","MicroDocument","rawRootDocument","hasInstance","proto","getPrototypeOf","setPrototypeOf","createMicroDocument","Document","patchWindow","filter","getOwnPropertyDescriptor","patchWindowProperty","descriptorTargetMap","scopeProperties","rawWindowScopeKeyList","injectedKeys","descriptor","escapeProperties","staticEscapeProperties","escapeKeys","ownKeys","concat","create","deleteProperty","createProxyWindow","intervalIdMap","timeoutIdMap","rawDispatchEvent","rawSetInterval","rawSetTimeout","rawClearInterval","rawClearTimeout","getEventTarget","setInterval","timeout","intervalId","timeoutId","clearInterval","clearTimeout","clearTimer","patchWindowEffect","setMicroState","microState","isRouterModeSearch","rawState","history","state","additionalState","microAppState","getMicroState","ENC_AD_RE","ENC_EQ_RE","DEC_AD_RE","DEC_EQ_RE","encodeMicroPath","commonDecode","decodeMicroPath","decPath","getMicroPathFromURL","isRouterModePure","rawLocation","getQueryObjectFromURL","hash","microPath","hashQuery","searchQuery","setMicroPathToURL","targetLocation","targetFullPath","isAttach2Hash","encodedMicroPath","baseHash","isEffectiveApp","routerMode","isRouterModeNative","isRouterModeCustom","isRouterModeNativeScope","getRouterMode","mode","inlineDisableMemoryRouter","addHistoryListener","popStateHandler","getActiveApps","excludeHiddenApp","excludePreRender","onlyForBrowser","updateMicroLocationWithEvent","isHashChange","oldHref","oldHash","updateMicroLocation","newPopStateEvent","PopStateEvent","isIframeSandbox","onpopstate","dispatchPopStateEventToMicroApp","newHashChangeEvent","HashChangeEvent","newURL","oldURL","onhashchange","dispatchHashChangeEventToMicroApp","dispatchNativeEvent","dispatchNativePopStateEvent","dispatchNativeHashChangeEvent","createMicroHistory","microLocation","rawHistory","getMicroHistoryMethod","methodName","rests","navigateWithNativeEvent","updateIframeBase","nativeHistoryNavigate","pushState","replaceState","title","rawPushState","rawReplaceState","oldFullPath","attachRouteToBrowserURL","reWriteHistoryMethod","method","currentHref","apply","patchHistory","releasePatchHistory","router","executeNavigationGuard","clearRouterWhenUnmount","handleNavigate","to","currentFullPath","navigateWithRawHistory","createNavigationMethod","reject","sandboxReady","createRawHistoryMethod","beforeGuards","afterGuards","runGuards","guards","guard","commonHandlerForAttachToURL","current","encode","decode","go","back","forward","beforeEach","afterEach","attachToURL","attachAllToURL","includeHiddenApp","includePreRender","defaultPageRecord","useMapRecord","setDefaultPage","removeDefaultPage","getDefaultPage","createDefaultPageApi","baseRouterProxy","setBaseAppRouter","baseRouter","getBaseAppRouter","createBaseRouterApi","createRouterApi","escape2RawWindowKeys","escape2RawWindowRegExpKeys","uniqueDocumentElement","hijackMicroLocationKeys","proxy2RawDocOrShadowKeys","proxy2RawDocOrShadowMethods","proxy2RawDocumentKeys","proxy2RawDocumentMethods","guardLocationKeys","createMicroLocation","childStaticLocation","browserHost","childHost","isIframe","withLocation","getTarget","commonHandler","proxyLocation","setMicroPathResult","reload","handleForPathNameAndSearch","targetPath","createLocationMethod","locationMethodName","forcedReload","createGuardLocation","guardLocation","oAssign","newLocation","targetHref","initRouteStateWithURL","defaultPage","updateBrowserURLWithLocation","autoTriggerNavigationGuard","clearRouteStateFromURL","keepRouteState","removePathFromBrowser","hashQueryStr","Number","Boolean","searchQueryStr","removeMicroPathFromURL","removeMicroState","BaseSandbox","staticScopeProperties","injectReactHMRProperty","CustomWindow","patchElementTree","updateElementInfo","node","createMicroFetch","rawFetch","input","init","createMicroXMLHttpRequest","rawXMLHttpRequest","XMLHttpRequest","open","reqUrl","createMicroEventSource","clearMicroEventSource","eventSourceMap","rawEventSource","EventSource","eventSourceUrl","eventSourceInitDict","eventSourceList","close","useMicroEventSource","WithSandBox","patchWith","getSpecialProperties","patchRouter","windowEffect","setMappingPropertiesWithRawDescriptor","initStaticGlobalKeys","start","umdMode","baseroute","disablePatchRequest","active","initRouteState","removeHistoryListener","__MICRO_APP_BASE_ROUTE__","__MICRO_APP_BASE_URL__","initGlobalKeysWhenStart","__MICRO_APP_URL__","activeSandbox","patchElementAndDocument","activeCount","_babelPolyfill","stop","destroy","recordAndReleaseEffect","clearRouteState","releasePatchElementAndDocument","__MICRO_APP_PUBLIC_PATH__","__MICRO_APP_WINDOW__","__MICRO_APP_PRE_RENDER__","__MICRO_APP_SANDBOX__","__MICRO_APP_SANDBOX_TYPE__","preventRecord","resetEffectSnapshot","recordEffectSnapshot","releaseGlobalEffect","rebuildEffectSnapshot","keepAlive","commonActionForSpecialProperties","setPreRenderState","markUmdMode","topValue","parentValue","top","createDescriptorForMicroAppWindow","setHijackProperty","patchRequestApi","setScopeProperties","modifiedEval","modifiedImage","eval","Image","ImageProxy","microFetch","microXMLHttpRequest","microEventSource","microHistory","createMicroRouter","setRouteInfoForKeepAliveApp","removeRouteInfoForKeepAliveApp","patchStaticElement","actionBeforeExecScripts","setStaticAppState","__MICRO_APP_STATE__","customProperties","microRootDocument","microDocument","rawMicroCreateElement","rawMicroCreateElementNS","rawMicroCreateTextNode","createTextNode","rawMicroCreateDocumentFragment","createDocumentFragment","rawMicroCreateComment","rawMicroQuerySelector","rawMicroQuerySelectorAll","querySelectorAll","rawMicroGetElementById","getElementById","rawMicroGetElementsByClassName","getElementsByClassName","rawMicroGetElementsByTagName","getElementsByTagName","rawMicroGetElementsByName","getElementsByName","rawMicroElementFromPoint","elementFromPoint","rawMicroCaretRangeFromPoint","caretRangeFromPoint","getDefaultRawTarget","_this","x","y","range","patchDocumentPrototype","getCommonDescriptor","getter","createDescriptors","documentElement","scrollingElement","desc","patchDocumentProperty","bindTarget","createSetterHandler","__MICRO_APP_BOUND_FUNCTION__","patchDocumentEffect","patchElement","rawRootElement","microRootNode","microRootElement","rawMicroAppendChild","rawMicroInsertBefore","insertBefore","rawMicroReplaceChild","rawMicroRemoveChild","rawMicroAppend","append","rawMicroPrepend","prepend","rawMicroInsertAdjacentElement","insertAdjacentElement","rawMicroCloneNode","cloneNode","rawInnerHTMLDesc","rawParentNodeDesc","rawOwnerDocumentDesc","isPureNode","isBaseElement","getRawTarget","microHead","head","body","getRootNode","oldChild","contains","nodes","hasPureNode","where","deep","getRootElementParentNode","construct","Target","elementImage","patchIframeNode","rawMicroSetAttribute","setAttribute","protoAttrList","HTMLImageElement","HTMLScriptElement","HTMLLinkElement","patchIframeAttribute","IframeSandbox","baseElement","deleteIframeElement","createIframeElement","contentWindow","patchIframe","createIframeTemplate","childFullPath","browserPath","iframeAttrs","iframeSrc","style","id","createIframeBase","oldMicroDocument","iframeLocationReady","$dom","firstChild","clearDOM","innerHTML","CreateApp","CREATED","getInlineModeState","loadSourceCode","createSandbox","setAppState","LOADING","loadSourceLevel","isUnmounted","mount","LOAD_FAILED","appState","BEFORE_MOUNT","nextAction","cloneContainer","preRenderEvents","dispatchBeforeMount","setLifeCycleState","BEFOREMOUNT","MOUNTING","handleMounted","umdHookMount","initHook","deferScriptPromise","deferScriptInfo","errorCount","execScripts","unmount","getUmdLibraryHooks","umdHookUnmount","umdHookMountResult","dispatchAction","dispatchMountedEvent","MOUNTED","getMicroAppGlobalHook","ONMOUNT","isHidden","unmountcb","UNMOUNT","umdHookUnmountResult","ONUNMOUNT","handleUnmounted","actionsForUnmount","clearOptions","setKeepAliveState","actionsForCompletelyDestroy","hiddenKeepAliveApp","KEEP_ALIVE_HIDDEN","AFTERHIDDEN","showKeepAliveApp","BEFORESHOW","KEEP_ALIVE_SHOW","AFTERSHOW","ERROR","htmlString","DOMParser","parseFromString","childNodes","getAppState","lifeCycleState","getLifeCycleState","keepAliveState","getKeepAliveState","libraryName","rawElementQuerySelectorAll","dynamicElementInMicroAppMap","WeakMap","getMappingNode","handleNewNode","linkReplaceComment","excludeAssetFilter","replaceStyle","originLink","handleDynamicLink","formatDynamicLink","originScript","dispatchScriptOnLoadEvent","runDynamicScript","runDynamicRemoteScript","runDynamicInlineScript","invokePrototypeMethod","rawMethod","targetChild","passiveChild","hijackParent","getHijackParent","rawRemoveChild","__MICRO_APP_HAS_DPN__","rawInsertBefore","indexOfParent","invokeRawMethod","rawAppendChild","rawAppend","rawPrepend","commonElementHandler","newChild","currentAppName","completePathDynamic","getBindTarget","isProxyDocument","rawQuerySelector","rawQuerySelectorAll","markElement","rawCreateDocumentFragment","rawCreateComment","rawGetElementById","rawGetElementsByClassName","rawGetElementsByTagName","rawGetElementsByName","rawRootNode","getQueryTarget","refChild","rawReplaceChild","rawCreateTextNode","processedEle","realParent","rawInsertAdjacentElement","clonedNode","rawCloneNode","firstElementChild","releasePatchDocument","hasRejectMicroAppStyle","initGlobalEnv","rawRootEventTarget","EventTarget","__MICRO_APP_BASE_APPLICATION__","rejectMicroAppStyle","defineElement","MicroAppElement","HTMLElement","getBaseHTMLElement","isWaiting","formatAttrName","formatAttrUrl","legalAttribute","oldApp","appUrl","actionsForAttributeChange","getKeepAliveModeResult","handleHiddenKeepAliveApp","observedAttributes","connectedCallback","cacheCount","connectedCount","connectStateMap","effectiveApp","handleConnected","handleDisconnected","handleAfterReload","attributeChangedCallback","_oldVal","newVal","NAME","handleAttributeUpdate","formatNewName","cacheData","handleInitialNameAndUrl","getDisposeResult","shadowRoot","attachShadow","updateSsrUrl","oldAppUrl","targetUrl","handleShowKeepAliveApp","sameCoreOptions","handleMount","handleCreateApp","val","createAppInstance","useScopecss","getMemoryRouterMode","getBaseRouteCompatible","getDestroyCompatibleResult","compatibleProperties","compatibleDisableProperties","baseUrl","formatLocation","getNoHashMicroPathFromURL","defaultPagePath","cloneValue","ownKey","publicPath","baseRoute","customElements","define","preFetch","apps","delay","delayTime","prefetchDelay","preFetchAction","onLine","disableScopecss","disableSandbox","level","oldOnload","oldOnLoadError","onLoadParam","preFetchInSerial","fetchGlobalResources","resources","suffix","sourceHandler","effectiveResource","activeApps","getAllApps","unmountApp","clearAliveState","unmountHandler","afterhiddenHandler","destroyAttrValue","destoryAttrValue","removeAttribute","keepAliveAttrValue","clearDataAttrValue","unmountAllApps","rootContainer","renderApp","microAppElement","lifeCycleConfig","lifeName","toLowerCase","releaseListener","handleError","getAppStatus","MicroApp","assets","hasInit","preFetchApps","globalAssets","js","css","formattedAppName"],"mappings":"sPAWaA,EAAU,aAGVC,EAA8B,oBAAXC,OAGnBC,EAAgC,oBAAXC,OAC9BA,OAEmB,oBAAXF,OACJA,OA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