kj-micro-app 1.0.3 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.esm.js +3 -3
- package/lib/index.esm.js.map +1 -1
- package/lib/index.min.js +1 -1
- package/lib/index.min.js.map +1 -1
- package/lib/index.umd.js +1 -1
- package/lib/index.umd.js.map +1 -1
- package/package.json +1 -1
package/lib/index.umd.js.map
CHANGED
|
@@ -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/adapter.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/router/location.ts","../src/sandbox/router/index.ts","../src/sandbox/request.ts","../src/sandbox/with/index.ts","../src/sandbox/iframe/special_key.ts","../src/proxies/worker.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 MicroAppElementInterface,\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 isCanvasElement(target: unknown): target is HTMLCanvasElement {\n return toTypeString(target) === '[object HTMLCanvasElement]'\n}\n\nexport function isAnchorElement(target: unknown): target is HTMLAnchorElement {\n return toTypeString(target) === '[object HTMLAnchorElement]'\n}\n\nexport function isAudioElement(target: unknown): target is HTMLAudioElement {\n return toTypeString(target) === '[object HTMLAudioElement]'\n}\n\nexport function isVideoElement(target: unknown): target is HTMLVideoElement {\n return toTypeString(target) === '[object HTMLVideoElement]'\n}\n\nexport function isLinkElement(target: unknown): target is HTMLLinkElement {\n return toTypeString(target) === '[object HTMLLinkElement]'\n}\nexport function isBodyElement(target: unknown): target is HTMLBodyElement {\n return toTypeString(target) === '[object HTMLBodyElement]'\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 isDocumentFragment(target: unknown): target is DocumentFragment {\n return toTypeString(target) === '[object DocumentFragment]'\n}\n\nexport function isDocumentShadowRoot(target: unknown): target is DocumentFragment {\n return toTypeString(target) === '[object ShadowRoot]'\n}\n\nexport function isMicroAppBody(target: unknown): target is HTMLElement {\n return isElement(target) && target.tagName.toUpperCase() === 'MICRO-APP-BODY'\n}\n\nexport function isMicroAppHead(target: unknown): target is HTMLElement {\n return isElement(target) && target.tagName.toUpperCase() === 'MICRO-APP-HEAD'\n}\n\nexport function isWebComponentElement(target: unknown): boolean {\n let result = toTypeString(target) === '[object HTMLElement]'\n if (result) {\n const tagName = (target as HTMLElement).tagName.toUpperCase()\n result = result && !tagName.startsWith('MICRO-APP')\n }\n return result\n}\n\n// is ProxyDocument\nexport function isProxyDocument(target: unknown): target is Document {\n return toTypeString(target) === '[object ProxyDocument]'\n}\n\nexport function isTargetExtension(path: string, suffix: string): boolean {\n try {\n return createURL(path).pathname.split('.').pop() === suffix\n } catch {\n return false\n }\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 * async execution with macro task\n * @param fn callback\n * @param args params\n */\nexport function macro(fn: Func, delay = 0, ...args: unknown[]): void {\n setTimeout(fn.bind(null, ...args), delay)\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, port, host, protocol} = createURL(addProtocol(url), (window.rawWindow || window).location.href)\n\n // 自定义协议时, origin 返回字符串 null\n let newOrigin = origin;\n if (origin == 'null') {\n if (port) {\n newOrigin = protocol + '//' + host + ':' + port\n } else {\n newOrigin = protocol + '//' + host\n }\n }\n console.log('newOrigin', newOrigin, origin);\n\n /**\n * keep the original url unchanged, such as .html .node .php .net .etc, search, except hash\n * BUG FIX: Never using '/' to complete url, refer to https://github.com/jd-opensource/micro-app/issues/1147\n */\n const fullPath = `${newOrigin}${pathname}${search}`\n console.log('fullPath', fullPath);\n return /^\\w+?:\\/\\//.test(fullPath) ? fullPath : ''\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\n * 1. https://domain/xx/xx.html to https://domain/xx/\n * 2. https://domain/xx to https://domain/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 pathArr = `${origin}${pathname}`.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 /^((\\w+):)?\\/\\//.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 currentAppName: string | null = null\nexport function setCurrentAppName(appName: string | null): void {\n currentAppName = appName\n}\n\n// get the currently running app.name\nexport function getCurrentAppName(): string | null {\n return currentAppName\n}\n\nexport function throttleDeferForSetAppName(appName: string): void {\n if (currentAppName !== appName && !getPreventSetState()) {\n setCurrentAppName(appName)\n defer(() => {\n setCurrentAppName(null)\n })\n }\n}\n\n// only for iframe document.body(head).querySelector(querySelectorAll)\nlet iframeCurrentAppName: string | null = null\nexport function setIframeCurrentAppName(appName: string | null) {\n iframeCurrentAppName = appName\n}\n\nexport function getIframeCurrentAppName(): string | null {\n return iframeCurrentAppName\n}\n\nexport function throttleDeferForIframeAppName(appName: string): void {\n if (iframeCurrentAppName !== appName && !getPreventSetState()) {\n setIframeCurrentAppName(appName)\n defer(() => {\n setIframeCurrentAppName(null)\n })\n }\n}\n\n// prevent set app name\nlet preventSetState = false\nexport function getPreventSetState(): boolean {\n return preventSetState\n}\n\n/**\n * prevent set appName\n * usage:\n * removeDomScope(true)\n * -----> element scope point to base app <-----\n * removeDomScope(false)\n */\nexport function removeDomScope(force?: boolean): void {\n if (force !== false) {\n setCurrentAppName(null)\n setIframeCurrentAppName(null)\n if (force && !preventSetState) {\n preventSetState = true\n defer(() => {\n preventSetState = false\n })\n }\n } else {\n preventSetState = false\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\nexport type RootContainer = HTMLElement & MicroAppElementInterface\n/**\n * get micro-app element\n * @param target app container\n */\nexport function getRootContainer(target: HTMLElement | ShadowRoot): RootContainer {\n return (isShadowRoot(target) ? (target as ShadowRoot).host : target) as RootContainer\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\nexport function instanceOf<T extends new (...args: unknown[]) => unknown>(\n instance: unknown,\n constructor: T,\n): instance is T extends new (...args: unknown[]) => infer R ? R : boolean {\n if (instance === null || instance === undefined) {\n return false\n } else if (!isFunction(constructor)) {\n throw new TypeError(\"Right-hand side of 'instanceof' is not callable\")\n } else if (typeof instance === 'number' || typeof instance === 'string' || typeof instance === 'boolean') {\n // 检查 obj 是否是基本类型的包装器实例\n return false\n }\n let proto = Object.getPrototypeOf(instance)\n while (proto) {\n if (proto === constructor.prototype) {\n return true\n }\n proto = Object.getPrototypeOf(proto)\n }\n return false\n}\n\n/**\n * Format event name\n * In with sandbox, child event and lifeCycles bind to microAppElement, there are two events with same name - mounted unmount, it should be handled specifically to prevent conflicts\n * Issue: https://github.com/jd-opensource/micro-app/issues/1161\n * @param type event name\n * @param appName app name\n */\nconst formatEventList = ['mounted', 'unmount']\nexport function formatEventType(type: string, appName: string): string {\n return formatEventList.includes(type) ? `${type}-${appName}` : type\n}\n\n/**\n * Is the object empty\n * target maybe number, string, array ...\n */\nexport function isEmptyObject(target: unknown): boolean {\n return isPlainObject(target) ? !Object.keys(target).length : true\n}\n","import type { lifeCyclesType, AppInterface } from '@micro-app/types'\nimport microApp from '../micro_app'\nimport {\n logWarn,\n isFunction,\n removeDomScope,\n getRootContainer,\n assign,\n formatEventType,\n} 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 | null,\n appName: string,\n lifecycleName: LifecycleEventName,\n error?: Error,\n): void {\n if (!element) {\n return logWarn(`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, appName)\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 ['mounted', 'unmount', 'appstate-change', 'statechange']\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(formatEventType(eventName, app.name), {\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, isTargetExtension } 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 isJsResource = isTargetExtension(htmlUrl, 'js')\n const htmlPromise = isJsResource\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 this.printError('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 /**\n * NOTE:\n * 1. :is(h1, h2, h3):has(+ h2, + h3, + h4) {}\n * should be ==> micro-app[name=xxx] :is(h1, h2, h3):has(+ h2, + h3, + h4) {}\n * 2. :dir(ltr) {}\n * should be ==> micro-app[name=xxx] :dir(ltr) {}\n * 3. body :not(div, .fancy) {}\n * should be ==> micro-app[name=xxx] micro-app-body :not(div, .fancy) {}\n * 4. .a, .b, li:nth-child(3)\n * should be ==> micro-app[name=xxx] .a, micro-app[name=xxx] .b, micro-app[name=xxx] li:nth-child(3)\n * 5. :is(.a, .b, .c) a {}\n * should be ==> micro-app[name=xxx] :is(.a, .b, .c) a {}\n * 6. :where(.a, .b, .c) a {}\n * should be ==> micro-app[name=xxx] :where(.a, .b, .c) a {}\n */\n const attributeValues: {[key: string]: any} = {}\n const matchRes = m[0].replace(/\\[([^\\]=]+)(?:=([^\\]]+))?\\]/g, (match, p1, p2, offset) => {\n const mock = `__mock_${p1}_${offset}Value__`\n attributeValues[mock] = p2\n return match.replace(p2, mock)\n })\n\n return matchRes.replace(/(^|,[\\n\\s]*)([^,]+)/g, (_, separator, selector) => {\n selector = trim(selector)\n selector = selector.replace(/\\[[^\\]=]+(?:=([^\\]]+))?\\]/g, (match:string, p1: string) => {\n if (attributeValues[p1]) {\n return match.replace(p1, attributeValues[p1])\n }\n return match\n })\n if (selector && !(\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 this.printError(\"Declaration missing '{'\", this.linkPath)\n\n this.matchAllDeclarations()\n\n if (!this.matchCloseBrace()) return this.printError(\"Declaration missing '}'\", this.linkPath)\n\n return true\n }\n\n private matchAllDeclarations (nesting = 0): 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\\(([\"']?)(.*?)\\1\\)/gm, (all, _, $1) => {\n if (/^((data|blob):|#|%23)/.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.length) return\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 } else if (this.cssText.charAt(0) === '{') {\n this.matchOpenBrace()\n nesting++\n } else if (this.cssText.charAt(0) === '}') {\n if (nesting < 1) return\n this.matchCloseBrace()\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 this.layerRule()\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 this.printError('@keyframes missing name', this.linkPath)\n\n this.matchComments()\n\n if (!this.matchOpenBrace()) return this.printError(\"@keyframes missing '{'\", this.linkPath)\n\n this.matchComments()\n while (this.keyframeRule()) {\n this.matchComments()\n }\n\n if (!this.matchCloseBrace()) return this.printError(\"@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/CSS/@layer\n private layerRule (): boolean | void {\n if (!this.commonMatch(/^@layer\\s*([^{;]+)/)) return false\n\n if (!this.matchOpenBrace()) return !!this.commonMatch(/^[;]+/)\n\n this.matchComments()\n\n this.matchRules()\n\n if (!this.matchCloseBrace()) return this.printError('@layer missing \\'}\\'', this.linkPath)\n\n this.matchLeadingSpaces()\n\n return true\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 this.printError(`${name} missing '{'`, this.linkPath)\n\n this.matchComments()\n\n this.matchRules()\n\n if (!this.matchCloseBrace()) return this.printError(`${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 this.printError(`@${name} missing '{'`, this.linkPath)\n\n this.matchAllDeclarations()\n\n if (!this.matchCloseBrace()) return this.printError(`@${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 this.printError('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(/^}\\s*/)\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/jd-opensource/micro-app/issues/256\n if (isFireFox()) {\n this.result += encodeURIComponent(strFragment)\n } else {\n this.result += strFragment\n }\n }\n\n private printError (msg: string, linkPath?: string): void {\n if (this.cssText.length) {\n parseError(msg, linkPath)\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 const escapeRegExp = (regStr: string) => regStr.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n if (styleElement.textContent) {\n commonAction(styleElement, app.name, prefix, app.url, linkPath)\n\n const observer = new MutationObserver(() => {\n const escapedPrefix = escapeRegExp(prefix)\n const isPrefixed = styleElement.textContent && new RegExp(escapedPrefix).test(styleElement.textContent)\n observer.disconnect()\n if (!isPrefixed) {\n styleElement.__MICRO_APP_HAS_SCOPED__ = false\n scopedCSS(styleElement, app, linkPath)\n }\n })\n observer.observe(styleElement, { childList: true, characterData: true })\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 KEEP_ALIVE = 'keep-alive',\n CLEAR_DATA ='clear-data',\n SSR = 'ssr',\n FIBER = 'fiber',\n}\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\n// prefetch level\nexport const PREFETCH_LEVEL: number[] = [1, 2, 3]\n\n/**\n * memory router modes\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 * 2. native mode equal to disable-memory-router\n*/\n// 临时注释,1.0版本放开,默认模式切换为state\n// // default mode, sync child app router info to history.state\n// export const DEFAULT_ROUTER_MODE = 'state'\n// // sync child app router info to browser url as search\n// export const ROUTER_MODE_SEARCH = 'search'\n\n// 临时放开,1.0版本去除\nexport const ROUTER_MODE_STATE = 'state'\nexport const DEFAULT_ROUTER_MODE = 'search'\n\n// render base on browser url, and location.origin location.href point to base app\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_STATE,\n ROUTER_MODE_NATIVE,\n ROUTER_MODE_NATIVE_SCOPE,\n ROUTER_MODE_PURE,\n]\n\n// event bound to child app window\nconst BASE_SCOPE_WINDOW_EVENT = [\n 'popstate',\n 'hashchange',\n 'load',\n 'unload',\n 'unmount',\n 'appstate-change',\n 'statechange',\n 'mounted',\n 'error'\n // 'beforeunload', // remove at 2024.5.30 by cangdu\n]\n\n// bind event of with sandbox\nexport const SCOPE_WINDOW_EVENT_OF_WITH = BASE_SCOPE_WINDOW_EVENT\n\n// bind event of iframe sandbox\nexport const SCOPE_WINDOW_EVENT_OF_IFRAME = BASE_SCOPE_WINDOW_EVENT.concat([\n 'unhandledrejection',\n 'message'\n])\n\n// on event bound to child app window\n// TODO: with和iframe处理方式不同,需修改\nconst BASE_SCOPE_WINDOW_ON_EVENT = [\n 'onpopstate',\n 'onhashchange',\n 'onload',\n 'onunload',\n 'onerror'\n // 'onbeforeunload', // remove at 2024.5.30 by cangdu\n]\n\n// bind on event of with sandbox\nexport const SCOPE_WINDOW_ON_EVENT_OF_WITH = BASE_SCOPE_WINDOW_ON_EVENT\n\n// bind on event of iframe sandbox\nexport const SCOPE_WINDOW_ON_EVENT_OF_IFRAME = BASE_SCOPE_WINDOW_ON_EVENT.concat([\n 'onunhandledrejection',\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\nexport const HIJACK_LOCATION_KEYS = [\n 'host',\n 'hostname',\n 'port',\n 'protocol',\n 'origin',\n]\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', 'modulepreload', 'icon'].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.warn(`[micro-app from ${replaceElement ? 'runDynamicScript' : 'runScript'}] app ${app.name}: `, e, address)\n // throw error in with sandbox to parent app\n const error = e as Error\n let throwError = true\n if (typeof microApp?.options?.excludeRunScriptFilter === 'function') {\n throwError = microApp.options.excludeRunScriptFilter(address, error, app.name, app.url) !== true\n }\n if (throwError) {\n throw e\n }\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 with src='${address}' 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 inline 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/jd-opensource/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 isBodyElement,\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 body body element\n * @param app app\n * @param microAppHead micro-app-head element\n */\nfunction flatBodyChildren(\n body: HTMLElement,\n app: AppInterface,\n fiberStyleTasks: fiberTasks,\n): void {\n if (!body || !isBodyElement(body)) {\n return\n }\n const links = Array.from(body.getElementsByTagName('link'))\n\n links.map((dom) => {\n if (dom.hasAttribute('exclude') || checkExcludeUrl(dom.getAttribute('href'), app.name)) {\n dom.parentElement!.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, dom.parentElement, app)\n } else if (dom.hasAttribute('href')) {\n globalEnv.rawSetAttribute.call(dom, 'href', CompletionPath(dom.getAttribute('href')!, app.url))\n }\n return dom\n })\n\n const styles = Array.from(body.getElementsByTagName('style'))\n\n styles.map((dom) => {\n if (dom.hasAttribute('exclude')) {\n dom.parentElement!.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 return dom\n })\n\n const scripts = Array.from(body.getElementsByTagName('script'))\n\n scripts.map((dom) => {\n extractScriptElement(dom, dom.parentElement, app)\n return dom\n })\n const images = Array.from(body.getElementsByTagName('img'))\n\n images.map((dom) => {\n if (dom.hasAttribute('src')) {\n globalEnv.rawSetAttribute.call(dom, 'src', CompletionPath(dom.getAttribute('src')!, app.url))\n }\n return dom\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 flatBodyChildren(wrapElement, app, fiberStyleTasks)\n\n /**\n * Style and link are parallel, as 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 ? `__${appName}_from_base_app__` : `__${appName}_from_micro_app__`\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 changeEventAppName (newAppName: string, oldAppName: string): void {\n const newEventName = createEventName(formatAppName(newAppName), true)\n const oldEventName = createEventName(formatAppName(oldAppName), true)\n if (eventCenter.eventList.has(oldEventName)) {\n eventCenter.eventList.set(newEventName, eventCenter.eventList.get(oldEventName))\n eventCenter.eventList.delete(oldEventName)\n }\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'\ninterface IEventInfo {\n data: Record<PropertyKey, unknown>\n tempData?: Record<PropertyKey, unknown> | null\n force?: boolean\n callbacks: Set<CallableFunctionForInteract>\n}\n\nexport default class EventCenter {\n public eventList = new Map<string, IEventInfo | undefined>()\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 /**\n * In safari, nest app like: A -> B -> C\n * if B is iframe sandbox, and C is with sandbox, same property of document in C is abnormal\n * e.g:\n * document.all:\n * - typeof document.all ==> 'function'\n * - document.all.bind ==> undefined\n */\n if (isFunction(value) && !isConstructorFunction(value) && !isBoundedFunction(value) && value.bind) {\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","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 isMicroAppBody,\n getPreventSetState,\n throttleDeferForIframeAppName,\n isAnchorElement,\n} from '../libs/utils'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} from '../create_app'\nimport microApp from '../micro_app'\nimport { AppManager } from '../app_manager'\n\nexport class BaseSandbox implements BaseSandboxType {\n constructor (appName: string, url: string) {\n this.appName = appName\n this.url = url\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 'event',\n ]\n\n public appName: string\n public url: string\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 // reset mount, unmount when stop in default mode\n public clearHijackUmdHooks!: () => 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/jd-opensource/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 (\n container: Node,\n appName: string,\n): void {\n const children = Array.from(container.childNodes)\n\n children.length && children.forEach((child) => {\n patchElementTree(child, appName)\n })\n\n updateElementInfo(container, appName)\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 | null): T {\n if (\n appName &&\n isNode(node) &&\n node.__MICRO_APP_NAME__ !== appName &&\n !node.__PURE_ELEMENT__ &&\n !getPreventSetState()\n ) {\n /**\n * TODO:\n * 1. 测试baseURI和ownerDocument在with沙箱中是否正确\n * 经过验证with沙箱不能重写ownerDocument,否则react点击事件会触发两次\n */\n const props: {[kye:string]:any} = {\n __MICRO_APP_NAME__: {\n configurable: true,\n enumerable: true,\n writable: true,\n value: appName,\n },\n }\n if (isAnchorElement(node)) {\n // a 标签\n const microApp = AppManager.getInstance().get(appName)\n const hrefDescriptor = Object.getOwnPropertyDescriptor(node, 'href')\n const hrefConfigurable = hrefDescriptor?.configurable || !hrefDescriptor\n if (microApp && hrefConfigurable) {\n props.href = {\n get() {\n return this.getAttribute('href')\n },\n set(value: string) {\n if (value === undefined) {\n return\n }\n this.setAttribute('href', value)\n },\n }\n }\n }\n rawDefineProperties(node, props)\n\n /**\n * In FireFox, iframe Node.prototype will point to native Node.prototype after insert to document\n *\n * Performance:\n * iframe element.__proto__ === browser HTMLElement.prototype // Chrome: false, FireFox: true\n * iframe element.__proto__ === iframe HTMLElement.prototype // Chrome: true, FireFox: false\n *\n * NOTE:\n * 1. Node.prototype.baseURI\n * 2. Node.prototype.ownerDocument\n * 3. Node.prototype.parentNode\n * 4. Node.prototype.getRootNode\n * 5. Node.prototype.cloneNode\n * 6. Element.prototype.innerHTML\n * 7. Image\n */\n if (isIframeSandbox(appName)) {\n const proxyWindow = appInstanceMap.get(appName)?.sandBox?.proxyWindow\n if (proxyWindow) {\n rawDefineProperties(node, {\n baseURI: {\n configurable: true,\n enumerable: true,\n get: () => proxyWindow.location.href,\n },\n ownerDocument: {\n configurable: true,\n enumerable: true,\n get: () => node !== proxyWindow.document ? proxyWindow.document : null,\n },\n parentNode: getIframeParentNodeDesc(\n appName,\n globalEnv.rawParentNodeDesc,\n ),\n getRootNode: {\n configurable: true,\n enumerable: true,\n writable: true,\n value: function getRootNode (): Node {\n return proxyWindow.document\n }\n },\n })\n }\n }\n }\n\n return node\n}\n\n/**\n * get Descriptor of Node.prototype.parentNode for iframe\n * @param appName app name\n * @param parentNode parentNode Descriptor of iframe or browser\n */\nexport function getIframeParentNodeDesc (\n appName: string,\n parentNodeDesc: PropertyDescriptor,\n): PropertyDescriptor {\n return {\n configurable: true,\n enumerable: true,\n get (this: Node) {\n throttleDeferForIframeAppName(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 * e.g.:\n * 1. element-ui@2.x el-dropdown\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 const customParent = microApp.options.getRootElementParentNode?.(this, appName)\n if (customParent) {\n return customParent\n }\n if (microApp?.options?.inheritBaseBody !== true) {\n return appInstanceMap.get(appName)?.container?.querySelector('micro-app-body') || globalEnv.rawDocument.body\n }\n return globalEnv.rawDocument.body\n }\n return result\n }\n }\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'\nimport {\n updateElementInfo,\n} from '../adapter'\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 return updateElementInfo(element, appName)\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 return updateElementInfo(element, appName)\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_OF_WITH,\n SCOPE_WINDOW_ON_EVENT_OF_WITH,\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 formatEventType,\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_OF_WITH.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/jd-opensource/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_OF_WITH.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 type = formatEventType(type, appName)\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 type = formatEventType(type, appName)\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 setTimeoutHander = function(...args: any[]) {\n timeoutIdMap.delete(timeoutId)\n typeof handler === 'function' && handler(...args)\n }\n const handlerWithCleanup: TimerHandler = typeof handler === 'string' ? handler : setTimeoutHander\n const timeoutId = rawSetTimeout.call(rawWindow, handlerWithCleanup, timeout, ...args)\n timeoutIdMap.set(timeoutId, { handler: handlerWithCleanup, 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 MicroRouterInfoState,\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 isEmptyObject,\n} from '../../libs/utils'\nimport {\n appInstanceMap,\n} from '../../create_app'\nimport {\n ROUTER_MODE_LIST,\n DEFAULT_ROUTER_MODE,\n ROUTER_MODE_STATE,\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 targetLocation?: MicroLocation,\n): MicroState {\n // TODO: 验证native模式下修改state nextjs路由是否正常\n const rawState = globalEnv.rawWindow.history.state\n const additionalState: Record<'__MICRO_APP_STATE__', Record<string, MicroRouterInfoState>> = {\n __MICRO_APP_STATE__: assign({}, rawState?.__MICRO_APP_STATE__, {\n [appName]: {\n fullPath: targetLocation ? targetLocation.pathname + targetLocation.search + targetLocation.hash : null,\n state: microState ?? null,\n mode: getRouterMode(appName),\n }\n }),\n }\n\n // create new state object\n return assign({}, rawState, additionalState)\n}\n\n// delete micro app state form origin state\nexport function removeMicroState (appName: string, rawState: MicroState): MicroState {\n if (isPlainObject(rawState?.__MICRO_APP_STATE__)) {\n if (!isUndefined(rawState.__MICRO_APP_STATE__[appName])) {\n delete rawState.__MICRO_APP_STATE__[appName]\n }\n if (!Object.keys(rawState.__MICRO_APP_STATE__).length) {\n delete rawState.__MICRO_APP_STATE__\n }\n }\n\n return !isEmptyObject(rawState) ? assign({}, rawState) : null\n}\n\n// get micro app state form origin state\nexport function getMicroState (appName: string): MicroState {\n const rawState = globalEnv.rawWindow.history.state\n return rawState?.__MICRO_APP_STATE__?.[appName]?.state || null\n}\n\n// get micro app router info state form origin state\nexport function getMicroRouterInfoState (appName: string): MicroRouterInfoState | null {\n const rawState = globalEnv.rawWindow.history.state\n return rawState?.__MICRO_APP_STATE__?.[appName] || null\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 const rawState = globalEnv.rawWindow.history.state\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 /**\n * Get fullPath from __MICRO_APP_STATE__\n * NOTE:\n * 1. state mode: all base on __MICRO_APP_STATE__\n * 2. pure mode: navigate by location.xxx may contain one-time information in __MICRO_APP_STATE__\n * 3. native mode: vue-router@4 will exec replaceState with history.state before pushState, like:\n * history.replaceState(\n * assign({}, history.state, {...}),\n * title,\n * history.state.current, <---\n * )\n * when base app jump to another page from child page, it will replace child path with base app path\n * e.g: base-home --> child-home --> child-about(will replace with child-home before jump to base-home) --> base-home, when go back, it will back to child-home not child-about\n * So we take the fullPath as standard\n */\n // 问题:1、同一个页面多个子应用,一个修改后... --- native模式不支持多个子应用同时渲染,多个子应用推荐使用其它模式\n // if (isRouterModeCustom(appName)) {\n // return rawLocation.pathname + rawLocation.search + rawLocation.hash\n // }\n // return rawState?.__MICRO_APP_STATE__?.[appName]?.fullPath || null\n return rawState?.__MICRO_APP_STATE__?.[appName]?.fullPath || (isRouterModeCustom(appName) ? rawLocation.pathname + rawLocation.search + rawLocation.hash : null)\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 rawLocation = globalEnv.rawWindow.location\n let targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n let isAttach2Hash = false\n if (isRouterModeSearch(appName)) {\n let { pathname, search, hash } = rawLocation\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 // TODO: 这里和下面的if判断可以简化一下\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 if (isRouterModeState(appName) || isRouterModePure(appName)) {\n targetFullPath = rawLocation.pathname + rawLocation.search + rawLocation.hash\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 */\nexport function removeMicroPathFromURL (appName: string): HandleMicroPathResult {\n let { pathname, search, hash } = 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/**\n * get router mode of app\n * NOTE: app maybe undefined\n */\nfunction getRouterMode (appName: string): string | undefined {\n return appInstanceMap.get(appName)?.routerMode\n}\n\n// router mode is search\nexport function isRouterModeSearch (appName: string): boolean {\n return getRouterMode(appName) === DEFAULT_ROUTER_MODE\n}\n\n// router mode is state\nexport function isRouterModeState (appName: string): boolean {\n return getRouterMode(appName) === ROUTER_MODE_STATE\n}\n\n// router mode is history\nexport function isRouterModeNative (appName: string): boolean {\n return getRouterMode(appName) === ROUTER_MODE_NATIVE\n}\n\n// router mode is disable\nexport function isRouterModeNativeScope (appName: string): boolean {\n return getRouterMode(appName) === ROUTER_MODE_NATIVE_SCOPE\n}\n\n// router mode is pure\nexport function isRouterModePure (appName: string): boolean {\n return getRouterMode(appName) === 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 initRouterMode (\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 getMicroRouterInfoState,\n isEffectiveApp,\n isRouterModeCustom,\n} from './core'\nimport {\n updateMicroLocation,\n} from './location'\nimport {\n removeDomScope,\n isFunction,\n macro,\n getRootContainer,\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 /**\n * base app may respond to popstateEvent async(lazy load page & browser back/forward), but child app will respond to popstateEvent immediately(vue2, react), this will cause some problems\n * 2 solutions:\n * 1. child app respond to popstateEvent async -- router-event-delay\n * 2. child app will not respond to popstateEvent in some scenarios (history.state===null || history.state?__MICRO_APP_STATE__[appName])\n * NOTE 1:\n * 1. browser back/forward\n * 2. location.hash/search/pathname = xxx\n * 3. <a href=\"/#/xxx\">, <a href=\"/xxx\">\n * 4. history.back/go/forward\n * 5. history.pushState/replaceState\n *\n * NOTE2:\n * 1、react16 hash mode navigate by location.hash = xxx, history.state is always null, but react16 respond to popstateEvent sync\n * 2、multiple child apps may has problems\n */\n if (\n !isRouterModeCustom(appName) ||\n !globalEnv.rawWindow.history.state ||\n getMicroRouterInfoState(appName)\n ) {\n const container = appInstanceMap.get(appName)?.container\n macro(\n () => updateMicroLocationWithEvent(appName, getMicroPathFromURL(appName)),\n (container && getRootContainer(container))?.getRouterEventDelay() ?? 0\n )\n }\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 if (app?.sandBox) {\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/**\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 * Object.defineProperty(newPopStateEvent, 'type', {\n * value: 'popstate',\n * writable: true,\n * configurable: true,\n * enumerable: true,\n * })\n */\n /**\n * create PopStateEvent named popstate-appName with sub app state\n * TODO: feeling like there's something wrong, check carefully\n * In native mode, getMicroState(appName) return rawWindow.history.state when use microApp.router.push/replace or other scenes when state.__MICRO_APP_STATE__[appName] is null\n */\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 bindFunctionToRawTarget from '../bind_function'\nimport {\n isString,\n createURL,\n isPlainObject,\n isURL,\n assign,\n removeDomScope,\n isUndefined,\n isNull,\n} from '../../libs/utils'\nimport {\n setMicroPathToURL,\n setMicroState,\n getMicroState,\n getMicroRouterInfoState,\n getMicroPathFromURL,\n isEffectiveApp,\n isRouterModePure,\n isRouterModeSearch,\n isRouterModeState,\n isRouterModeCustom,\n} from './core'\nimport {\n dispatchNativeEvent,\n} from './event'\nimport {\n updateMicroLocation,\n} from './location'\nimport {\n getActiveApps,\n} from '../../micro_app'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} 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 rests[2] = isUndefined(rests[2]) || isNull(rests[2]) || ('' + rests[2] === '') ? microLocation.href : '' + 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], targetLocation),\n rests[1],\n )\n }\n if (targetFullPath !== microLocation.fullPath) {\n updateMicroLocation(appName, targetFullPath, microLocation)\n }\n appInstanceMap.get(appName)?.sandBox.updateIframeBase?.()\n }\n }\n\n const originalHistory = {\n pushState: getMicroHistoryMethod('pushState'),\n replaceState: getMicroHistoryMethod('replaceState'),\n }\n\n if (isIframeSandbox(appName)) {\n return assign({\n go (delta?: number) {\n return rawHistory.go(delta)\n }\n }, originalHistory) as MicroHistory\n }\n\n return new Proxy(rawHistory, {\n get (target: History, key: PropertyKey): HistoryProxyValue {\n if (key === 'pushState' || key === 'replaceState') {\n return originalHistory[key]\n } else if (key === 'state') {\n return getMicroState(appName)\n }\n return bindFunctionToRawTarget<History, HistoryProxyValue>(Reflect.get(target, key), target, 'HISTORY')\n },\n set (target: History, key: PropertyKey, value: unknown): boolean {\n if (key === 'pushState' || key === 'replaceState') {\n originalHistory[key] = value as CallableFunction\n } else {\n Reflect.set(target, key, value)\n }\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 // just search mode will dispatch native event\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 __MICRO_APP_STATE__ in history.state\n * Fix bug of missing __MICRO_APP_STATE__ 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?.__MICRO_APP_STATE__ &&\n (!isPlainObject(rests[0]) || !rests[0].__MICRO_APP_STATE__) &&\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 __MICRO_APP_STATE__: rawWindow.history.state.__MICRO_APP_STATE__,\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) || isRouterModeState(appName)) && !getMicroPathFromURL(appName)) {\n const app = appInstanceMap.get(appName)!\n attachRouteToBrowserURL(\n appName,\n setMicroPathToURL(appName, app.sandBox.proxyWindow.location),\n setMicroState(appName, getMicroState(appName), app.sandBox.proxyWindow.location),\n )\n }\n\n if (isRouterModeCustom(appName) && !getMicroRouterInfoState(appName)) {\n nativeHistoryNavigate(\n appName,\n 'replaceState',\n rawWindow.location.href,\n setMicroState(appName)\n )\n }\n\n // if (isRouterModeCustom(appName) || isRouterModeSearch(appName)) {\n /**\n * history.pushState/replaceState后主动触发子应用响应\n * 问题:子应用的卸载可能是异步的,而跳转的地址不一定在基础路径中,太快响应pushState可能会导致url地址被子应用改变或者子应用404,Promise太快卸载时出问题、setTimeout太慢keep-alive二次渲染后出问题\n * 1、history.pushState/replaceState执行后,子应用以异步的形式被主应用卸载,Promise响应时子应用还在,导致子应用跳转404后者浏览器url被子应用修改,产生异常\n * 2、keep-alive应用二次渲染时,由于setTimeout响应过慢,子应用在渲染后才接受到popstate事件,响应新的url,从而导致状态丢失\n * 3、同一个页面多个子应用,修改地址响应\n * 4、vue3跳转前会执行一次replace,有没有影响?\n */\n\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 __MICRO_APP_STATE__ 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 isRouterModeSearch,\n isRouterModePure,\n isRouterModeState,\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 targetLocation,\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 // pure mode will not call history.pushState/replaceState\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 // only search mode will dispatch PopStateEvent to browser\n if (!isRouterModeSearch(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、预渲染 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('导航失败,请确保子应用渲染后再调用此方法'))\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) || isRouterModeState(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), app.sandBox.proxyWindow.location as MicroLocation),\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","/* 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 setMicroState,\n getMicroState,\n isRouterModeCustom,\n isRouterModeNative,\n isRouterModeSearch,\n isRouterModePure,\n} from './core'\nimport {\n dispatchNativeEvent,\n updateMicroLocationWithEvent,\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 HIJACK_LOCATION_KEYS,\n} from '../../constants'\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 methodName = isRouterModePure(appName) ? 'replaceState' : methodName\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 will not reload browser\n * 2. if address is same and has hash, it will not add route stack\n */\n if (\n targetLocation.pathname === proxyLocation.pathname &&\n targetLocation.search === proxyLocation.search\n ) {\n let oldHref = null\n // NOTE: if pathname & search is same, it should record router info to history.state in pure mode\n if (targetLocation.hash !== proxyLocation.hash || isRouterModePure(appName)) {\n // search mode only\n if (setMicroPathResult.isAttach2Hash) {\n oldHref = rawLocation.href\n }\n // if router mode is pure and targetLocation.hash exist, it will not call nativeHistoryNavigate\n if (!isRouterModePure(appName) || !targetLocation.hash) {\n nativeHistoryNavigate(\n appName,\n methodName,\n setMicroPathResult.fullPath,\n !isRouterModeSearch(appName) ? setMicroState(appName, null, targetLocation) : null,\n )\n }\n }\n\n if (targetLocation.hash) {\n if (isRouterModeSearch(appName)) {\n dispatchNativeEvent(appName, false, oldHref)\n } else {\n updateMicroLocationWithEvent(appName, targetLocation.pathname + targetLocation.search + targetLocation.hash)\n }\n } else {\n reload()\n }\n return void 0\n }\n\n // when pathname or search change, simulate behavior of browser (reload) manually\n // TODO: state模式下pushState会带上上一个页面的state,会不会有问题,尤其是vue3,应不应该将主应用的state设置为null\n nativeHistoryNavigate(\n appName,\n methodName,\n setMicroPathResult.fullPath,\n !isRouterModeSearch(appName) ? setMicroState(appName, null, targetLocation) : null,\n )\n reload()\n return void 0\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 (\n targetLocation[key] === proxyLocation[key] || isRouterModePure(appName)\n )\n ? 'replaceState'\n : 'pushState',\n setMicroPathToURL(appName, targetLocation).fullPath,\n !isRouterModeSearch(appName) ? setMicroState(appName, null, targetLocation) : null,\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 /**\n * Special keys: host, hostname, port, protocol, origin, href\n * NOTE:\n * 1. In native mode this keys point to browser, in other mode this keys point to child app origin\n * 2. In iframe sandbox, iframe.src is base app address, so origin points to the browser by default, we need to replace it with child app origin\n * 3. In other modes, origin points to child app\n */\n if (HIJACK_LOCATION_KEYS.includes(key)) {\n if (isRouterModeNative(appName)) {\n return rawLocation[key]\n }\n if (isIframe) {\n return childStaticLocation![key]\n }\n }\n\n if (key === 'href') {\n if (isRouterModeNative(appName)) {\n return target[key].replace(target.origin, rawLocation.origin)\n }\n if (isIframe) {\n // 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 if (!isRouterModePure(appName)) {\n navigateWithNativeEvent(\n appName,\n 'pushState',\n setMicroPathToURL(appName, targetLocation),\n false,\n setMicroState(appName, null, targetLocation),\n )\n }\n if (!isRouterModeSearch(appName)) {\n updateMicroLocationWithEvent(appName, targetLocation.pathname + targetLocation.search + targetLocation.hash)\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 targetFullPath: 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(targetFullPath, 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\n /**\n * The native mode also base of history.state, and the modification of the browser url cannot be controlled. It is very likely that the browser url and __MICRO_APP_STATE__ are different.\n * Especially during init of child or forward and backward of browser, because vue-router@4 will actively modify the browser URL, the above situation often occurs\n * To solve this problem, after child app is initialized and responds to the popstateEvent, it is determined whether __MICRO_APP_STATE__ and the browser url are different. If they are different, the browser url will updated to the address of __MICRO_APP_STATE__\n * NOTE:\n * 1. If __MICRO_APP_STATE__ is different from the URL, then the operation of updating the URL is correct, otherwise there will be a problem of inconsistency between the URL and the rendered page\n * 2. When there are multiple child app in native mode, if one of them changes the URL address, the other one will not change __MICRO_APP_STATE__, and refresh browser will cause problems\n */\n const rawLocation = globalEnv.rawWindow.location\n if (\n isRouterModeCustom(appName) &&\n (targetFullPath !== rawLocation.pathname + rawLocation.search + rawLocation.hash) &&\n type !== 'prevent'\n ) {\n nativeHistoryNavigate(appName, 'replaceState', targetFullPath, globalEnv.rawWindow.history.state)\n }\n\n // update latest values of microLocation to `to`\n const to = createGuardLocation(appName, microLocation)\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 initRouterMode,\n isRouterModeCustom,\n isRouterModeSearch,\n} from './core'\nexport {\n patchHistory,\n releasePatchHistory,\n} from './history'\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 if (isRouterModePure(appName)) {\n removePathFromBrowser(appName)\n }\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(appName, null, microLocation),\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 // TODO: keep-router-state 功能太弱,是否可以增加优先级,或者去掉\n if (!keepRouteState && !isRouterModeCustom(appName)) {\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 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 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 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 // The methods defined by class are hung on the prototype, and enumerable is false by default\n MicroXMLHttpRequest.prototype && Object.defineProperty(MicroXMLHttpRequest.prototype, 'open', { enumerable: true })\n return MicroXMLHttpRequest\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 Func,\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 isFunction,\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(appName, url)\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 * 4. mount & unmount hook should delete in default mode when stop\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 this.clearHijackUmdHooks()\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 location: microAppWindow.location,\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 * 2. hijack umd hooks -- mount, unmount, micro-app-appName\n * @param container micro app container\n */\n public actionsBeforeExecScripts (container: Element | ShadowRoot, handleUmdHooks: Func): void {\n this.patchStaticElement(container)\n this.clearHijackUmdHooks = this.hijackUmdHooks(this.appName, this.microAppWindow, handleUmdHooks)\n }\n\n // hijack mount, unmount, micro-app-appName hook to microAppWindow\n private hijackUmdHooks (\n appName: string,\n microAppWindow: microAppWindowType,\n handleUmdHooks: Func,\n ): () => void {\n let mount: Func | null, unmount: Func | null, microAppLibrary: Record<string, unknown> | null\n rawDefineProperties(microAppWindow, {\n mount: {\n configurable: true,\n get: () => mount,\n set: (value) => {\n if (this.active && isFunction(value) && !mount) {\n handleUmdHooks(mount = value, unmount)\n }\n }\n },\n unmount: {\n configurable: true,\n get: () => unmount,\n set: (value) => {\n if (this.active && isFunction(value) && !unmount) {\n handleUmdHooks(mount, unmount = value)\n }\n }\n },\n [`micro-app-${appName}`]: {\n configurable: true,\n get: () => microAppLibrary,\n set: (value) => {\n if (this.active && isPlainObject(value) && !microAppLibrary) {\n microAppLibrary = value\n handleUmdHooks(microAppLibrary.mount, microAppLibrary.unmount)\n }\n }\n }\n })\n\n return () => {\n mount = unmount = microAppLibrary = null\n }\n }\n\n public setStaticAppState (state: string): void {\n this.microAppWindow.__MICRO_APP_STATE__ = state\n }\n}\n","\nexport const UN_PROXY_INSTANCEOF_KEYS = [\n 'Array'\n]\n\nexport const escape2RawWindowKeys = [\n 'getComputedStyle',\n // FIX ISSUE: https://github.com/jd-opensource/micro-app/issues/1292\n 'DOMParser',\n 'visualViewport',\n 'matchMedia',\n 'ResizeObserver',\n 'IntersectionObserver',\n]\n\nexport const escape2RawWindowRegExpKeys = [\n /animationFrame$/i,\n /mutationObserver$/i,\n /height$|width$/i,\n /offset$/i,\n /selection$/i,\n /^range/i,\n /^screen/i,\n /^scroll/i,\n /X$|Y$/,\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// hijack InstanceOf of iframe class\nexport const hijackInstanceOfWindowRegExpKeys = [\n /^((HTML|SVG)\\w*|MathML)?Element$/,\n /^(Node|Text|Attr|Comment|EventTarget|CharacterData|NamedNodeMap|ShadowRoot)$/,\n /^Document(Type|Fragment)?$/,\n /^(?!PopState).*Event$/,\n /^DataTransfer/\n]\n\n// proxy to shadowRoot or rawDocument (property)\nexport const proxy2RawDocOrShadowKeys = [\n 'childElementCount',\n 'children',\n 'firstElementChild',\n 'firstChild',\n 'lastElementChild',\n 'activeElement', // not for Element, just for document/shadowRoot\n 'fullscreenElement', // not for Element, just for document/shadowRoot\n 'pictureInPictureElement', // not for Element, just for document/shadowRoot\n 'pointerLockElement', // not for Element, just for document/shadowRoot\n 'styleSheets', // not for Element, just for document/shadowRoot\n]\n\n// proxy to shadowRoot or rawDocument (method)\nexport const proxy2RawDocOrShadowMethods = [\n 'append',\n 'contains',\n 'replaceChildren',\n 'createRange', // not for Element, just for document/shadowRoot\n 'getSelection', // not for Element, just for document/shadowRoot\n 'elementFromPoint', // not for Element, just for document/shadowRoot\n 'elementsFromPoint', // not for Element, just for document/shadowRoot\n 'getAnimations', // not for Element, just for document/shadowRoot\n]\n\n// proxy to rawDocument (property)\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// proxy to rawDocument (method)\nexport const proxy2RawDocumentMethods = [\n 'execCommand',\n 'createRange',\n 'exitFullscreen',\n 'exitPictureInPicture',\n 'getElementsByTagNameNS',\n 'hasFocus',\n 'prepend',\n]\n","\nimport { appInstanceMap } from '../create_app'\nimport { CompletionPath, getCurrentAppName } from '../libs/utils'\n\ninterface WorkerOptions {\n name?: string;\n type?: 'classic' | 'module';\n credentials?: 'omit' | 'same-origin' | 'include';\n}\n\nconst EXCLUDE_URL_PROTOCOLS = [\n 'blob:'\n]\n\ninterface WorkerInstance extends EventTarget {\n postMessage(message: any, transfer?: Transferable[]): void;\n terminate(): void;\n}\ninterface Worker {\n new(url: string | URL, options?: WorkerOptions): WorkerInstance;\n}\n\n// 重写 Worker 构造函数的类型\nconst originalWorker = window.Worker\n\nfunction isSameOrigin(url: string | URL): boolean {\n try {\n // 检查 URL 是否与当前页面在同一个源\n const parsedUrl = url instanceof URL ? url : new URL(url as string)\n if (EXCLUDE_URL_PROTOCOLS.includes(parsedUrl.protocol)) {\n return true\n }\n return (\n parsedUrl.protocol === window.location.protocol &&\n parsedUrl.hostname === window.location.hostname &&\n parsedUrl.port === window.location.port\n )\n } catch (error) {\n return false\n }\n}\n\nfunction urlFromScript(script: string) {\n let blob\n try {\n blob = new Blob([script], {\n type: 'application/javascript'\n })\n } catch (e) {\n const BlobBuilder =\n // @ts-ignore\n window.BlobBuilder ||\n // @ts-ignore\n window.WebKitBlobBuilder ||\n // @ts-ignore\n window.MozBlobBuilder ||\n // @ts-ignore\n window.MSBlobBuilder\n const blobBuilder = new BlobBuilder()\n blobBuilder.append(script)\n blob = blobBuilder.getBlob('application/javascript')\n }\n\n const URL = window.URL || window.webkitURL\n return URL.createObjectURL(blob)\n}\n\n// @ts-ignore\nconst WorkerProxy = new Proxy<Worker>(originalWorker, {\n construct(Target, args): WorkerInstance {\n let [scriptURL, options] = args\n options = options || {}\n const appName = getCurrentAppName()\n let url = scriptURL\n if (appName) {\n const app = appInstanceMap.get(appName)\n url = CompletionPath(scriptURL, app!.url)\n }\n\n if (url && !isSameOrigin(url)) {\n // 如果 scriptURL 是跨域的,使用 Blob URL 加载并执行 worker\n const script = `import \"${scriptURL}\";`\n const workerPath = urlFromScript(script)\n options.type = 'module'\n return new Target(workerPath, options) as WorkerInstance\n } else {\n // 如果 scriptURL 是同源的,直接使用原生的 Worker 构造函数\n return new Target(scriptURL, options) as WorkerInstance\n }\n },\n})\n\nexport default WorkerProxy\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 instanceOf,\n isConstructor,\n} from '../../libs/utils'\nimport {\n GLOBAL_KEY_TO_WINDOW,\n SCOPE_WINDOW_EVENT_OF_IFRAME,\n SCOPE_WINDOW_ON_EVENT_OF_IFRAME,\n} from '../../constants'\nimport {\n UN_PROXY_INSTANCEOF_KEYS,\n escape2RawWindowKeys,\n escape2RawWindowRegExpKeys,\n} from './special_key'\nimport WorkerProxy from '../../proxies/worker'\nimport microApp from '../../micro_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: IframeSandbox,\n): CommonEffectHook {\n patchWindowProperty(appName, microAppWindow, sandbox)\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 sandbox: IframeSandbox,\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 /**\n * In FireFox, iframe Element.prototype will point to native Element.prototype after insert to document\n * Rewrite all constructor's Symbol.hasInstance of iframeWindow\n * NOTE:\n * 1. native event instanceof iframe window.Event\n * 2. native node instanceof iframe window.Node\n * 3. native element instanceof iframe window.Element\n * 4. native url instanceof iframe window.URL\n * ...\n */\n if (\n isConstructor(microAppWindow[key]) &&\n key in rawWindow &&\n !UN_PROXY_INSTANCEOF_KEYS.includes(key) &&\n !microApp.options.excludeRewriteIframeConstructor?.includes(key)\n ) {\n rawDefineProperty(microAppWindow[key], Symbol.hasInstance, {\n configurable: true,\n enumerable: false,\n value (target: unknown): boolean {\n return instanceOf(target, rawWindow[key]) || instanceOf(target, microAppWindow[key])\n },\n })\n }\n\n return /^on/.test(key) && !SCOPE_WINDOW_ON_EVENT_OF_IFRAME.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 * In esmodule(vite) proxyWindow will not take effect,\n * escapeProperties should define to microAppWindow\n */\n sandbox.escapeProperties.forEach((key: PropertyKey) => {\n let rawValue = microAppWindow[key]\n rawDefineProperty(microAppWindow, key, {\n enumerable: true,\n configurable: true,\n get () {\n return rawValue ?? bindFunctionToRawTarget(rawWindow[key], rawWindow)\n },\n set (value: unknown) {\n rawValue = value\n }\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 Object.defineProperty(microAppWindow, 'Worker', {\n value: WorkerProxy,\n configurable: true,\n writable: true,\n })\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 === 'Worker') {\n return WorkerProxy\n }\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.get(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 // sandbox.escapeProperties will not set to rawWindow from rc.9\n Reflect.set(target, key, value)\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 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, rawDispatchEvent } = 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 /**\n * TODO: SCOPE_WINDOW_EVENT_OF_IFRAME的事件非常少,有可能导致问题\n * 1、一些未知的需要绑定到iframe的事件被错误的绑定到原生window上\n */\n let escapeSandboxEvent: Array<string> = []\n if (Array.isArray(microApp?.options?.escapeIframeWindowEvents)) {\n escapeSandboxEvent = microApp.options.escapeIframeWindowEvents\n }\n const scopeWindowEvent = SCOPE_WINDOW_EVENT_OF_IFRAME.filter(item => !escapeSandboxEvent.includes(item))\n return scopeWindowEvent.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 microAppWindow.dispatchEvent = function (event: Event): boolean {\n return rawDispatchEvent.call(getEventTarget(event?.type), event)\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 throttleDeferForIframeAppName,\n isWebComponentElement,\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'\nimport microApp from '../../micro_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}\nfunction getElementDocument(microDocument: Document, rawDocument: Document): Document {\n if (microApp?.options?.disableIframeRootDocument) {\n return rawDocument\n }\n return microDocument\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 let element = rawMicroCreateElement.call(getElementDocument(this, rawDocument), tagName, options)\n if (isWebComponentElement(element)) {\n element = rawMicroCreateElement.call(rawDocument, tagName, options)\n }\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(getElementDocument(this, rawDocument), namespaceURI, name, options)\n return updateElementInfo(element, appName)\n }\n\n microRootDocument.prototype.createTextNode = function createTextNode (data: string): Text {\n const element = rawMicroCreateTextNode.call(getElementDocument(this, rawDocument), data)\n return updateElementInfo<Text>(element, appName)\n }\n\n microRootDocument.prototype.createDocumentFragment = function createDocumentFragment (): DocumentFragment {\n const element = rawMicroCreateDocumentFragment.call(getElementDocument(this, rawDocument))\n return updateElementInfo(element, appName)\n }\n\n microRootDocument.prototype.createComment = function createComment (data: string): Comment {\n const element = rawMicroCreateComment.call(getElementDocument(this, rawDocument), data)\n return updateElementInfo<Comment>(element, appName)\n }\n\n function getBindTarget (target: Document): Document {\n /**\n * handler for:\n * 1. document.getElementsByTagName('head')[0].querySelector('script')\n * 2. document.querySelector('body').querySelectorAll('script')\n * ...\n */\n throttleDeferForIframeAppName(appName)\n // DOMParser.document !== microDocument\n return microDocument === target ? rawDocument : target\n }\n\n // query element👇\n function querySelector (this: Document, selectors: string): any {\n const _this = getBindTarget(this)\n if (selectors === 'body' && microApp?.options?.inheritBaseBody !== true) {\n return this.body\n }\n if (\n !selectors ||\n isUniqueElement(selectors) ||\n rawDocument !== _this\n ) {\n return rawMicroQuerySelector.call(_this, selectors)\n }\n\n /**\n * The child app cannot query the base element inside iframe\n * Same for querySelectorAll\n *\n * Scenes:\n * 1. vue-router@4.x --> createWebHistory(base?: string)\n * const baseEl = document.querySelector('base')\n * base = (baseEl && baseEl.getAttribute('href')) || '/'\n *\n * Issue: https://github.com/jd-opensource/micro-app/issues/1335\n */\n const result = appInstanceMap.get(appName)?.querySelector(selectors)\n return result || selectors === 'base' ? result : rawMicroQuerySelector.call(microDocument, selectors)\n }\n\n function querySelectorAll (this: Document, selectors: string): any {\n const _this = getBindTarget(this)\n if (\n !selectors ||\n isUniqueElement(selectors) ||\n rawDocument !== _this\n ) {\n return rawMicroQuerySelectorAll.call(_this, selectors)\n }\n\n const result = appInstanceMap.get(appName)?.querySelectorAll(selectors) ?? []\n return result.length || selectors === 'base' ? result : rawMicroQuerySelectorAll.call(microDocument, 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 = getBindTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementById.call(_this, key)\n }\n\n try {\n return querySelector.call(getElementDocument(this, rawDocument), `#${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 = getBindTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementsByClassName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(getElementDocument(this, rawDocument), `.${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 = getBindTarget(getElementDocument(this, rawDocument))\n if (\n isUniqueElement(key) ||\n isInvalidQuerySelectorKey(key)\n ) {\n return rawMicroGetElementsByTagName.call(_this, key)\n // just script, not base\n } else if (/^script$/i.test(key)) {\n return rawMicroGetElementsByTagName.call(microDocument, key)\n }\n\n try {\n return querySelectorAll.call(getElementDocument(this, rawDocument), 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 = getBindTarget(getElementDocument(this, rawDocument))\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementsByName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(getElementDocument(this, rawDocument), `[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 throttleDeferForIframeAppName(appName)\n if (tagName === 'body' && microApp?.options?.inheritBaseBody !== true) {\n return sandbox.options.container?.querySelector('micro-app-body') || rawDocument[tagName]\n }\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, rawDispatchEvent } = 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.dispatchEvent = function (event: Event): boolean {\n return rawDispatchEvent.call(getEventTarget(event?.type, this), event)\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 isDocumentFragment,\n isFunction,\n isBrowser,\n} from '../../libs/utils'\nimport {\n updateElementInfo,\n getIframeParentNodeDesc,\n} from '../adapter'\nimport microApp from '../../micro_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, appName)\n}\n\n/**\n * patch iframe Node/Element\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 rawRootNode = globalEnv.rawRootNode\n const rawDocument = globalEnv.rawDocument\n const microDocument = microAppWindow.document\n const microRootNode = microAppWindow.Node\n const microRootElement = microAppWindow.Element\n const microDocumentFragment = microAppWindow.DocumentFragment\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 rawMicroFragmentAppend = microDocumentFragment.prototype.append\n const rawMicroFragmentPrepend = microDocumentFragment.prototype.prepend\n const rawMicroInsertAdjacentElement = microRootElement.prototype.insertAdjacentElement\n const rawMicroCloneNode = microRootNode.prototype.cloneNode\n const rawInnerHTMLDesc = Object.getOwnPropertyDescriptor(microRootElement.prototype, 'innerHTML')!\n const rawParentNodeDesc = Object.getOwnPropertyDescriptor(microRootNode.prototype, 'parentNode')!\n const rawOwnerDocumentDesc = Object.getOwnPropertyDescriptor(microRootNode.prototype, 'ownerDocument')!\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.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 rawRootNode.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 rawRootNode.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 rawRootNode.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 rawRootNode.prototype.removeChild.call(getRawTarget(this), oldChild)\n }\n\n microDocumentFragment.prototype.append = 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 (isDocumentFragment(this) ? rawMicroFragmentAppend : rawMicroAppend).call(this, ...nodes)\n }\n return rawRootElement.prototype.append.call(getRawTarget(this), ...nodes)\n }\n\n microDocumentFragment.prototype.prepend = 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 (isDocumentFragment(this) ? rawMicroFragmentPrepend : 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 /**\n * Specific prototype properties:\n * 1. baseURI\n * 2. ownerDocument\n * 3. parentNode\n * 4. innerHTML\n */\n rawDefineProperty(microRootNode.prototype, 'baseURI', {\n configurable: true,\n enumerable: true,\n get () {\n return sandbox.proxyWindow.location.href\n },\n })\n\n rawDefineProperty(microRootNode.prototype, 'ownerDocument', {\n configurable: true,\n enumerable: true,\n get () {\n return this.__PURE_ELEMENT__ || this === microDocument\n ? rawOwnerDocumentDesc.get?.call(this)\n : microDocument\n },\n })\n\n // patch parentNode\n rawDefineProperty(microRootNode.prototype, 'parentNode', getIframeParentNodeDesc(\n appName,\n rawParentNodeDesc,\n ))\n\n microRootNode.prototype.getRootNode = function getRootNode (): Node {\n return microDocument\n // TODO: any case return document?\n // const rootNode = rawMicroGetRootNode.call(this, options)\n // if (rootNode === appInstanceMap.get(appName)?.container) return microDocument\n // return rootNode\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(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 // 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, appName: string): 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 /^micro-app(-\\S+)?/i.test(this.tagName) &&\n key === 'data' &&\n this.setAttribute !== microRootElement.prototype.setAttribute\n ) {\n this.setAttribute(key, value)\n } else {\n const aHrefResolver = microApp?.options?.aHrefResolver\n if (key === 'href' && /^a$/i.test(this.tagName) && typeof aHrefResolver === 'function') {\n // 试验性质:a 标签开放自定义补齐功能\n value = aHrefResolver(value, appName, url)\n } else if (\n ((key === 'src' || key === 'srcset') && /^(img|script|video|audio|source|embed)$/i.test(this.tagName)) ||\n (key === 'href' && /^(link|image)$/i.test(this.tagName)) ||\n // If it is the anchor tag,eg. <a href=\"#xxx\"/>, the path will not be completed\n (key === 'href' && /^(a)$/i.test(this.tagName) && !/^#/.test(value))\n ) {\n let _url = url\n if (isBrowser && key === 'href' && /^a$/i.test(this.tagName) && isFunction(microApp.options.excludeAssetFilter) && microApp.options.excludeAssetFilter(value)) {\n _url = document.baseURI\n }\n value = CompletionPath(value, _url)\n }\n rawMicroSetAttribute.call(this, key, value)\n }\n }\n\n const protoAttrList: Array<[HTMLElement, string]> = [\n [microAppWindow.HTMLImageElement.prototype, 'src'],\n [microAppWindow.HTMLScriptElement.prototype, 'src'],\n [microAppWindow.HTMLLinkElement.prototype, 'href'],\n [microAppWindow.SVGImageElement.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 Func,\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 rawDefineProperties,\n isFunction,\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\ninterface IOption {\n container: HTMLElement | ShadowRoot | null,\n [key: string]: any\n}\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 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 public options: IOption\n // reset mount, unmount when stop in default mode\n public clearHijackUmdHooks!: () => void\n\n constructor (appName: string, url: string, options: IOption) {\n this.appName = appName\n this.url = url\n this.options = options\n const rawLocation = globalEnv.rawWindow.location\n const browserHost = rawLocation.protocol + '//' + rawLocation.host\n\n this.deleteIframeElement = this.createIframeElement(appName, browserHost + rawLocation.pathname, options)\n this.microAppWindow = this.iframe!.contentWindow\n\n this.patchIframe(this.microAppWindow, (resolve: CallableFunction) => {\n // refresh\n this.microAppWindow = this.iframe!.contentWindow\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 options?: Record<string, any>\n ): () => void {\n this.iframe = pureCreateElement('iframe')\n\n const iframeAttrs: Record<string, string> = {\n ...options?.attrs,\n id: appName,\n src: microApp.options.iframeSrc || browserPath,\n style: 'display: none',\n 'powered-by': 'micro-app',\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 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 // sandbox.stop may exec before sandbox.start, e.g: iframe sandbox + default mode + remount\n if (!this.active) return\n\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.clearHijackUmdHooks()\n }\n\n if (--globalEnv.activeSandbox === 0) {\n releasePatchElementAndDocument()\n releasePatchHistory()\n }\n\n if (--IframeSandbox.activeCount === 0) {\n // TODO: Is there anything to do?\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 // Update the base.href when initial and each redirect\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 * 2. hijack umd hooks -- mount, unmount, micro-app-appName\n * @param container micro app container\n */\n public actionsBeforeExecScripts (container: Element | ShadowRoot, handleUmdHooks: Func): void {\n this.patchStaticElement(container)\n this.clearHijackUmdHooks = this.hijackUmdHooks(this.appName, this.microAppWindow, handleUmdHooks)\n }\n\n // hijack mount, unmount, micro-app-appName hook to microAppWindow\n private hijackUmdHooks (\n appName: string,\n microAppWindow: microAppWindowType,\n handleUmdHooks: Func,\n ): () => void {\n let mount: Func | null, unmount: Func | null, microAppLibrary: Record<string, unknown> | null\n rawDefineProperties(microAppWindow, {\n mount: {\n configurable: true,\n get: () => mount,\n set: (value) => {\n if (this.active && isFunction(value) && !mount) {\n handleUmdHooks(mount = value, unmount)\n }\n }\n },\n unmount: {\n configurable: true,\n get: () => unmount,\n set: (value) => {\n if (this.active && isFunction(value) && !unmount) {\n handleUmdHooks(mount, unmount = value)\n }\n }\n },\n [`micro-app-${appName}`]: {\n configurable: true,\n get: () => microAppLibrary,\n set: (value) => {\n if (this.active && isPlainObject(value) && !microAppLibrary) {\n microAppLibrary = value\n handleUmdHooks(microAppLibrary.mount, microAppLibrary.unmount)\n }\n }\n }\n })\n\n return () => {\n mount = unmount = microAppLibrary = null\n }\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 rawDefineProperties,\n} from '../../libs/utils'\nimport globalEnv from '../../libs/global_env'\n\nexport function patchRouter (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n browserHost: string,\n): MicroLocation {\n const rawHistory = globalEnv.rawWindow.history\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 // save history.replaceState, it will be used in updateMicroLocation\n microAppWindow.rawReplaceState = microHistory.replaceState\n // rewrite microAppWindow.history\n assign(microHistory, createMicroHistory(appName, microAppWindow.location))\n // scrollRestoration proxy to rawHistory\n rawDefineProperties(microHistory, {\n scrollRestoration: {\n configurable: true,\n enumerable: true,\n get () {\n return rawHistory.scrollRestoration\n },\n set (value: string) {\n rawHistory.scrollRestoration = value\n }\n }\n })\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 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 attrs?: Record<string, string>,\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 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 public attrs?: Record<string, string>\n public isReloading = false\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 attrs,\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 this.attrs = attrs\n // exec before getInlineModeState\n this.iframe = iframe ?? false\n this.inline = this.getInlineModeState(inline)\n this.isReloading = false\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 if (this.isUnmounted()) return\n if (!this.isPrefetch) {\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 // TODO: statechange 还是 state-change,保持一致\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 const nextAction = () => {\n // place inside of nextAction, make sure iframe ready\n this.setAppState(appStates.BEFORE_MOUNT)\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 * current this.container is <div prerender='true'></div>\n * set this.container to <micro-app></micro-app>\n * NOTE:\n * 1. must exec before this.sandBox.rebuildEffectSnapshot\n * 2. must exec before this.preRenderEvents?.forEach((cb) => cb())\n */\n this.container = this.cloneContainer(container, this.container, false)\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 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 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: 兼容shadowRoot的场景\n this.cloneContainer(this.container, this.source.html, !this.umdMode)\n\n this.sandBox?.start({\n umdMode: this.umdMode,\n baseroute,\n defaultPage,\n disablePatchRequest,\n })\n\n if (!this.umdMode) {\n // patch element info of html\n this.sandBox?.actionsBeforeExecScripts(this.container, (mount, unmount) => {\n if (!this.umdMode && !this.isUnmounted()) {\n this.umdHookMount = isFunction(mount) ? mount : null\n // umdHookUnmount can works in default mode, register by window.unmount\n this.umdHookUnmount = isFunction(unmount) ? unmount : null\n // if mount & unmount is function, the sub app is umd mode\n if (isFunction(this.umdHookMount) && isFunction(this.umdHookUnmount)) {\n this.sandBox?.markUmdMode(this.umdMode = true)\n try {\n // if appState is mounted, it means that isFinished is true and this.handleMounted has already been executed, just exec this.umdHookMount\n if (this.getAppState() === appStates.MOUNTED) {\n this.umdHookMount(microApp.getData(this.name, true))\n } else {\n this.handleMounted(this.umdHookMount(microApp.getData(this.name, true)))\n }\n } catch (e) {\n logError('An error occurred when mount \\n', this.name, e)\n }\n }\n }\n })\n\n // if all js are executed, param isFinished will be true\n execScripts(this, (isFinished: boolean) => {\n if (!this.umdMode && isFinished === true) {\n this.handleMounted()\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 when mount \\n', this.name, e)\n }\n }\n }\n }\n\n /**\n * Initialization of sandbox is async, especially iframe sandbox are macro tasks\n * when child apps switch quickly, we need to pay attention to the following points:\n * NOTE:\n * 1. unmount app before exec nextAction (especially: iframe sandbox + default mode + remount)\n * this.container is null, this.sandBox will not start\n * 2. remount app of note 1\n * 3. unmount app during exec js\n */\n // TODO: 可优化?\n this.sandBox ? this.sandBox.sandboxReady.then(() => !this.isUnmounted() && 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 const nextAction = () => this.actionsAfterMounted()\n if (isPromise(umdHookMountResult)) {\n umdHookMountResult\n .then(nextAction)\n .catch((e) => {\n logError('An error occurred in window.mount \\n', this.name, e)\n nextAction()\n })\n } else {\n nextAction()\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 actionsAfterMounted (): 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 // 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 * 2. this.container maybe null: Initialization of sandbox is async, child app may unmount before exec nextAction of mount\n * 3. unmount app when loading files (this.container is not null)\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 try {\n this.handleUnmounted(\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n this.umdHookUnmount?.(microApp.getData(this.name, true)),\n )\n } catch (e) {\n logError('An error occurred when unmount \\n', this.name, e)\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: boolean,\n clearData: boolean,\n keepRouteState: boolean,\n unmountcb?: CallableFunction,\n umdHookUnmountResult?: unknown,\n ): void {\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 const nextAction = () => this.actionsAfterUnmounted({\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\n .then(nextAction)\n .catch((e) => {\n logError('An error occurred in window.unmount \\n', this.name, e)\n nextAction()\n })\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 actionsAfterUnmounted ({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n }: UnmountParam): void {\n if (this.umdMode && this.container && !destroy) {\n this.cloneContainer(this.source.html, this.container as HTMLElement, false)\n }\n const shouldClearData = this.isReloading ? false : (clearData || destroy)\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: shouldClearData,\n })\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.isPrerender = false\n this.preRenderEvents = null\n this.setKeepAliveState(null)\n if (this.container) {\n this.container.innerHTML = ''\n this.container = null\n } else if (!this.umdMode) {\n /**\n * this.container is null means sandBox.start has not exec, so sandBox.stop won't exec either\n * we should remove iframeElement in default mode manually\n */\n this.sandBox?.deleteIframeElement?.()\n }\n // in iframe sandbox & default mode, delete the sandbox & iframeElement\n /**\n * TODO:\n * 1. with沙箱与iframe沙箱保持一致:with沙箱默认模式下删除 或者 iframe沙箱umd模式下保留\n * 2. 接1.0,this.sandBox置空,还需要注意后续app.sandBox相关操作,比如 scripts.ts --> app.iframe ? app.sandBox!.microBody : app.querySelector('micro-app-body'),如果是fiber或者预加载,会存在卸载后js还在处理的情况\n */\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 // 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,\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 /**\n * NOTE:\n * 1. this.container must set to container(micro-app element) before exec rebuildEffectSnapshot\n * ISSUE: https://github.com/jd-opensource/micro-app/issues/1115\n * 2. rebuildEffectSnapshot must exec before dispatch beforeshow event\n */\n const oldContainer = this.container\n this.container = container\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.cloneContainer(\n this.container,\n oldContainer,\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 // 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 // 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 target Accept cloned elements\n * @param origin Cloned element\n * @param deep deep clone or transfer dom\n */\n private cloneContainer <T extends HTMLElement | ShadowRoot | null> (\n target: T,\n origin: T,\n deep: boolean,\n ): T {\n // 在基座接受到afterhidden方法后立即执行unmount,彻底destroy应用时,因为unmount时同步执行,所以this.container为null后才执行cloneContainer\n if (origin && target) {\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 const iframeOption = {\n attrs: this.attrs,\n container: this.container\n }\n this.sandBox = this.iframe ? new IframeSandbox(this.name, this.url, iframeOption) : 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 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 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 isMicroAppHead,\n isNull,\n getIframeCurrentAppName,\n isDocumentFragment,\n isDocumentShadowRoot,\n isImageElement,\n isVideoElement,\n isAudioElement,\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 updateElementInfo,\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 targetNode target node\n * @param passiveNode second param of insertBefore and replaceChild\n */\nfunction invokePrototypeMethod(\n app: AppInterface,\n rawMethod: Func,\n parent: Node,\n targetNode: Node,\n passiveNode?: Node | null,\n): any {\n const hijackParent = getHijackParent(parent, targetNode, 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/jd-opensource/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(targetNode, 'parentNode')\n if ((!descriptor || descriptor.configurable) && !targetNode.__MICRO_APP_HAS_DPN__) {\n rawDefineProperties(targetNode, {\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(targetNode) &&\n rawMethod === globalEnv.rawAppendChild\n ) {\n fixReactHMRConflict(app)\n }\n\n /**\n * 1. If passiveNode exists, it must be insertBefore or replaceChild\n * 2. When removeChild, targetNode may not be in microAppHead or head\n * NOTE:\n * 1. If passiveNode not in hijackParent, insertBefore replaceChild will be degraded to appendChild\n * E.g: document.head.replaceChild(targetNode, document.scripts[0])\n * 2. If passiveNode 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(targetNode, document.head.childNodes[0])\n * ISSUE: https://github.com/jd-opensource/micro-app/issues/1071\n */\n if (passiveNode && !hijackParent.contains(passiveNode)) {\n if (rawMethod === globalEnv.rawInsertBefore && parent.contains(passiveNode)) {\n const indexOfParent = Array.from(parent.childNodes).indexOf(passiveNode as ChildNode)\n if (hijackParent.childNodes[indexOfParent]) {\n return invokeRawMethod(rawMethod, hijackParent, targetNode, hijackParent.childNodes[indexOfParent], app)\n }\n }\n return globalEnv.rawAppendChild.call(hijackParent, targetNode)\n } else if (rawMethod === globalEnv.rawRemoveChild && !hijackParent.contains(targetNode)) {\n if (parent.contains(targetNode)) {\n return rawMethod.call(targetNode.parentElement, targetNode)\n }\n return targetNode\n }\n\n return invokeRawMethod(rawMethod, hijackParent, targetNode, passiveNode, app)\n }\n\n return invokeRawMethod(rawMethod, parent, targetNode, passiveNode, app)\n}\n\n// head/body map to micro-app-head/micro-app-body\nfunction getHijackParent(\n parent: Node,\n targetNode: Node,\n app: AppInterface,\n): HTMLElement | null | undefined {\n if (app) {\n if (parent === document.head) {\n if (app.iframe && isScriptElement(targetNode)) {\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(targetNode)) {\n return app.sandBox.microBody\n }\n return app.querySelector<HTMLElement>('micro-app-body')\n }\n if (app.iframe && isScriptElement(targetNode)) {\n return app.sandBox.microBody\n }\n }\n return null\n}\n\nfunction invokeRawMethod(\n rawMethod: Func,\n parent: Node,\n targetNode: Node,\n passiveNode?: Node | null,\n app?: AppInterface,\n) {\n if (isPendMethod(rawMethod)) {\n /**\n * In iframe sandbox, script will pend to iframe.body, so we should reset rawMethod, because:\n * Element.prototype.append === DocumentFragment.prototype.append ==> false\n * Element.prototype.prepend === DocumentFragment.prototype.prepend ==> false\n */\n if (app?.iframe && isScriptElement(targetNode)) {\n if (rawMethod === globalEnv.rawFragmentAppend) {\n rawMethod = globalEnv.rawAppend\n } else if (rawMethod === globalEnv.rawFragmentPrepend) {\n rawMethod = globalEnv.rawPrepend\n }\n }\n return rawMethod.call(parent, targetNode)\n }\n\n return rawMethod.call(parent, targetNode, passiveNode)\n}\n\nfunction isPendMethod(method: CallableFunction) {\n return (\n method === globalEnv.rawAppend ||\n method === globalEnv.rawPrepend ||\n method === globalEnv.rawFragmentAppend ||\n method === globalEnv.rawFragmentPrepend\n )\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|image)$/i.test(newChild.tagName) && newChild.hasAttribute('href')) ||\n // If it is the anchor tag,eg. <a href=\"#xxx\"/>, the path will not be completed\n (/^(a)$/i.test(newChild.tagName) && newChild.hasAttribute('href') && !/^#/.test(newChild.getAttribute('href') || ''))\n ) {\n const aHrefResolver = microApp?.options?.aHrefResolver\n const hrefValue = newChild.getAttribute('href')!\n let nextHrefValue\n if ((/^(a)$/i.test(newChild.tagName) && typeof aHrefResolver === 'function')) {\n nextHrefValue = aHrefResolver(hrefValue, app.name, app.url)\n } else {\n nextHrefValue = CompletionPath(hrefValue, app.url)\n }\n globalEnv.rawSetAttribute.call(newChild, 'href', nextHrefValue)\n }\n }\n}\n\n/**\n * method of handle new node\n * @param parent parent node\n * @param newChild new node\n * @param passiveNode passive node\n * @param rawMethod method\n */\nfunction commonElementHandler(\n parent: Node,\n newChild: Node,\n passiveNode: 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 updateElementInfo(newChild, newChild.__MICRO_APP_NAME__ || currentAppName)\n const app = appInstanceMap.get(newChild.__MICRO_APP_NAME__!)\n if (app?.container) {\n if (isStyleElement(newChild)) {\n parent.getRootNode() instanceof ShadowRoot && newChild.setAttribute('ignore', 'true')\n }\n completePathDynamic(app, newChild)\n return invokePrototypeMethod(\n app,\n rawMethod,\n parent,\n handleNewNode(newChild, app),\n passiveNode && getMappingNode(passiveNode),\n )\n }\n }\n\n return invokeRawMethod(rawMethod, parent, newChild, passiveNode)\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 const rawDocumentFragment = globalEnv.rawDocumentFragment\n\n // prototype methods of add element👇\n rawRootNode.prototype.appendChild = function appendChild<T extends Node>(newChild: T): T {\n return commonElementHandler(this, newChild, null, globalEnv.rawAppendChild)\n }\n\n rawRootNode.prototype.insertBefore = function insertBefore<T extends Node>(newChild: T, refChild: Node | null): T {\n return commonElementHandler(this, newChild, refChild, globalEnv.rawInsertBefore)\n }\n\n rawRootNode.prototype.replaceChild = function replaceChild<T extends Node>(newChild: Node, oldChild: T): T {\n return commonElementHandler(this, newChild, oldChild, globalEnv.rawReplaceChild)\n }\n\n // prototype methods of delete element👇\n rawRootNode.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 rawDocumentFragment.prototype.append = 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(\n this,\n markElement(node as Node),\n null,\n isDocumentFragment(this) ? globalEnv.rawFragmentAppend : globalEnv.rawAppend,\n )\n i++\n }\n }\n\n rawDocumentFragment.prototype.prepend = rawRootElement.prototype.prepend = function prepend(...nodes: (Node | string)[]): void {\n let i = nodes.length\n let target = globalEnv.rawPrepend\n if (isDocumentFragment(this) || isDocumentShadowRoot(this)) {\n target = globalEnv.rawFragmentPrepend\n }\n\n while (i > 0) {\n let node = nodes[i - 1]\n node = isNode(node) ? node : globalEnv.rawCreateTextNode.call(globalEnv.rawDocument, node)\n commonElementHandler(\n this,\n markElement(node as Node),\n null,\n target,\n )\n i--\n }\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 /**\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 getElementQueryTarget(targetNode: Node): Node | null {\n const currentAppName = getIframeCurrentAppName() || getCurrentAppName()\n if ((targetNode === document.body || targetNode === document.head) && currentAppName) {\n const app = appInstanceMap.get(currentAppName)\n if (app?.container) {\n if (targetNode === document.body) {\n return app.querySelector<HTMLElement>('micro-app-body')\n } else if (targetNode === document.head) {\n return app.querySelector<HTMLElement>('micro-app-head')\n }\n }\n }\n return targetNode\n }\n\n /**\n * In iframe sandbox, script will render to iframe instead of micro-app-body\n * So when query elements, we need to search both micro-app and iframe\n * @param isEmpty get empty result\n * @param targetNode targetNode element\n * @param result origin result\n * @param selectors selectors\n * @param methodName querySelector or querySelectorAll\n */\n function getElementQueryResult<T>(\n isEmpty: boolean,\n targetNode: Node,\n result: T,\n selectors: string,\n methodName: string,\n ): T {\n if (isEmpty) {\n const currentAppName = getIframeCurrentAppName() || getCurrentAppName()\n if (currentAppName && isIframeSandbox(currentAppName)) {\n const app = appInstanceMap.get(currentAppName)!\n if (isMicroAppHead(targetNode)) {\n return app.sandBox.microHead[methodName](selectors)\n }\n if (isMicroAppBody(targetNode)) {\n return app.sandBox.microBody[methodName](selectors)\n }\n }\n }\n return result\n }\n\n rawRootElement.prototype.querySelector = function querySelector(selectors: string): Node | null {\n const _this = getElementQueryTarget(this) ?? this\n const result = globalEnv.rawElementQuerySelector.call(_this, selectors)\n return getElementQueryResult<Node | null>(\n isNull(result) && _this !== this,\n _this,\n result,\n selectors,\n 'querySelector',\n )\n }\n\n rawRootElement.prototype.querySelectorAll = function querySelectorAll(selectors: string): NodeListOf<Node> {\n const _this = getElementQueryTarget(this) ?? this\n const result = globalEnv.rawElementQuerySelectorAll.call(_this, selectors)\n return getElementQueryResult<NodeListOf<Node>>(\n !result.length && _this !== this,\n _this,\n result,\n selectors,\n 'querySelectorAll',\n )\n }\n\n // rewrite setAttribute, complete resource address\n rawRootElement.prototype.setAttribute = function setAttribute(key: string, value: any): void {\n if (\n /^micro-app(-\\S+)?/i.test(this.tagName) &&\n key === 'data' &&\n this.setAttribute !== rawRootElement.prototype.setAttribute\n ) {\n this.setAttribute(key, value)\n } else {\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|image)$/i.test(this.tagName)) ||\n // If it is the anchor tag,eg. <a href=\"#xxx\"/>, the path will not be completed\n (key === 'href' && /^(a)$/i.test(this.tagName) && !/^#/.test(value))\n )\n\n ) {\n const app = appInstanceMap.get(appName)\n const aHrefResolver = microApp?.options?.aHrefResolver\n if (key === 'href' && /^a$/i.test(this.tagName) && typeof aHrefResolver === 'function') {\n value = aHrefResolver(value, appName, app!.url)\n } else {\n value = CompletionPath(value, app!.url)\n }\n }\n globalEnv.rawSetAttribute.call(this, key, value)\n if (isImageElement(this) || isVideoElement(this) || isAudioElement(this)) {\n let includeCrossOrigin = false\n if (microApp?.options?.includeCrossOrigin && isFunction(microApp.options.includeCrossOrigin)) {\n includeCrossOrigin = microApp.options.includeCrossOrigin(value)\n }\n // @ts-ignore\n includeCrossOrigin && (node.crossOrigin = 'anonymous')\n }\n }\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 = this.__MICRO_APP_NAME__ || 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(rawRootNode.prototype, 'parentNode', {\n configurable: true,\n enumerable: true,\n get() {\n /**\n * hijack parentNode of html for with sandbox\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 = getIframeCurrentAppName() || getCurrentAppName()\n if (currentAppName && this === globalEnv.rawDocument.firstElementChild) {\n const microDocument = appInstanceMap.get(currentAppName)?.sandBox?.proxyWindow?.document\n if (microDocument) return microDocument\n }\n // NOTE: run after hijack html.parentNode\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 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 = this.__MICRO_APP_NAME__ || getIframeCurrentAppName() || getCurrentAppName()\n Array.from(this.children).forEach((child) => {\n if (isElement(child) && currentAppName) {\n updateElementInfo(child, currentAppName)\n }\n })\n }\n })\n\n // patch cloneNode\n rawRootNode.prototype.cloneNode = function cloneNode(deep?: boolean): Node {\n const clonedNode = globalEnv.rawCloneNode.call(this, deep)\n return updateElementInfo(clonedNode, this.__MICRO_APP_NAME__)\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 return updateElementInfo(element, getCurrentAppName())\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/jd-opensource/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(this: Document, 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(this: Document, 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(this: Document, 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(this: Document, 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 rawRootNode.prototype.appendChild = globalEnv.rawAppendChild\n rawRootNode.prototype.insertBefore = globalEnv.rawInsertBefore\n rawRootNode.prototype.replaceChild = globalEnv.rawReplaceChild\n rawRootNode.prototype.removeChild = globalEnv.rawRemoveChild\n rawRootNode.prototype.cloneNode = globalEnv.rawCloneNode\n rawRootElement.prototype.append = globalEnv.rawAppend\n rawRootElement.prototype.prepend = globalEnv.rawPrepend\n rawRootElement.prototype.querySelector = globalEnv.rawElementQuerySelector\n rawRootElement.prototype.querySelectorAll = globalEnv.rawElementQuerySelectorAll\n rawRootElement.prototype.setAttribute = globalEnv.rawSetAttribute\n rawDefineProperty(rawRootNode.prototype, 'parentNode', globalEnv.rawParentNodeDesc)\n rawDefineProperty(rawRootElement.prototype, 'innerHTML', globalEnv.rawInnerHTMLDesc)\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 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'\nimport {\n updateElementInfo,\n} from '../sandbox/adapter'\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 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: any\n rawDocument: any\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 const rawDocumentFragment = rawWindow.DocumentFragment\n\n // save patch raw methods, pay attention to this binding\n const rawAppendChild = rawRootNode.prototype.appendChild\n const rawInsertBefore = rawRootNode.prototype.insertBefore\n const rawReplaceChild = rawRootNode.prototype.replaceChild\n const rawRemoveChild = rawRootNode.prototype.removeChild\n const rawSetAttribute = rawRootElement.prototype.setAttribute\n const rawAppend = rawRootElement.prototype.append\n const rawPrepend = rawRootElement.prototype.prepend\n const rawFragmentAppend = rawDocumentFragment.prototype.append\n const rawFragmentPrepend = rawDocumentFragment.prototype.prepend\n const rawCloneNode = rawRootNode.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 // TODO: 将ImageProxy移出去\n const ImageProxy = new Proxy(rawWindow.Image, {\n construct (Target, args): HTMLImageElement {\n return updateElementInfo(new Target(...args), getCurrentAppName())\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 rawDocumentFragment,\n\n // source/patch\n rawSetAttribute,\n rawAppendChild,\n rawInsertBefore,\n rawReplaceChild,\n rawRemoveChild,\n rawAppend,\n rawPrepend,\n rawFragmentAppend,\n rawFragmentPrepend,\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 MicroAppElementInterface,\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} 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 initRouterMode,\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 HTMLElement implements MicroAppElementInterface {\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 private _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 /**\n * In FireFox, iframe Node.prototype will point to native Node.prototype after insert to document\n * If <micro-app>.prototype is not MicroAppElement.prototype, we should reset it\n */\n if (Object.getPrototypeOf(this) !== MicroAppElement.prototype) {\n Object.setPrototypeOf(this, MicroAppElement.prototype)\n }\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)\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)\n )\n ) {\n const formatNewName = formatAppName(newVal)\n\n if (!formatNewName) {\n return logError(`Invalid attribute name ${newVal}`, this.appName)\n }\n\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 attrs: Record<string, string> = {}\n Array.prototype.slice.call(this.attributes).forEach(({ name, value }: Attr) => {\n if (name.startsWith('data-')) {\n attrs[name] = value\n }\n })\n\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 attrs\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/jd-opensource/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 delete this.__MICRO_APP_NAME__\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 // TODO: 新版本路由系统要重新兼容ssr\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 initRouterMode(\n this.getAttribute('router-mode'),\n // is micro-app element set disable-memory-router, like <micro-app disable-memory-router></micro-app>\n // or <micro-app disable-memory-router='false'></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 * get delay time of router event\n * @returns delay time\n */\n public getRouterEventDelay (): number {\n let delay = parseInt(this.getAttribute('router-event-delay') as string)\n if (isNaN(delay)) {\n delay = parseInt((isFunction(microApp.options['router-event-delay']) ? microApp.options['router-event-delay'](this.appName) : microApp.options['router-event-delay']) as unknown as string)\n }\n return !isNaN(delay) ? delay : 0\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 set appName(value: string) {\n if (value !== this._appName) {\n microApp.changeEventAppName(value, this._appName)\n this._appName = value\n }\n }\n\n get appName(): string {\n return this._appName\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 window.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 isTargetExtension,\n} from './libs/utils'\nimport {\n fetchSource,\n} from './source/fetch'\nimport {\n initRouterMode,\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 * 如果要保留setTimeout,则需要考虑清空定时器的情况\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: initRouterMode(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) && isTargetExtension(path, 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 { 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 when unmountApp`)\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 const currentData = microApp.getData(appName)\n app.isReloading = true\n rootContainer.reload(destroy).then(() => {\n if (currentData) {\n microApp.setData(appName, currentData)\n }\n app.isReloading = false\n resolve(true)\n })\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 when reload app`)\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\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 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 (window.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","isPromise","isConstructor","targetStr","constructor","getOwnPropertyNames","length","test","isURL","URL","href","isElement","Element","tagName","isNode","Node","nodeType","isStyleElement","isScriptElement","isDocumentFragment","isMicroAppBody","toUpperCase","isTargetExtension","path","suffix","createURL","pathname","split","pop","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","Location","base","addProtocol","url","startsWith","location","protocol","formatAppURL","origin","search","port","host","rawWindow","newOrigin","log","fullPath","e","formatAppName","name","replace","getEffectivePath","pathArr","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","currentAppName","setCurrentAppName","getCurrentAppName","throttleDeferForSetAppName","getPreventSetState","iframeCurrentAppName","setIframeCurrentAppName","getIframeCurrentAppName","throttleDeferForIframeAppName","preventSetState","removeDomScope","force","pureCreateElement","options","element","rawDocument","document","createElement","__MICRO_APP_NAME__","__PURE_ELEMENT__","isInvalidQuerySelectorKey","key","isUniqueElement","getRootContainer","ShadowRoot","isShadowRoot","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","instanceOf","instance","proto","getPrototypeOf","formatEventList","formatEventType","type","dispatchLifecyclesEvent","lifecycleName","detail","container","event","CustomEvent","currentTarget","get","formatEventInfo","microApp","lifeCycles","dispatchEvent","dispatchCustomEventToMicroApp","app","eventName","sandBox","microAppWindow","fetchSource","fetch","text","HTMLLoader","getInstance","this","run","htmlUrl","ssrUrl","cache","htmlStr","onerror","Error","formatHTML","onLoadError","processHtml","plugins","match","code","mergedPlugins","modules","preCode","plugin","rootSelectorREG","bodySelectorREG","CSSParser","createMatcherForRuleWithChildRule","createMatcherForNoneBraceAtRule","exec","cssText","prefix","linkPath","matchRules","decodeURIComponent","reset","scopecssDisable","scopecssDisableNextLine","scopecssDisableSelectors","matchLeadingSpaces","matchComments","charAt","matchAtRule","matchStyleRule","selectors","formatSelector","recordResult","styleDeclarations","printError","skip","m","commonMatch","attributeValues","p1","p2","offset","mock","_","separator","selector","matchOpenBrace","matchAllDeclarations","matchCloseBrace","nesting","cssValue","all","$1","getLinkFileDir","keyframesRule","mediaRule","customMediaRule","supportsRule","importRule","charsetRule","namespaceRule","containerRule","documentRule","pageRule","hostRule","fontFaceRule","layerRule","keyframeRule","r","valList","commonHandlerForAtRuleWithSelfRule","reg","RegExp","matchComment","commentText","rule","matchArray","matchStr","strFragment","encodeURIComponent","reason","filename","parseError","commonAction","styleElement","__MICRO_APP_HAS_SCOPED__","parser","textContent","scopedCSS","scopecss","createPrefix","escapeRegExp","regStr","observer","MutationObserver","escapedPrefix","isPrefixed","disconnect","observe","childList","characterData","hasAttribute","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","GLOBAL_CACHED_KEY","PREFETCH_LEVEL","ROUTER_MODE_STATE","DEFAULT_ROUTER_MODE","ROUTER_MODE_NATIVE","ROUTER_MODE_NATIVE_SCOPE","ROUTER_MODE_PURE","ROUTER_MODE_LIST","BASE_SCOPE_WINDOW_EVENT","SCOPE_WINDOW_EVENT_OF_WITH","SCOPE_WINDOW_EVENT_OF_IFRAME","concat","BASE_SCOPE_WINDOW_ON_EVENT","SCOPE_WINDOW_ON_EVENT_OF_WITH","SCOPE_WINDOW_ON_EVENT_OF_IFRAME","SCOPE_DOCUMENT_EVENT","SCOPE_DOCUMENT_ON_EVENT","GLOBAL_KEY_TO_WINDOW","RAW_GLOBAL_TARGET","HIJACK_LOCATION_KEYS","scriptTypes","isTypeModule","scriptInfo","module","useSandbox","iframe","isInlineMode","inline","isSpecialScript","getEffectWindow","getParsedFunction","currentCode","parsedFunction","getExistParseResult","code2Function","getUniqueNonceSrc","nonceStr","random","substr","isWrapInSandBox","getSandboxType","extractScriptElement","src","checkExcludeUrl","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","throwError","excludeRunScriptFilter","newCode","processCode","usePlugins","configs","config","loader","flatBodyChildren","body","fiberStyleTasks","getElementsByTagName","dom","parentElement","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","changeEventAppName","newAppName","oldAppName","newEventName","oldEventName","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","BaseSandbox","staticScopeProperties","injectReactHMRProperty","CustomWindow","patchElementTree","children","childNodes","child","updateElementInfo","node","props","hrefDescriptor","getOwnPropertyDescriptor","hrefConfigurable","setAttribute","isIframeSandbox","ownerDocument","getIframeParentNodeDesc","rawParentNodeDesc","getRootNode","parentNodeDesc","customParent","getRootElementParentNode","inheritBaseBody","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","setPrototypeOf","createMicroDocument","Document","patchWindow","filter","patchWindowProperty","descriptorTargetMap","scopeProperties","rawWindowScopeKeyList","injectedKeys","descriptor","escapeProperties","staticEscapeProperties","escapeKeys","ownKeys","create","deleteProperty","createProxyWindow","intervalIdMap","timeoutIdMap","rawDispatchEvent","rawSetInterval","rawSetTimeout","rawClearInterval","rawClearTimeout","getEventTarget","setInterval","timeout","intervalId","setTimeoutHander","timeoutId","handlerWithCleanup","clearInterval","clearTimeout","clearTimer","patchWindowEffect","setMicroState","microState","targetLocation","rawState","history","state","additionalState","__MICRO_APP_STATE__","hash","mode","getRouterMode","removeMicroState","getMicroState","getMicroRouterInfoState","ENC_AD_RE","ENC_EQ_RE","DEC_AD_RE","DEC_EQ_RE","encodeMicroPath","commonDecode","decodeMicroPath","decPath","formatQueryAppName","getMicroPathFromURL","rawLocation","isRouterModeSearch","getQueryObjectFromURL","microPath","hashQuery","searchQuery","isRouterModeCustom","setMicroPathToURL","targetFullPath","isAttach2Hash","encodedMicroPath","baseHash","isRouterModeState","isRouterModePure","isEffectiveApp","routerMode","isRouterModeNative","isRouterModeNativeScope","initRouterMode","inlineDisableMemoryRouter","addHistoryListener","popStateHandler","getActiveApps","excludeHiddenApp","excludePreRender","onlyForBrowser","delay","macro","updateMicroLocationWithEvent","getRouterEventDelay","isHashChange","oldHref","oldHash","updateMicroLocation","newPopStateEvent","PopStateEvent","onpopstate","dispatchPopStateEventToMicroApp","newHashChangeEvent","HashChangeEvent","newURL","oldURL","onhashchange","dispatchHashChangeEventToMicroApp","dispatchNativeEvent","dispatchNativePopStateEvent","dispatchNativeHashChangeEvent","createMicroHistory","microLocation","rawHistory","getMicroHistoryMethod","methodName","rests","navigateWithNativeEvent","updateIframeBase","originalHistory","pushState","replaceState","go","delta","nativeHistoryNavigate","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","back","forward","beforeEach","afterEach","attachToURL","attachAllToURL","includeHiddenApp","includePreRender","defaultPageRecord","useMapRecord","setDefaultPage","removeDefaultPage","getDefaultPage","createDefaultPageApi","baseRouterProxy","setBaseAppRouter","baseRouter","getBaseAppRouter","createBaseRouterApi","createRouterApi","guardLocationKeys","createMicroLocation","childStaticLocation","browserHost","childHost","isIframe","withLocation","getTarget","commonHandler","proxyLocation","setMicroPathResult","reload","handleForPathNameAndSearch","targetPath","createLocationMethod","locationMethodName","forcedReload","createGuardLocation","guardLocation","oAssign","newLocation","targetHref","initRouteStateWithURL","defaultPage","removePathFromBrowser","updateBrowserURLWithLocation","autoTriggerNavigationGuard","clearRouteStateFromURL","keepRouteState","hashQueryStr","Number","Boolean","searchQueryStr","removeMicroPathFromURL","createMicroFetch","rawFetch","input","init","createMicroXMLHttpRequest","rawXMLHttpRequest","XMLHttpRequest","MicroXMLHttpRequest","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","clearHijackUmdHooks","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","actionsBeforeExecScripts","handleUmdHooks","hijackUmdHooks","mount","unmount","microAppLibrary","setStaticAppState","UN_PROXY_INSTANCEOF_KEYS","escape2RawWindowKeys","escape2RawWindowRegExpKeys","uniqueDocumentElement","proxy2RawDocOrShadowKeys","proxy2RawDocOrShadowMethods","proxy2RawDocumentKeys","proxy2RawDocumentMethods","EXCLUDE_URL_PROTOCOLS","originalWorker","Worker","WorkerProxy","construct","Target","scriptURL","parsedUrl","hostname","isSameOrigin","workerPath","blob","Blob","blobBuilder","BlobBuilder","WebKitBlobBuilder","MozBlobBuilder","MSBlobBuilder","append","getBlob","webkitURL","createObjectURL","urlFromScript","excludeRewriteIframeConstructor","rawValue","customProperties","escapeSandboxEvent","escapeIframeWindowEvents","microRootDocument","microDocument","rawMicroCreateElement","rawMicroCreateElementNS","rawMicroCreateTextNode","createTextNode","rawMicroCreateDocumentFragment","createDocumentFragment","rawMicroCreateComment","rawMicroQuerySelector","rawMicroQuerySelectorAll","querySelectorAll","rawMicroGetElementById","getElementById","rawMicroGetElementsByClassName","getElementsByClassName","rawMicroGetElementsByTagName","rawMicroGetElementsByName","getElementsByName","rawMicroElementFromPoint","elementFromPoint","rawMicroCaretRangeFromPoint","caretRangeFromPoint","getBindTarget","_this","x","y","range","getElementDocument","isWebComponentElement","patchDocumentPrototype","getCommonDescriptor","getter","createDescriptors","documentElement","scrollingElement","desc","patchDocumentProperty","bindTarget","createSetterHandler","__MICRO_APP_BOUND_FUNCTION__","patchDocumentEffect","disableIframeRootDocument","patchElement","rawRootElement","rawRootNode","microRootNode","microRootElement","microDocumentFragment","DocumentFragment","rawMicroAppendChild","rawMicroInsertBefore","insertBefore","rawMicroReplaceChild","rawMicroRemoveChild","rawMicroAppend","rawMicroPrepend","prepend","rawMicroFragmentAppend","rawMicroFragmentPrepend","rawMicroInsertAdjacentElement","insertAdjacentElement","rawMicroCloneNode","cloneNode","rawInnerHTMLDesc","rawOwnerDocumentDesc","isPureNode","isBaseElement","getRawTarget","microHead","head","oldChild","contains","nodes","hasPureNode","where","deep","elementImage","patchIframeNode","rawMicroSetAttribute","aHrefResolver","_url","excludeAssetFilter","protoAttrList","HTMLImageElement","HTMLScriptElement","HTMLLinkElement","SVGImageElement","patchIframeAttribute","IframeSandbox","baseElement","deleteIframeElement","createIframeElement","contentWindow","patchIframe","createIframeTemplate","childFullPath","scrollRestoration","browserPath","iframeAttrs","id","iframeSrc","style","createIframeBase","oldMicroDocument","iframeLocationReady","$dom","firstChild","clearDOM","innerHTML","CreateApp","CREATED","getInlineModeState","isReloading","loadSourceCode","createSandbox","setAppState","LOADING","loadSourceLevel","isUnmounted","LOAD_FAILED","appState","nextAction","BEFORE_MOUNT","cloneContainer","preRenderEvents","dispatchBeforeMount","BEFOREMOUNT","MOUNTING","handleMounted","umdHookMount","umdHookUnmount","getAppState","MOUNTED","initHook","deferScriptPromise","deferScriptInfo","errorCount","execScripts","umdHookMountResult","dispatchAction","actionsAfterMounted","getMicroAppGlobalHook","ONMOUNT","isHidden","unmountcb","UNMOUNT","handleUnmounted","umdHookUnmountResult","ONUNMOUNT","actionsAfterUnmounted","shouldClearData","clearOptions","setKeepAliveState","actionsForCompletelyDestroy","hiddenKeepAliveApp","KEEP_ALIVE_HIDDEN","AFTERHIDDEN","showKeepAliveApp","oldContainer","BEFORESHOW","KEEP_ALIVE_SHOW","AFTERSHOW","ERROR","htmlString","DOMParser","parseFromString","iframeOption","keepAliveState","getKeepAliveState","rawElementQuerySelectorAll","dynamicElementInMicroAppMap","WeakMap","getMappingNode","handleNewNode","linkReplaceComment","replaceStyle","originLink","handleDynamicLink","formatDynamicLink","originScript","dispatchScriptOnLoadEvent","runDynamicScript","runDynamicRemoteScript","runDynamicInlineScript","invokePrototypeMethod","rawMethod","targetNode","passiveNode","hijackParent","getHijackParent","rawRemoveChild","__MICRO_APP_HAS_DPN__","rawInsertBefore","indexOfParent","invokeRawMethod","rawAppendChild","rawAppend","rawPrepend","rawFragmentAppend","rawFragmentPrepend","commonElementHandler","newChild","hrefValue","nextHrefValue","completePathDynamic","isProxyDocument","rawQuerySelector","rawQuerySelectorAll","markElement","rawCreateDocumentFragment","rawCreateComment","rawGetElementById","rawGetElementsByClassName","rawGetElementsByTagName","rawGetElementsByName","rawDocumentFragment","getElementQueryTarget","getElementQueryResult","isEmpty","refChild","rawReplaceChild","rawCreateTextNode","isDocumentShadowRoot","processedEle","realParent","rawInsertAdjacentElement","isVideoElement","isAudioElement","includeCrossOrigin","crossOrigin","firstElementChild","rawCloneNode","releasePatchDocument","hasRejectMicroAppStyle","initGlobalEnv","rawRootEventTarget","EventTarget","__MICRO_APP_BASE_APPLICATION__","rejectMicroAppStyle","defineElement","MicroAppElement","HTMLElement","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","isNaN","_appName","publicPath","baseRoute","customElements","define","preFetch","apps","delayTime","prefetchDelay","preFetchAction","onLine","disableScopecss","disableSandbox","level","oldOnload","oldOnLoadError","onLoadParam","preFetchInSerial","fetchGlobalResources","resources","sourceHandler","effectiveResource","activeApps","getAllApps","unmountApp","clearAliveState","unmountHandler","afterhiddenHandler","destroyAttrValue","destoryAttrValue","removeAttribute","keepAliveAttrValue","clearDataAttrValue","unmountAllApps","rootContainer","currentData","renderApp","microAppElement","lifeCycleConfig","lifeName","toLowerCase","releaseListener","handleError","MicroApp","assets","hasInit","preFetchApps","globalAssets","js","css","formattedAppName"],"mappings":"sPAYaA,EAAU,QAGVC,EAA8B,oBAAXC,OAGnBC,EAAgC,oBAAXC,OAC9BA,OAEmB,oBAAXF,OACJA,OAEiB,oBAATG,KAAwBA,KAAOC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,EAAOI,GAAI,KAAMv7B,GAAaX,QACnDo6B,GAAqB0B,EAAOK,IAAK,MAAOx7B,GAAaZ,KAAK,KC2KtDzU,EAAcoH,EAAQ8F,UAAU,CAClC,MAAMI,EAAUlG,EAAQ8F,QAAQI,QAChC,GAAItN,EAAcsN,GAChB,IAAK,MAAM7K,KAAW6K,EAAS,CAC7B,MAAMwjC,EAAmBtsC,EAAc/B,GACnCquC,GAAoBruC,IAAYquC,IAClCxjC,EAAQwjC,GAAoBxjC,EAAQ7K,UAC7B6K,EAAQ7K,KAQzB6nC,GAAc/9B,KAAK1L,gBAIjB6K,GAAW,IAAI6kC"}
|
|
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/adapter.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/router/location.ts","../src/sandbox/router/index.ts","../src/sandbox/request.ts","../src/sandbox/with/index.ts","../src/sandbox/iframe/special_key.ts","../src/proxies/worker.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 MicroAppElementInterface,\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 isCanvasElement(target: unknown): target is HTMLCanvasElement {\n return toTypeString(target) === '[object HTMLCanvasElement]'\n}\n\nexport function isAnchorElement(target: unknown): target is HTMLAnchorElement {\n return toTypeString(target) === '[object HTMLAnchorElement]'\n}\n\nexport function isAudioElement(target: unknown): target is HTMLAudioElement {\n return toTypeString(target) === '[object HTMLAudioElement]'\n}\n\nexport function isVideoElement(target: unknown): target is HTMLVideoElement {\n return toTypeString(target) === '[object HTMLVideoElement]'\n}\n\nexport function isLinkElement(target: unknown): target is HTMLLinkElement {\n return toTypeString(target) === '[object HTMLLinkElement]'\n}\nexport function isBodyElement(target: unknown): target is HTMLBodyElement {\n return toTypeString(target) === '[object HTMLBodyElement]'\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 isDocumentFragment(target: unknown): target is DocumentFragment {\n return toTypeString(target) === '[object DocumentFragment]'\n}\n\nexport function isDocumentShadowRoot(target: unknown): target is DocumentFragment {\n return toTypeString(target) === '[object ShadowRoot]'\n}\n\nexport function isMicroAppBody(target: unknown): target is HTMLElement {\n return isElement(target) && target.tagName.toUpperCase() === 'MICRO-APP-BODY'\n}\n\nexport function isMicroAppHead(target: unknown): target is HTMLElement {\n return isElement(target) && target.tagName.toUpperCase() === 'MICRO-APP-HEAD'\n}\n\nexport function isWebComponentElement(target: unknown): boolean {\n let result = toTypeString(target) === '[object HTMLElement]'\n if (result) {\n const tagName = (target as HTMLElement).tagName.toUpperCase()\n result = result && !tagName.startsWith('MICRO-APP')\n }\n return result\n}\n\n// is ProxyDocument\nexport function isProxyDocument(target: unknown): target is Document {\n return toTypeString(target) === '[object ProxyDocument]'\n}\n\nexport function isTargetExtension(path: string, suffix: string): boolean {\n try {\n return createURL(path).pathname.split('.').pop() === suffix\n } catch {\n return false\n }\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 * async execution with macro task\n * @param fn callback\n * @param args params\n */\nexport function macro(fn: Func, delay = 0, ...args: unknown[]): void {\n setTimeout(fn.bind(null, ...args), delay)\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, port, host, protocol} = createURL(addProtocol(url), (window.rawWindow || window).location.href)\n\n // 自定义协议时, origin 返回字符串 null\n let newOrigin = origin;\n if (origin == 'null') {\n if (port) {\n newOrigin = protocol + '//' + host + ':' + port\n } else {\n newOrigin = protocol + '//' + host\n }\n }\n logError('newOrigin', newOrigin, origin);\n\n /**\n * keep the original url unchanged, such as .html .node .php .net .etc, search, except hash\n * BUG FIX: Never using '/' to complete url, refer to https://github.com/jd-opensource/micro-app/issues/1147\n */\n const fullPath = `${newOrigin}${pathname}${search}`\n logError('fullPath', fullPath);\n return /^\\w+?:\\/\\//.test(fullPath) ? fullPath : ''\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\n * 1. https://domain/xx/xx.html to https://domain/xx/\n * 2. https://domain/xx to https://domain/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 pathArr = `${origin}${pathname}`.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 /^((\\w+):)?\\/\\//.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 currentAppName: string | null = null\nexport function setCurrentAppName(appName: string | null): void {\n currentAppName = appName\n}\n\n// get the currently running app.name\nexport function getCurrentAppName(): string | null {\n return currentAppName\n}\n\nexport function throttleDeferForSetAppName(appName: string): void {\n if (currentAppName !== appName && !getPreventSetState()) {\n setCurrentAppName(appName)\n defer(() => {\n setCurrentAppName(null)\n })\n }\n}\n\n// only for iframe document.body(head).querySelector(querySelectorAll)\nlet iframeCurrentAppName: string | null = null\nexport function setIframeCurrentAppName(appName: string | null) {\n iframeCurrentAppName = appName\n}\n\nexport function getIframeCurrentAppName(): string | null {\n return iframeCurrentAppName\n}\n\nexport function throttleDeferForIframeAppName(appName: string): void {\n if (iframeCurrentAppName !== appName && !getPreventSetState()) {\n setIframeCurrentAppName(appName)\n defer(() => {\n setIframeCurrentAppName(null)\n })\n }\n}\n\n// prevent set app name\nlet preventSetState = false\nexport function getPreventSetState(): boolean {\n return preventSetState\n}\n\n/**\n * prevent set appName\n * usage:\n * removeDomScope(true)\n * -----> element scope point to base app <-----\n * removeDomScope(false)\n */\nexport function removeDomScope(force?: boolean): void {\n if (force !== false) {\n setCurrentAppName(null)\n setIframeCurrentAppName(null)\n if (force && !preventSetState) {\n preventSetState = true\n defer(() => {\n preventSetState = false\n })\n }\n } else {\n preventSetState = false\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\nexport type RootContainer = HTMLElement & MicroAppElementInterface\n/**\n * get micro-app element\n * @param target app container\n */\nexport function getRootContainer(target: HTMLElement | ShadowRoot): RootContainer {\n return (isShadowRoot(target) ? (target as ShadowRoot).host : target) as RootContainer\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\nexport function instanceOf<T extends new (...args: unknown[]) => unknown>(\n instance: unknown,\n constructor: T,\n): instance is T extends new (...args: unknown[]) => infer R ? R : boolean {\n if (instance === null || instance === undefined) {\n return false\n } else if (!isFunction(constructor)) {\n throw new TypeError(\"Right-hand side of 'instanceof' is not callable\")\n } else if (typeof instance === 'number' || typeof instance === 'string' || typeof instance === 'boolean') {\n // 检查 obj 是否是基本类型的包装器实例\n return false\n }\n let proto = Object.getPrototypeOf(instance)\n while (proto) {\n if (proto === constructor.prototype) {\n return true\n }\n proto = Object.getPrototypeOf(proto)\n }\n return false\n}\n\n/**\n * Format event name\n * In with sandbox, child event and lifeCycles bind to microAppElement, there are two events with same name - mounted unmount, it should be handled specifically to prevent conflicts\n * Issue: https://github.com/jd-opensource/micro-app/issues/1161\n * @param type event name\n * @param appName app name\n */\nconst formatEventList = ['mounted', 'unmount']\nexport function formatEventType(type: string, appName: string): string {\n return formatEventList.includes(type) ? `${type}-${appName}` : type\n}\n\n/**\n * Is the object empty\n * target maybe number, string, array ...\n */\nexport function isEmptyObject(target: unknown): boolean {\n return isPlainObject(target) ? !Object.keys(target).length : true\n}\n","import type { lifeCyclesType, AppInterface } from '@micro-app/types'\nimport microApp from '../micro_app'\nimport {\n logWarn,\n isFunction,\n removeDomScope,\n getRootContainer,\n assign,\n formatEventType,\n} 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 | null,\n appName: string,\n lifecycleName: LifecycleEventName,\n error?: Error,\n): void {\n if (!element) {\n return logWarn(`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, appName)\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 ['mounted', 'unmount', 'appstate-change', 'statechange']\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(formatEventType(eventName, app.name), {\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, isTargetExtension } 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 isJsResource = isTargetExtension(htmlUrl, 'js')\n const htmlPromise = isJsResource\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 this.printError('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 /**\n * NOTE:\n * 1. :is(h1, h2, h3):has(+ h2, + h3, + h4) {}\n * should be ==> micro-app[name=xxx] :is(h1, h2, h3):has(+ h2, + h3, + h4) {}\n * 2. :dir(ltr) {}\n * should be ==> micro-app[name=xxx] :dir(ltr) {}\n * 3. body :not(div, .fancy) {}\n * should be ==> micro-app[name=xxx] micro-app-body :not(div, .fancy) {}\n * 4. .a, .b, li:nth-child(3)\n * should be ==> micro-app[name=xxx] .a, micro-app[name=xxx] .b, micro-app[name=xxx] li:nth-child(3)\n * 5. :is(.a, .b, .c) a {}\n * should be ==> micro-app[name=xxx] :is(.a, .b, .c) a {}\n * 6. :where(.a, .b, .c) a {}\n * should be ==> micro-app[name=xxx] :where(.a, .b, .c) a {}\n */\n const attributeValues: {[key: string]: any} = {}\n const matchRes = m[0].replace(/\\[([^\\]=]+)(?:=([^\\]]+))?\\]/g, (match, p1, p2, offset) => {\n const mock = `__mock_${p1}_${offset}Value__`\n attributeValues[mock] = p2\n return match.replace(p2, mock)\n })\n\n return matchRes.replace(/(^|,[\\n\\s]*)([^,]+)/g, (_, separator, selector) => {\n selector = trim(selector)\n selector = selector.replace(/\\[[^\\]=]+(?:=([^\\]]+))?\\]/g, (match:string, p1: string) => {\n if (attributeValues[p1]) {\n return match.replace(p1, attributeValues[p1])\n }\n return match\n })\n if (selector && !(\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 this.printError(\"Declaration missing '{'\", this.linkPath)\n\n this.matchAllDeclarations()\n\n if (!this.matchCloseBrace()) return this.printError(\"Declaration missing '}'\", this.linkPath)\n\n return true\n }\n\n private matchAllDeclarations (nesting = 0): 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\\(([\"']?)(.*?)\\1\\)/gm, (all, _, $1) => {\n if (/^((data|blob):|#|%23)/.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.length) return\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 } else if (this.cssText.charAt(0) === '{') {\n this.matchOpenBrace()\n nesting++\n } else if (this.cssText.charAt(0) === '}') {\n if (nesting < 1) return\n this.matchCloseBrace()\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 this.layerRule()\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 this.printError('@keyframes missing name', this.linkPath)\n\n this.matchComments()\n\n if (!this.matchOpenBrace()) return this.printError(\"@keyframes missing '{'\", this.linkPath)\n\n this.matchComments()\n while (this.keyframeRule()) {\n this.matchComments()\n }\n\n if (!this.matchCloseBrace()) return this.printError(\"@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/CSS/@layer\n private layerRule (): boolean | void {\n if (!this.commonMatch(/^@layer\\s*([^{;]+)/)) return false\n\n if (!this.matchOpenBrace()) return !!this.commonMatch(/^[;]+/)\n\n this.matchComments()\n\n this.matchRules()\n\n if (!this.matchCloseBrace()) return this.printError('@layer missing \\'}\\'', this.linkPath)\n\n this.matchLeadingSpaces()\n\n return true\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 this.printError(`${name} missing '{'`, this.linkPath)\n\n this.matchComments()\n\n this.matchRules()\n\n if (!this.matchCloseBrace()) return this.printError(`${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 this.printError(`@${name} missing '{'`, this.linkPath)\n\n this.matchAllDeclarations()\n\n if (!this.matchCloseBrace()) return this.printError(`@${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 this.printError('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(/^}\\s*/)\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/jd-opensource/micro-app/issues/256\n if (isFireFox()) {\n this.result += encodeURIComponent(strFragment)\n } else {\n this.result += strFragment\n }\n }\n\n private printError (msg: string, linkPath?: string): void {\n if (this.cssText.length) {\n parseError(msg, linkPath)\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 const escapeRegExp = (regStr: string) => regStr.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n if (styleElement.textContent) {\n commonAction(styleElement, app.name, prefix, app.url, linkPath)\n\n const observer = new MutationObserver(() => {\n const escapedPrefix = escapeRegExp(prefix)\n const isPrefixed = styleElement.textContent && new RegExp(escapedPrefix).test(styleElement.textContent)\n observer.disconnect()\n if (!isPrefixed) {\n styleElement.__MICRO_APP_HAS_SCOPED__ = false\n scopedCSS(styleElement, app, linkPath)\n }\n })\n observer.observe(styleElement, { childList: true, characterData: true })\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 KEEP_ALIVE = 'keep-alive',\n CLEAR_DATA ='clear-data',\n SSR = 'ssr',\n FIBER = 'fiber',\n}\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\n// prefetch level\nexport const PREFETCH_LEVEL: number[] = [1, 2, 3]\n\n/**\n * memory router modes\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 * 2. native mode equal to disable-memory-router\n*/\n// 临时注释,1.0版本放开,默认模式切换为state\n// // default mode, sync child app router info to history.state\n// export const DEFAULT_ROUTER_MODE = 'state'\n// // sync child app router info to browser url as search\n// export const ROUTER_MODE_SEARCH = 'search'\n\n// 临时放开,1.0版本去除\nexport const ROUTER_MODE_STATE = 'state'\nexport const DEFAULT_ROUTER_MODE = 'search'\n\n// render base on browser url, and location.origin location.href point to base app\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_STATE,\n ROUTER_MODE_NATIVE,\n ROUTER_MODE_NATIVE_SCOPE,\n ROUTER_MODE_PURE,\n]\n\n// event bound to child app window\nconst BASE_SCOPE_WINDOW_EVENT = [\n 'popstate',\n 'hashchange',\n 'load',\n 'unload',\n 'unmount',\n 'appstate-change',\n 'statechange',\n 'mounted',\n 'error'\n // 'beforeunload', // remove at 2024.5.30 by cangdu\n]\n\n// bind event of with sandbox\nexport const SCOPE_WINDOW_EVENT_OF_WITH = BASE_SCOPE_WINDOW_EVENT\n\n// bind event of iframe sandbox\nexport const SCOPE_WINDOW_EVENT_OF_IFRAME = BASE_SCOPE_WINDOW_EVENT.concat([\n 'unhandledrejection',\n 'message'\n])\n\n// on event bound to child app window\n// TODO: with和iframe处理方式不同,需修改\nconst BASE_SCOPE_WINDOW_ON_EVENT = [\n 'onpopstate',\n 'onhashchange',\n 'onload',\n 'onunload',\n 'onerror'\n // 'onbeforeunload', // remove at 2024.5.30 by cangdu\n]\n\n// bind on event of with sandbox\nexport const SCOPE_WINDOW_ON_EVENT_OF_WITH = BASE_SCOPE_WINDOW_ON_EVENT\n\n// bind on event of iframe sandbox\nexport const SCOPE_WINDOW_ON_EVENT_OF_IFRAME = BASE_SCOPE_WINDOW_ON_EVENT.concat([\n 'onunhandledrejection',\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\nexport const HIJACK_LOCATION_KEYS = [\n 'host',\n 'hostname',\n 'port',\n 'protocol',\n 'origin',\n]\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', 'modulepreload', 'icon'].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.warn(`[micro-app from ${replaceElement ? 'runDynamicScript' : 'runScript'}] app ${app.name}: `, e, address)\n // throw error in with sandbox to parent app\n const error = e as Error\n let throwError = true\n if (typeof microApp?.options?.excludeRunScriptFilter === 'function') {\n throwError = microApp.options.excludeRunScriptFilter(address, error, app.name, app.url) !== true\n }\n if (throwError) {\n throw e\n }\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 with src='${address}' 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 inline 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/jd-opensource/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 isBodyElement,\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 body body element\n * @param app app\n * @param microAppHead micro-app-head element\n */\nfunction flatBodyChildren(\n body: HTMLElement,\n app: AppInterface,\n fiberStyleTasks: fiberTasks,\n): void {\n if (!body || !isBodyElement(body)) {\n return\n }\n const links = Array.from(body.getElementsByTagName('link'))\n\n links.map((dom) => {\n if (dom.hasAttribute('exclude') || checkExcludeUrl(dom.getAttribute('href'), app.name)) {\n dom.parentElement!.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, dom.parentElement, app)\n } else if (dom.hasAttribute('href')) {\n globalEnv.rawSetAttribute.call(dom, 'href', CompletionPath(dom.getAttribute('href')!, app.url))\n }\n return dom\n })\n\n const styles = Array.from(body.getElementsByTagName('style'))\n\n styles.map((dom) => {\n if (dom.hasAttribute('exclude')) {\n dom.parentElement!.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 return dom\n })\n\n const scripts = Array.from(body.getElementsByTagName('script'))\n\n scripts.map((dom) => {\n extractScriptElement(dom, dom.parentElement, app)\n return dom\n })\n const images = Array.from(body.getElementsByTagName('img'))\n\n images.map((dom) => {\n if (dom.hasAttribute('src')) {\n globalEnv.rawSetAttribute.call(dom, 'src', CompletionPath(dom.getAttribute('src')!, app.url))\n }\n return dom\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 flatBodyChildren(wrapElement, app, fiberStyleTasks)\n\n /**\n * Style and link are parallel, as 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 ? `__${appName}_from_base_app__` : `__${appName}_from_micro_app__`\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 changeEventAppName (newAppName: string, oldAppName: string): void {\n const newEventName = createEventName(formatAppName(newAppName), true)\n const oldEventName = createEventName(formatAppName(oldAppName), true)\n if (eventCenter.eventList.has(oldEventName)) {\n eventCenter.eventList.set(newEventName, eventCenter.eventList.get(oldEventName))\n eventCenter.eventList.delete(oldEventName)\n }\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'\ninterface IEventInfo {\n data: Record<PropertyKey, unknown>\n tempData?: Record<PropertyKey, unknown> | null\n force?: boolean\n callbacks: Set<CallableFunctionForInteract>\n}\n\nexport default class EventCenter {\n public eventList = new Map<string, IEventInfo | undefined>()\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 /**\n * In safari, nest app like: A -> B -> C\n * if B is iframe sandbox, and C is with sandbox, same property of document in C is abnormal\n * e.g:\n * document.all:\n * - typeof document.all ==> 'function'\n * - document.all.bind ==> undefined\n */\n if (isFunction(value) && !isConstructorFunction(value) && !isBoundedFunction(value) && value.bind) {\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","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 isMicroAppBody,\n getPreventSetState,\n throttleDeferForIframeAppName,\n isAnchorElement,\n} from '../libs/utils'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} from '../create_app'\nimport microApp from '../micro_app'\nimport { AppManager } from '../app_manager'\n\nexport class BaseSandbox implements BaseSandboxType {\n constructor (appName: string, url: string) {\n this.appName = appName\n this.url = url\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 'event',\n ]\n\n public appName: string\n public url: string\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 // reset mount, unmount when stop in default mode\n public clearHijackUmdHooks!: () => 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/jd-opensource/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 (\n container: Node,\n appName: string,\n): void {\n const children = Array.from(container.childNodes)\n\n children.length && children.forEach((child) => {\n patchElementTree(child, appName)\n })\n\n updateElementInfo(container, appName)\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 | null): T {\n if (\n appName &&\n isNode(node) &&\n node.__MICRO_APP_NAME__ !== appName &&\n !node.__PURE_ELEMENT__ &&\n !getPreventSetState()\n ) {\n /**\n * TODO:\n * 1. 测试baseURI和ownerDocument在with沙箱中是否正确\n * 经过验证with沙箱不能重写ownerDocument,否则react点击事件会触发两次\n */\n const props: {[kye:string]:any} = {\n __MICRO_APP_NAME__: {\n configurable: true,\n enumerable: true,\n writable: true,\n value: appName,\n },\n }\n if (isAnchorElement(node)) {\n // a 标签\n const microApp = AppManager.getInstance().get(appName)\n const hrefDescriptor = Object.getOwnPropertyDescriptor(node, 'href')\n const hrefConfigurable = hrefDescriptor?.configurable || !hrefDescriptor\n if (microApp && hrefConfigurable) {\n props.href = {\n get() {\n return this.getAttribute('href')\n },\n set(value: string) {\n if (value === undefined) {\n return\n }\n this.setAttribute('href', value)\n },\n }\n }\n }\n rawDefineProperties(node, props)\n\n /**\n * In FireFox, iframe Node.prototype will point to native Node.prototype after insert to document\n *\n * Performance:\n * iframe element.__proto__ === browser HTMLElement.prototype // Chrome: false, FireFox: true\n * iframe element.__proto__ === iframe HTMLElement.prototype // Chrome: true, FireFox: false\n *\n * NOTE:\n * 1. Node.prototype.baseURI\n * 2. Node.prototype.ownerDocument\n * 3. Node.prototype.parentNode\n * 4. Node.prototype.getRootNode\n * 5. Node.prototype.cloneNode\n * 6. Element.prototype.innerHTML\n * 7. Image\n */\n if (isIframeSandbox(appName)) {\n const proxyWindow = appInstanceMap.get(appName)?.sandBox?.proxyWindow\n if (proxyWindow) {\n rawDefineProperties(node, {\n baseURI: {\n configurable: true,\n enumerable: true,\n get: () => proxyWindow.location.href,\n },\n ownerDocument: {\n configurable: true,\n enumerable: true,\n get: () => node !== proxyWindow.document ? proxyWindow.document : null,\n },\n parentNode: getIframeParentNodeDesc(\n appName,\n globalEnv.rawParentNodeDesc,\n ),\n getRootNode: {\n configurable: true,\n enumerable: true,\n writable: true,\n value: function getRootNode (): Node {\n return proxyWindow.document\n }\n },\n })\n }\n }\n }\n\n return node\n}\n\n/**\n * get Descriptor of Node.prototype.parentNode for iframe\n * @param appName app name\n * @param parentNode parentNode Descriptor of iframe or browser\n */\nexport function getIframeParentNodeDesc (\n appName: string,\n parentNodeDesc: PropertyDescriptor,\n): PropertyDescriptor {\n return {\n configurable: true,\n enumerable: true,\n get (this: Node) {\n throttleDeferForIframeAppName(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 * e.g.:\n * 1. element-ui@2.x el-dropdown\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 const customParent = microApp.options.getRootElementParentNode?.(this, appName)\n if (customParent) {\n return customParent\n }\n if (microApp?.options?.inheritBaseBody !== true) {\n return appInstanceMap.get(appName)?.container?.querySelector('micro-app-body') || globalEnv.rawDocument.body\n }\n return globalEnv.rawDocument.body\n }\n return result\n }\n }\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'\nimport {\n updateElementInfo,\n} from '../adapter'\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 return updateElementInfo(element, appName)\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 return updateElementInfo(element, appName)\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_OF_WITH,\n SCOPE_WINDOW_ON_EVENT_OF_WITH,\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 formatEventType,\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_OF_WITH.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/jd-opensource/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_OF_WITH.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 type = formatEventType(type, appName)\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 type = formatEventType(type, appName)\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 setTimeoutHander = function(...args: any[]) {\n timeoutIdMap.delete(timeoutId)\n typeof handler === 'function' && handler(...args)\n }\n const handlerWithCleanup: TimerHandler = typeof handler === 'string' ? handler : setTimeoutHander\n const timeoutId = rawSetTimeout.call(rawWindow, handlerWithCleanup, timeout, ...args)\n timeoutIdMap.set(timeoutId, { handler: handlerWithCleanup, 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 MicroRouterInfoState,\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 isEmptyObject,\n} from '../../libs/utils'\nimport {\n appInstanceMap,\n} from '../../create_app'\nimport {\n ROUTER_MODE_LIST,\n DEFAULT_ROUTER_MODE,\n ROUTER_MODE_STATE,\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 targetLocation?: MicroLocation,\n): MicroState {\n // TODO: 验证native模式下修改state nextjs路由是否正常\n const rawState = globalEnv.rawWindow.history.state\n const additionalState: Record<'__MICRO_APP_STATE__', Record<string, MicroRouterInfoState>> = {\n __MICRO_APP_STATE__: assign({}, rawState?.__MICRO_APP_STATE__, {\n [appName]: {\n fullPath: targetLocation ? targetLocation.pathname + targetLocation.search + targetLocation.hash : null,\n state: microState ?? null,\n mode: getRouterMode(appName),\n }\n }),\n }\n\n // create new state object\n return assign({}, rawState, additionalState)\n}\n\n// delete micro app state form origin state\nexport function removeMicroState (appName: string, rawState: MicroState): MicroState {\n if (isPlainObject(rawState?.__MICRO_APP_STATE__)) {\n if (!isUndefined(rawState.__MICRO_APP_STATE__[appName])) {\n delete rawState.__MICRO_APP_STATE__[appName]\n }\n if (!Object.keys(rawState.__MICRO_APP_STATE__).length) {\n delete rawState.__MICRO_APP_STATE__\n }\n }\n\n return !isEmptyObject(rawState) ? assign({}, rawState) : null\n}\n\n// get micro app state form origin state\nexport function getMicroState (appName: string): MicroState {\n const rawState = globalEnv.rawWindow.history.state\n return rawState?.__MICRO_APP_STATE__?.[appName]?.state || null\n}\n\n// get micro app router info state form origin state\nexport function getMicroRouterInfoState (appName: string): MicroRouterInfoState | null {\n const rawState = globalEnv.rawWindow.history.state\n return rawState?.__MICRO_APP_STATE__?.[appName] || null\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 const rawState = globalEnv.rawWindow.history.state\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 /**\n * Get fullPath from __MICRO_APP_STATE__\n * NOTE:\n * 1. state mode: all base on __MICRO_APP_STATE__\n * 2. pure mode: navigate by location.xxx may contain one-time information in __MICRO_APP_STATE__\n * 3. native mode: vue-router@4 will exec replaceState with history.state before pushState, like:\n * history.replaceState(\n * assign({}, history.state, {...}),\n * title,\n * history.state.current, <---\n * )\n * when base app jump to another page from child page, it will replace child path with base app path\n * e.g: base-home --> child-home --> child-about(will replace with child-home before jump to base-home) --> base-home, when go back, it will back to child-home not child-about\n * So we take the fullPath as standard\n */\n // 问题:1、同一个页面多个子应用,一个修改后... --- native模式不支持多个子应用同时渲染,多个子应用推荐使用其它模式\n // if (isRouterModeCustom(appName)) {\n // return rawLocation.pathname + rawLocation.search + rawLocation.hash\n // }\n // return rawState?.__MICRO_APP_STATE__?.[appName]?.fullPath || null\n return rawState?.__MICRO_APP_STATE__?.[appName]?.fullPath || (isRouterModeCustom(appName) ? rawLocation.pathname + rawLocation.search + rawLocation.hash : null)\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 rawLocation = globalEnv.rawWindow.location\n let targetFullPath = targetLocation.pathname + targetLocation.search + targetLocation.hash\n let isAttach2Hash = false\n if (isRouterModeSearch(appName)) {\n let { pathname, search, hash } = rawLocation\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 // TODO: 这里和下面的if判断可以简化一下\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 if (isRouterModeState(appName) || isRouterModePure(appName)) {\n targetFullPath = rawLocation.pathname + rawLocation.search + rawLocation.hash\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 */\nexport function removeMicroPathFromURL (appName: string): HandleMicroPathResult {\n let { pathname, search, hash } = 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/**\n * get router mode of app\n * NOTE: app maybe undefined\n */\nfunction getRouterMode (appName: string): string | undefined {\n return appInstanceMap.get(appName)?.routerMode\n}\n\n// router mode is search\nexport function isRouterModeSearch (appName: string): boolean {\n return getRouterMode(appName) === DEFAULT_ROUTER_MODE\n}\n\n// router mode is state\nexport function isRouterModeState (appName: string): boolean {\n return getRouterMode(appName) === ROUTER_MODE_STATE\n}\n\n// router mode is history\nexport function isRouterModeNative (appName: string): boolean {\n return getRouterMode(appName) === ROUTER_MODE_NATIVE\n}\n\n// router mode is disable\nexport function isRouterModeNativeScope (appName: string): boolean {\n return getRouterMode(appName) === ROUTER_MODE_NATIVE_SCOPE\n}\n\n// router mode is pure\nexport function isRouterModePure (appName: string): boolean {\n return getRouterMode(appName) === 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 initRouterMode (\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 getMicroRouterInfoState,\n isEffectiveApp,\n isRouterModeCustom,\n} from './core'\nimport {\n updateMicroLocation,\n} from './location'\nimport {\n removeDomScope,\n isFunction,\n macro,\n getRootContainer,\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 /**\n * base app may respond to popstateEvent async(lazy load page & browser back/forward), but child app will respond to popstateEvent immediately(vue2, react), this will cause some problems\n * 2 solutions:\n * 1. child app respond to popstateEvent async -- router-event-delay\n * 2. child app will not respond to popstateEvent in some scenarios (history.state===null || history.state?__MICRO_APP_STATE__[appName])\n * NOTE 1:\n * 1. browser back/forward\n * 2. location.hash/search/pathname = xxx\n * 3. <a href=\"/#/xxx\">, <a href=\"/xxx\">\n * 4. history.back/go/forward\n * 5. history.pushState/replaceState\n *\n * NOTE2:\n * 1、react16 hash mode navigate by location.hash = xxx, history.state is always null, but react16 respond to popstateEvent sync\n * 2、multiple child apps may has problems\n */\n if (\n !isRouterModeCustom(appName) ||\n !globalEnv.rawWindow.history.state ||\n getMicroRouterInfoState(appName)\n ) {\n const container = appInstanceMap.get(appName)?.container\n macro(\n () => updateMicroLocationWithEvent(appName, getMicroPathFromURL(appName)),\n (container && getRootContainer(container))?.getRouterEventDelay() ?? 0\n )\n }\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 if (app?.sandBox) {\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/**\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 * Object.defineProperty(newPopStateEvent, 'type', {\n * value: 'popstate',\n * writable: true,\n * configurable: true,\n * enumerable: true,\n * })\n */\n /**\n * create PopStateEvent named popstate-appName with sub app state\n * TODO: feeling like there's something wrong, check carefully\n * In native mode, getMicroState(appName) return rawWindow.history.state when use microApp.router.push/replace or other scenes when state.__MICRO_APP_STATE__[appName] is null\n */\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 bindFunctionToRawTarget from '../bind_function'\nimport {\n isString,\n createURL,\n isPlainObject,\n isURL,\n assign,\n removeDomScope,\n isUndefined,\n isNull,\n} from '../../libs/utils'\nimport {\n setMicroPathToURL,\n setMicroState,\n getMicroState,\n getMicroRouterInfoState,\n getMicroPathFromURL,\n isEffectiveApp,\n isRouterModePure,\n isRouterModeSearch,\n isRouterModeState,\n isRouterModeCustom,\n} from './core'\nimport {\n dispatchNativeEvent,\n} from './event'\nimport {\n updateMicroLocation,\n} from './location'\nimport {\n getActiveApps,\n} from '../../micro_app'\nimport {\n appInstanceMap,\n isIframeSandbox,\n} 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 rests[2] = isUndefined(rests[2]) || isNull(rests[2]) || ('' + rests[2] === '') ? microLocation.href : '' + 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], targetLocation),\n rests[1],\n )\n }\n if (targetFullPath !== microLocation.fullPath) {\n updateMicroLocation(appName, targetFullPath, microLocation)\n }\n appInstanceMap.get(appName)?.sandBox.updateIframeBase?.()\n }\n }\n\n const originalHistory = {\n pushState: getMicroHistoryMethod('pushState'),\n replaceState: getMicroHistoryMethod('replaceState'),\n }\n\n if (isIframeSandbox(appName)) {\n return assign({\n go (delta?: number) {\n return rawHistory.go(delta)\n }\n }, originalHistory) as MicroHistory\n }\n\n return new Proxy(rawHistory, {\n get (target: History, key: PropertyKey): HistoryProxyValue {\n if (key === 'pushState' || key === 'replaceState') {\n return originalHistory[key]\n } else if (key === 'state') {\n return getMicroState(appName)\n }\n return bindFunctionToRawTarget<History, HistoryProxyValue>(Reflect.get(target, key), target, 'HISTORY')\n },\n set (target: History, key: PropertyKey, value: unknown): boolean {\n if (key === 'pushState' || key === 'replaceState') {\n originalHistory[key] = value as CallableFunction\n } else {\n Reflect.set(target, key, value)\n }\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 // just search mode will dispatch native event\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 __MICRO_APP_STATE__ in history.state\n * Fix bug of missing __MICRO_APP_STATE__ 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?.__MICRO_APP_STATE__ &&\n (!isPlainObject(rests[0]) || !rests[0].__MICRO_APP_STATE__) &&\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 __MICRO_APP_STATE__: rawWindow.history.state.__MICRO_APP_STATE__,\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) || isRouterModeState(appName)) && !getMicroPathFromURL(appName)) {\n const app = appInstanceMap.get(appName)!\n attachRouteToBrowserURL(\n appName,\n setMicroPathToURL(appName, app.sandBox.proxyWindow.location),\n setMicroState(appName, getMicroState(appName), app.sandBox.proxyWindow.location),\n )\n }\n\n if (isRouterModeCustom(appName) && !getMicroRouterInfoState(appName)) {\n nativeHistoryNavigate(\n appName,\n 'replaceState',\n rawWindow.location.href,\n setMicroState(appName)\n )\n }\n\n // if (isRouterModeCustom(appName) || isRouterModeSearch(appName)) {\n /**\n * history.pushState/replaceState后主动触发子应用响应\n * 问题:子应用的卸载可能是异步的,而跳转的地址不一定在基础路径中,太快响应pushState可能会导致url地址被子应用改变或者子应用404,Promise太快卸载时出问题、setTimeout太慢keep-alive二次渲染后出问题\n * 1、history.pushState/replaceState执行后,子应用以异步的形式被主应用卸载,Promise响应时子应用还在,导致子应用跳转404后者浏览器url被子应用修改,产生异常\n * 2、keep-alive应用二次渲染时,由于setTimeout响应过慢,子应用在渲染后才接受到popstate事件,响应新的url,从而导致状态丢失\n * 3、同一个页面多个子应用,修改地址响应\n * 4、vue3跳转前会执行一次replace,有没有影响?\n */\n\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 __MICRO_APP_STATE__ 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 isRouterModeSearch,\n isRouterModePure,\n isRouterModeState,\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 targetLocation,\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 // pure mode will not call history.pushState/replaceState\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 // only search mode will dispatch PopStateEvent to browser\n if (!isRouterModeSearch(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、预渲染 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('导航失败,请确保子应用渲染后再调用此方法'))\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) || isRouterModeState(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), app.sandBox.proxyWindow.location as MicroLocation),\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","/* 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 setMicroState,\n getMicroState,\n isRouterModeCustom,\n isRouterModeNative,\n isRouterModeSearch,\n isRouterModePure,\n} from './core'\nimport {\n dispatchNativeEvent,\n updateMicroLocationWithEvent,\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 HIJACK_LOCATION_KEYS,\n} from '../../constants'\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 methodName = isRouterModePure(appName) ? 'replaceState' : methodName\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 will not reload browser\n * 2. if address is same and has hash, it will not add route stack\n */\n if (\n targetLocation.pathname === proxyLocation.pathname &&\n targetLocation.search === proxyLocation.search\n ) {\n let oldHref = null\n // NOTE: if pathname & search is same, it should record router info to history.state in pure mode\n if (targetLocation.hash !== proxyLocation.hash || isRouterModePure(appName)) {\n // search mode only\n if (setMicroPathResult.isAttach2Hash) {\n oldHref = rawLocation.href\n }\n // if router mode is pure and targetLocation.hash exist, it will not call nativeHistoryNavigate\n if (!isRouterModePure(appName) || !targetLocation.hash) {\n nativeHistoryNavigate(\n appName,\n methodName,\n setMicroPathResult.fullPath,\n !isRouterModeSearch(appName) ? setMicroState(appName, null, targetLocation) : null,\n )\n }\n }\n\n if (targetLocation.hash) {\n if (isRouterModeSearch(appName)) {\n dispatchNativeEvent(appName, false, oldHref)\n } else {\n updateMicroLocationWithEvent(appName, targetLocation.pathname + targetLocation.search + targetLocation.hash)\n }\n } else {\n reload()\n }\n return void 0\n }\n\n // when pathname or search change, simulate behavior of browser (reload) manually\n // TODO: state模式下pushState会带上上一个页面的state,会不会有问题,尤其是vue3,应不应该将主应用的state设置为null\n nativeHistoryNavigate(\n appName,\n methodName,\n setMicroPathResult.fullPath,\n !isRouterModeSearch(appName) ? setMicroState(appName, null, targetLocation) : null,\n )\n reload()\n return void 0\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 (\n targetLocation[key] === proxyLocation[key] || isRouterModePure(appName)\n )\n ? 'replaceState'\n : 'pushState',\n setMicroPathToURL(appName, targetLocation).fullPath,\n !isRouterModeSearch(appName) ? setMicroState(appName, null, targetLocation) : null,\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 /**\n * Special keys: host, hostname, port, protocol, origin, href\n * NOTE:\n * 1. In native mode this keys point to browser, in other mode this keys point to child app origin\n * 2. In iframe sandbox, iframe.src is base app address, so origin points to the browser by default, we need to replace it with child app origin\n * 3. In other modes, origin points to child app\n */\n if (HIJACK_LOCATION_KEYS.includes(key)) {\n if (isRouterModeNative(appName)) {\n return rawLocation[key]\n }\n if (isIframe) {\n return childStaticLocation![key]\n }\n }\n\n if (key === 'href') {\n if (isRouterModeNative(appName)) {\n return target[key].replace(target.origin, rawLocation.origin)\n }\n if (isIframe) {\n // 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 if (!isRouterModePure(appName)) {\n navigateWithNativeEvent(\n appName,\n 'pushState',\n setMicroPathToURL(appName, targetLocation),\n false,\n setMicroState(appName, null, targetLocation),\n )\n }\n if (!isRouterModeSearch(appName)) {\n updateMicroLocationWithEvent(appName, targetLocation.pathname + targetLocation.search + targetLocation.hash)\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 targetFullPath: 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(targetFullPath, 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\n /**\n * The native mode also base of history.state, and the modification of the browser url cannot be controlled. It is very likely that the browser url and __MICRO_APP_STATE__ are different.\n * Especially during init of child or forward and backward of browser, because vue-router@4 will actively modify the browser URL, the above situation often occurs\n * To solve this problem, after child app is initialized and responds to the popstateEvent, it is determined whether __MICRO_APP_STATE__ and the browser url are different. If they are different, the browser url will updated to the address of __MICRO_APP_STATE__\n * NOTE:\n * 1. If __MICRO_APP_STATE__ is different from the URL, then the operation of updating the URL is correct, otherwise there will be a problem of inconsistency between the URL and the rendered page\n * 2. When there are multiple child app in native mode, if one of them changes the URL address, the other one will not change __MICRO_APP_STATE__, and refresh browser will cause problems\n */\n const rawLocation = globalEnv.rawWindow.location\n if (\n isRouterModeCustom(appName) &&\n (targetFullPath !== rawLocation.pathname + rawLocation.search + rawLocation.hash) &&\n type !== 'prevent'\n ) {\n nativeHistoryNavigate(appName, 'replaceState', targetFullPath, globalEnv.rawWindow.history.state)\n }\n\n // update latest values of microLocation to `to`\n const to = createGuardLocation(appName, microLocation)\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 initRouterMode,\n isRouterModeCustom,\n isRouterModeSearch,\n} from './core'\nexport {\n patchHistory,\n releasePatchHistory,\n} from './history'\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 if (isRouterModePure(appName)) {\n removePathFromBrowser(appName)\n }\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(appName, null, microLocation),\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 // TODO: keep-router-state 功能太弱,是否可以增加优先级,或者去掉\n if (!keepRouteState && !isRouterModeCustom(appName)) {\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 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 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 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 // The methods defined by class are hung on the prototype, and enumerable is false by default\n MicroXMLHttpRequest.prototype && Object.defineProperty(MicroXMLHttpRequest.prototype, 'open', { enumerable: true })\n return MicroXMLHttpRequest\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 Func,\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 isFunction,\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(appName, url)\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 * 4. mount & unmount hook should delete in default mode when stop\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 this.clearHijackUmdHooks()\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 location: microAppWindow.location,\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 * 2. hijack umd hooks -- mount, unmount, micro-app-appName\n * @param container micro app container\n */\n public actionsBeforeExecScripts (container: Element | ShadowRoot, handleUmdHooks: Func): void {\n this.patchStaticElement(container)\n this.clearHijackUmdHooks = this.hijackUmdHooks(this.appName, this.microAppWindow, handleUmdHooks)\n }\n\n // hijack mount, unmount, micro-app-appName hook to microAppWindow\n private hijackUmdHooks (\n appName: string,\n microAppWindow: microAppWindowType,\n handleUmdHooks: Func,\n ): () => void {\n let mount: Func | null, unmount: Func | null, microAppLibrary: Record<string, unknown> | null\n rawDefineProperties(microAppWindow, {\n mount: {\n configurable: true,\n get: () => mount,\n set: (value) => {\n if (this.active && isFunction(value) && !mount) {\n handleUmdHooks(mount = value, unmount)\n }\n }\n },\n unmount: {\n configurable: true,\n get: () => unmount,\n set: (value) => {\n if (this.active && isFunction(value) && !unmount) {\n handleUmdHooks(mount, unmount = value)\n }\n }\n },\n [`micro-app-${appName}`]: {\n configurable: true,\n get: () => microAppLibrary,\n set: (value) => {\n if (this.active && isPlainObject(value) && !microAppLibrary) {\n microAppLibrary = value\n handleUmdHooks(microAppLibrary.mount, microAppLibrary.unmount)\n }\n }\n }\n })\n\n return () => {\n mount = unmount = microAppLibrary = null\n }\n }\n\n public setStaticAppState (state: string): void {\n this.microAppWindow.__MICRO_APP_STATE__ = state\n }\n}\n","\nexport const UN_PROXY_INSTANCEOF_KEYS = [\n 'Array'\n]\n\nexport const escape2RawWindowKeys = [\n 'getComputedStyle',\n // FIX ISSUE: https://github.com/jd-opensource/micro-app/issues/1292\n 'DOMParser',\n 'visualViewport',\n 'matchMedia',\n 'ResizeObserver',\n 'IntersectionObserver',\n]\n\nexport const escape2RawWindowRegExpKeys = [\n /animationFrame$/i,\n /mutationObserver$/i,\n /height$|width$/i,\n /offset$/i,\n /selection$/i,\n /^range/i,\n /^screen/i,\n /^scroll/i,\n /X$|Y$/,\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// hijack InstanceOf of iframe class\nexport const hijackInstanceOfWindowRegExpKeys = [\n /^((HTML|SVG)\\w*|MathML)?Element$/,\n /^(Node|Text|Attr|Comment|EventTarget|CharacterData|NamedNodeMap|ShadowRoot)$/,\n /^Document(Type|Fragment)?$/,\n /^(?!PopState).*Event$/,\n /^DataTransfer/\n]\n\n// proxy to shadowRoot or rawDocument (property)\nexport const proxy2RawDocOrShadowKeys = [\n 'childElementCount',\n 'children',\n 'firstElementChild',\n 'firstChild',\n 'lastElementChild',\n 'activeElement', // not for Element, just for document/shadowRoot\n 'fullscreenElement', // not for Element, just for document/shadowRoot\n 'pictureInPictureElement', // not for Element, just for document/shadowRoot\n 'pointerLockElement', // not for Element, just for document/shadowRoot\n 'styleSheets', // not for Element, just for document/shadowRoot\n]\n\n// proxy to shadowRoot or rawDocument (method)\nexport const proxy2RawDocOrShadowMethods = [\n 'append',\n 'contains',\n 'replaceChildren',\n 'createRange', // not for Element, just for document/shadowRoot\n 'getSelection', // not for Element, just for document/shadowRoot\n 'elementFromPoint', // not for Element, just for document/shadowRoot\n 'elementsFromPoint', // not for Element, just for document/shadowRoot\n 'getAnimations', // not for Element, just for document/shadowRoot\n]\n\n// proxy to rawDocument (property)\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// proxy to rawDocument (method)\nexport const proxy2RawDocumentMethods = [\n 'execCommand',\n 'createRange',\n 'exitFullscreen',\n 'exitPictureInPicture',\n 'getElementsByTagNameNS',\n 'hasFocus',\n 'prepend',\n]\n","\nimport { appInstanceMap } from '../create_app'\nimport { CompletionPath, getCurrentAppName } from '../libs/utils'\n\ninterface WorkerOptions {\n name?: string;\n type?: 'classic' | 'module';\n credentials?: 'omit' | 'same-origin' | 'include';\n}\n\nconst EXCLUDE_URL_PROTOCOLS = [\n 'blob:'\n]\n\ninterface WorkerInstance extends EventTarget {\n postMessage(message: any, transfer?: Transferable[]): void;\n terminate(): void;\n}\ninterface Worker {\n new(url: string | URL, options?: WorkerOptions): WorkerInstance;\n}\n\n// 重写 Worker 构造函数的类型\nconst originalWorker = window.Worker\n\nfunction isSameOrigin(url: string | URL): boolean {\n try {\n // 检查 URL 是否与当前页面在同一个源\n const parsedUrl = url instanceof URL ? url : new URL(url as string)\n if (EXCLUDE_URL_PROTOCOLS.includes(parsedUrl.protocol)) {\n return true\n }\n return (\n parsedUrl.protocol === window.location.protocol &&\n parsedUrl.hostname === window.location.hostname &&\n parsedUrl.port === window.location.port\n )\n } catch (error) {\n return false\n }\n}\n\nfunction urlFromScript(script: string) {\n let blob\n try {\n blob = new Blob([script], {\n type: 'application/javascript'\n })\n } catch (e) {\n const BlobBuilder =\n // @ts-ignore\n window.BlobBuilder ||\n // @ts-ignore\n window.WebKitBlobBuilder ||\n // @ts-ignore\n window.MozBlobBuilder ||\n // @ts-ignore\n window.MSBlobBuilder\n const blobBuilder = new BlobBuilder()\n blobBuilder.append(script)\n blob = blobBuilder.getBlob('application/javascript')\n }\n\n const URL = window.URL || window.webkitURL\n return URL.createObjectURL(blob)\n}\n\n// @ts-ignore\nconst WorkerProxy = new Proxy<Worker>(originalWorker, {\n construct(Target, args): WorkerInstance {\n let [scriptURL, options] = args\n options = options || {}\n const appName = getCurrentAppName()\n let url = scriptURL\n if (appName) {\n const app = appInstanceMap.get(appName)\n url = CompletionPath(scriptURL, app!.url)\n }\n\n if (url && !isSameOrigin(url)) {\n // 如果 scriptURL 是跨域的,使用 Blob URL 加载并执行 worker\n const script = `import \"${scriptURL}\";`\n const workerPath = urlFromScript(script)\n options.type = 'module'\n return new Target(workerPath, options) as WorkerInstance\n } else {\n // 如果 scriptURL 是同源的,直接使用原生的 Worker 构造函数\n return new Target(scriptURL, options) as WorkerInstance\n }\n },\n})\n\nexport default WorkerProxy\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 instanceOf,\n isConstructor,\n} from '../../libs/utils'\nimport {\n GLOBAL_KEY_TO_WINDOW,\n SCOPE_WINDOW_EVENT_OF_IFRAME,\n SCOPE_WINDOW_ON_EVENT_OF_IFRAME,\n} from '../../constants'\nimport {\n UN_PROXY_INSTANCEOF_KEYS,\n escape2RawWindowKeys,\n escape2RawWindowRegExpKeys,\n} from './special_key'\nimport WorkerProxy from '../../proxies/worker'\nimport microApp from '../../micro_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: IframeSandbox,\n): CommonEffectHook {\n patchWindowProperty(appName, microAppWindow, sandbox)\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 sandbox: IframeSandbox,\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 /**\n * In FireFox, iframe Element.prototype will point to native Element.prototype after insert to document\n * Rewrite all constructor's Symbol.hasInstance of iframeWindow\n * NOTE:\n * 1. native event instanceof iframe window.Event\n * 2. native node instanceof iframe window.Node\n * 3. native element instanceof iframe window.Element\n * 4. native url instanceof iframe window.URL\n * ...\n */\n if (\n isConstructor(microAppWindow[key]) &&\n key in rawWindow &&\n !UN_PROXY_INSTANCEOF_KEYS.includes(key) &&\n !microApp.options.excludeRewriteIframeConstructor?.includes(key)\n ) {\n rawDefineProperty(microAppWindow[key], Symbol.hasInstance, {\n configurable: true,\n enumerable: false,\n value (target: unknown): boolean {\n return instanceOf(target, rawWindow[key]) || instanceOf(target, microAppWindow[key])\n },\n })\n }\n\n return /^on/.test(key) && !SCOPE_WINDOW_ON_EVENT_OF_IFRAME.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 * In esmodule(vite) proxyWindow will not take effect,\n * escapeProperties should define to microAppWindow\n */\n sandbox.escapeProperties.forEach((key: PropertyKey) => {\n let rawValue = microAppWindow[key]\n rawDefineProperty(microAppWindow, key, {\n enumerable: true,\n configurable: true,\n get () {\n return rawValue ?? bindFunctionToRawTarget(rawWindow[key], rawWindow)\n },\n set (value: unknown) {\n rawValue = value\n }\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 Object.defineProperty(microAppWindow, 'Worker', {\n value: WorkerProxy,\n configurable: true,\n writable: true,\n })\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 === 'Worker') {\n return WorkerProxy\n }\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.get(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 // sandbox.escapeProperties will not set to rawWindow from rc.9\n Reflect.set(target, key, value)\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 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, rawDispatchEvent } = 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 /**\n * TODO: SCOPE_WINDOW_EVENT_OF_IFRAME的事件非常少,有可能导致问题\n * 1、一些未知的需要绑定到iframe的事件被错误的绑定到原生window上\n */\n let escapeSandboxEvent: Array<string> = []\n if (Array.isArray(microApp?.options?.escapeIframeWindowEvents)) {\n escapeSandboxEvent = microApp.options.escapeIframeWindowEvents\n }\n const scopeWindowEvent = SCOPE_WINDOW_EVENT_OF_IFRAME.filter(item => !escapeSandboxEvent.includes(item))\n return scopeWindowEvent.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 microAppWindow.dispatchEvent = function (event: Event): boolean {\n return rawDispatchEvent.call(getEventTarget(event?.type), event)\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 throttleDeferForIframeAppName,\n isWebComponentElement,\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'\nimport microApp from '../../micro_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}\nfunction getElementDocument(microDocument: Document, rawDocument: Document): Document {\n if (microApp?.options?.disableIframeRootDocument) {\n return rawDocument\n }\n return microDocument\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 let element = rawMicroCreateElement.call(getElementDocument(this, rawDocument), tagName, options)\n if (isWebComponentElement(element)) {\n element = rawMicroCreateElement.call(rawDocument, tagName, options)\n }\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(getElementDocument(this, rawDocument), namespaceURI, name, options)\n return updateElementInfo(element, appName)\n }\n\n microRootDocument.prototype.createTextNode = function createTextNode (data: string): Text {\n const element = rawMicroCreateTextNode.call(getElementDocument(this, rawDocument), data)\n return updateElementInfo<Text>(element, appName)\n }\n\n microRootDocument.prototype.createDocumentFragment = function createDocumentFragment (): DocumentFragment {\n const element = rawMicroCreateDocumentFragment.call(getElementDocument(this, rawDocument))\n return updateElementInfo(element, appName)\n }\n\n microRootDocument.prototype.createComment = function createComment (data: string): Comment {\n const element = rawMicroCreateComment.call(getElementDocument(this, rawDocument), data)\n return updateElementInfo<Comment>(element, appName)\n }\n\n function getBindTarget (target: Document): Document {\n /**\n * handler for:\n * 1. document.getElementsByTagName('head')[0].querySelector('script')\n * 2. document.querySelector('body').querySelectorAll('script')\n * ...\n */\n throttleDeferForIframeAppName(appName)\n // DOMParser.document !== microDocument\n return microDocument === target ? rawDocument : target\n }\n\n // query element👇\n function querySelector (this: Document, selectors: string): any {\n const _this = getBindTarget(this)\n if (selectors === 'body' && microApp?.options?.inheritBaseBody !== true) {\n return this.body\n }\n if (\n !selectors ||\n isUniqueElement(selectors) ||\n rawDocument !== _this\n ) {\n return rawMicroQuerySelector.call(_this, selectors)\n }\n\n /**\n * The child app cannot query the base element inside iframe\n * Same for querySelectorAll\n *\n * Scenes:\n * 1. vue-router@4.x --> createWebHistory(base?: string)\n * const baseEl = document.querySelector('base')\n * base = (baseEl && baseEl.getAttribute('href')) || '/'\n *\n * Issue: https://github.com/jd-opensource/micro-app/issues/1335\n */\n const result = appInstanceMap.get(appName)?.querySelector(selectors)\n return result || selectors === 'base' ? result : rawMicroQuerySelector.call(microDocument, selectors)\n }\n\n function querySelectorAll (this: Document, selectors: string): any {\n const _this = getBindTarget(this)\n if (\n !selectors ||\n isUniqueElement(selectors) ||\n rawDocument !== _this\n ) {\n return rawMicroQuerySelectorAll.call(_this, selectors)\n }\n\n const result = appInstanceMap.get(appName)?.querySelectorAll(selectors) ?? []\n return result.length || selectors === 'base' ? result : rawMicroQuerySelectorAll.call(microDocument, 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 = getBindTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementById.call(_this, key)\n }\n\n try {\n return querySelector.call(getElementDocument(this, rawDocument), `#${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 = getBindTarget(this)\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementsByClassName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(getElementDocument(this, rawDocument), `.${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 = getBindTarget(getElementDocument(this, rawDocument))\n if (\n isUniqueElement(key) ||\n isInvalidQuerySelectorKey(key)\n ) {\n return rawMicroGetElementsByTagName.call(_this, key)\n // just script, not base\n } else if (/^script$/i.test(key)) {\n return rawMicroGetElementsByTagName.call(microDocument, key)\n }\n\n try {\n return querySelectorAll.call(getElementDocument(this, rawDocument), 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 = getBindTarget(getElementDocument(this, rawDocument))\n if (isInvalidQuerySelectorKey(key)) {\n return rawMicroGetElementsByName.call(_this, key)\n }\n\n try {\n return querySelectorAll.call(getElementDocument(this, rawDocument), `[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 throttleDeferForIframeAppName(appName)\n if (tagName === 'body' && microApp?.options?.inheritBaseBody !== true) {\n return sandbox.options.container?.querySelector('micro-app-body') || rawDocument[tagName]\n }\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, rawDispatchEvent } = 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.dispatchEvent = function (event: Event): boolean {\n return rawDispatchEvent.call(getEventTarget(event?.type, this), event)\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 isDocumentFragment,\n isFunction,\n isBrowser,\n} from '../../libs/utils'\nimport {\n updateElementInfo,\n getIframeParentNodeDesc,\n} from '../adapter'\nimport microApp from '../../micro_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, appName)\n}\n\n/**\n * patch iframe Node/Element\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 rawRootNode = globalEnv.rawRootNode\n const rawDocument = globalEnv.rawDocument\n const microDocument = microAppWindow.document\n const microRootNode = microAppWindow.Node\n const microRootElement = microAppWindow.Element\n const microDocumentFragment = microAppWindow.DocumentFragment\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 rawMicroFragmentAppend = microDocumentFragment.prototype.append\n const rawMicroFragmentPrepend = microDocumentFragment.prototype.prepend\n const rawMicroInsertAdjacentElement = microRootElement.prototype.insertAdjacentElement\n const rawMicroCloneNode = microRootNode.prototype.cloneNode\n const rawInnerHTMLDesc = Object.getOwnPropertyDescriptor(microRootElement.prototype, 'innerHTML')!\n const rawParentNodeDesc = Object.getOwnPropertyDescriptor(microRootNode.prototype, 'parentNode')!\n const rawOwnerDocumentDesc = Object.getOwnPropertyDescriptor(microRootNode.prototype, 'ownerDocument')!\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.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 rawRootNode.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 rawRootNode.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 rawRootNode.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 rawRootNode.prototype.removeChild.call(getRawTarget(this), oldChild)\n }\n\n microDocumentFragment.prototype.append = 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 (isDocumentFragment(this) ? rawMicroFragmentAppend : rawMicroAppend).call(this, ...nodes)\n }\n return rawRootElement.prototype.append.call(getRawTarget(this), ...nodes)\n }\n\n microDocumentFragment.prototype.prepend = 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 (isDocumentFragment(this) ? rawMicroFragmentPrepend : 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 /**\n * Specific prototype properties:\n * 1. baseURI\n * 2. ownerDocument\n * 3. parentNode\n * 4. innerHTML\n */\n rawDefineProperty(microRootNode.prototype, 'baseURI', {\n configurable: true,\n enumerable: true,\n get () {\n return sandbox.proxyWindow.location.href\n },\n })\n\n rawDefineProperty(microRootNode.prototype, 'ownerDocument', {\n configurable: true,\n enumerable: true,\n get () {\n return this.__PURE_ELEMENT__ || this === microDocument\n ? rawOwnerDocumentDesc.get?.call(this)\n : microDocument\n },\n })\n\n // patch parentNode\n rawDefineProperty(microRootNode.prototype, 'parentNode', getIframeParentNodeDesc(\n appName,\n rawParentNodeDesc,\n ))\n\n microRootNode.prototype.getRootNode = function getRootNode (): Node {\n return microDocument\n // TODO: any case return document?\n // const rootNode = rawMicroGetRootNode.call(this, options)\n // if (rootNode === appInstanceMap.get(appName)?.container) return microDocument\n // return rootNode\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(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 // 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, appName: string): 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 /^micro-app(-\\S+)?/i.test(this.tagName) &&\n key === 'data' &&\n this.setAttribute !== microRootElement.prototype.setAttribute\n ) {\n this.setAttribute(key, value)\n } else {\n const aHrefResolver = microApp?.options?.aHrefResolver\n if (key === 'href' && /^a$/i.test(this.tagName) && typeof aHrefResolver === 'function') {\n // 试验性质:a 标签开放自定义补齐功能\n value = aHrefResolver(value, appName, url)\n } else if (\n ((key === 'src' || key === 'srcset') && /^(img|script|video|audio|source|embed)$/i.test(this.tagName)) ||\n (key === 'href' && /^(link|image)$/i.test(this.tagName)) ||\n // If it is the anchor tag,eg. <a href=\"#xxx\"/>, the path will not be completed\n (key === 'href' && /^(a)$/i.test(this.tagName) && !/^#/.test(value))\n ) {\n let _url = url\n if (isBrowser && key === 'href' && /^a$/i.test(this.tagName) && isFunction(microApp.options.excludeAssetFilter) && microApp.options.excludeAssetFilter(value)) {\n _url = document.baseURI\n }\n value = CompletionPath(value, _url)\n }\n rawMicroSetAttribute.call(this, key, value)\n }\n }\n\n const protoAttrList: Array<[HTMLElement, string]> = [\n [microAppWindow.HTMLImageElement.prototype, 'src'],\n [microAppWindow.HTMLScriptElement.prototype, 'src'],\n [microAppWindow.HTMLLinkElement.prototype, 'href'],\n [microAppWindow.SVGImageElement.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 Func,\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 rawDefineProperties,\n isFunction,\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\ninterface IOption {\n container: HTMLElement | ShadowRoot | null,\n [key: string]: any\n}\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 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 public options: IOption\n // reset mount, unmount when stop in default mode\n public clearHijackUmdHooks!: () => void\n\n constructor (appName: string, url: string, options: IOption) {\n this.appName = appName\n this.url = url\n this.options = options\n const rawLocation = globalEnv.rawWindow.location\n const browserHost = rawLocation.protocol + '//' + rawLocation.host\n\n this.deleteIframeElement = this.createIframeElement(appName, browserHost + rawLocation.pathname, options)\n this.microAppWindow = this.iframe!.contentWindow\n\n this.patchIframe(this.microAppWindow, (resolve: CallableFunction) => {\n // refresh\n this.microAppWindow = this.iframe!.contentWindow\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 options?: Record<string, any>\n ): () => void {\n this.iframe = pureCreateElement('iframe')\n\n const iframeAttrs: Record<string, string> = {\n ...options?.attrs,\n id: appName,\n src: microApp.options.iframeSrc || browserPath,\n style: 'display: none',\n 'powered-by': 'micro-app',\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 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 // sandbox.stop may exec before sandbox.start, e.g: iframe sandbox + default mode + remount\n if (!this.active) return\n\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.clearHijackUmdHooks()\n }\n\n if (--globalEnv.activeSandbox === 0) {\n releasePatchElementAndDocument()\n releasePatchHistory()\n }\n\n if (--IframeSandbox.activeCount === 0) {\n // TODO: Is there anything to do?\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 // Update the base.href when initial and each redirect\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 * 2. hijack umd hooks -- mount, unmount, micro-app-appName\n * @param container micro app container\n */\n public actionsBeforeExecScripts (container: Element | ShadowRoot, handleUmdHooks: Func): void {\n this.patchStaticElement(container)\n this.clearHijackUmdHooks = this.hijackUmdHooks(this.appName, this.microAppWindow, handleUmdHooks)\n }\n\n // hijack mount, unmount, micro-app-appName hook to microAppWindow\n private hijackUmdHooks (\n appName: string,\n microAppWindow: microAppWindowType,\n handleUmdHooks: Func,\n ): () => void {\n let mount: Func | null, unmount: Func | null, microAppLibrary: Record<string, unknown> | null\n rawDefineProperties(microAppWindow, {\n mount: {\n configurable: true,\n get: () => mount,\n set: (value) => {\n if (this.active && isFunction(value) && !mount) {\n handleUmdHooks(mount = value, unmount)\n }\n }\n },\n unmount: {\n configurable: true,\n get: () => unmount,\n set: (value) => {\n if (this.active && isFunction(value) && !unmount) {\n handleUmdHooks(mount, unmount = value)\n }\n }\n },\n [`micro-app-${appName}`]: {\n configurable: true,\n get: () => microAppLibrary,\n set: (value) => {\n if (this.active && isPlainObject(value) && !microAppLibrary) {\n microAppLibrary = value\n handleUmdHooks(microAppLibrary.mount, microAppLibrary.unmount)\n }\n }\n }\n })\n\n return () => {\n mount = unmount = microAppLibrary = null\n }\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 rawDefineProperties,\n} from '../../libs/utils'\nimport globalEnv from '../../libs/global_env'\n\nexport function patchRouter (\n appName: string,\n url: string,\n microAppWindow: microAppWindowType,\n browserHost: string,\n): MicroLocation {\n const rawHistory = globalEnv.rawWindow.history\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 // save history.replaceState, it will be used in updateMicroLocation\n microAppWindow.rawReplaceState = microHistory.replaceState\n // rewrite microAppWindow.history\n assign(microHistory, createMicroHistory(appName, microAppWindow.location))\n // scrollRestoration proxy to rawHistory\n rawDefineProperties(microHistory, {\n scrollRestoration: {\n configurable: true,\n enumerable: true,\n get () {\n return rawHistory.scrollRestoration\n },\n set (value: string) {\n rawHistory.scrollRestoration = value\n }\n }\n })\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 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 attrs?: Record<string, string>,\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 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 public attrs?: Record<string, string>\n public isReloading = false\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 attrs,\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 this.attrs = attrs\n // exec before getInlineModeState\n this.iframe = iframe ?? false\n this.inline = this.getInlineModeState(inline)\n this.isReloading = false\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 if (this.isUnmounted()) return\n if (!this.isPrefetch) {\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 // TODO: statechange 还是 state-change,保持一致\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 const nextAction = () => {\n // place inside of nextAction, make sure iframe ready\n this.setAppState(appStates.BEFORE_MOUNT)\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 * current this.container is <div prerender='true'></div>\n * set this.container to <micro-app></micro-app>\n * NOTE:\n * 1. must exec before this.sandBox.rebuildEffectSnapshot\n * 2. must exec before this.preRenderEvents?.forEach((cb) => cb())\n */\n this.container = this.cloneContainer(container, this.container, false)\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 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 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: 兼容shadowRoot的场景\n this.cloneContainer(this.container, this.source.html, !this.umdMode)\n\n this.sandBox?.start({\n umdMode: this.umdMode,\n baseroute,\n defaultPage,\n disablePatchRequest,\n })\n\n if (!this.umdMode) {\n // patch element info of html\n this.sandBox?.actionsBeforeExecScripts(this.container, (mount, unmount) => {\n if (!this.umdMode && !this.isUnmounted()) {\n this.umdHookMount = isFunction(mount) ? mount : null\n // umdHookUnmount can works in default mode, register by window.unmount\n this.umdHookUnmount = isFunction(unmount) ? unmount : null\n // if mount & unmount is function, the sub app is umd mode\n if (isFunction(this.umdHookMount) && isFunction(this.umdHookUnmount)) {\n this.sandBox?.markUmdMode(this.umdMode = true)\n try {\n // if appState is mounted, it means that isFinished is true and this.handleMounted has already been executed, just exec this.umdHookMount\n if (this.getAppState() === appStates.MOUNTED) {\n this.umdHookMount(microApp.getData(this.name, true))\n } else {\n this.handleMounted(this.umdHookMount(microApp.getData(this.name, true)))\n }\n } catch (e) {\n logError('An error occurred when mount \\n', this.name, e)\n }\n }\n }\n })\n\n // if all js are executed, param isFinished will be true\n execScripts(this, (isFinished: boolean) => {\n if (!this.umdMode && isFinished === true) {\n this.handleMounted()\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 when mount \\n', this.name, e)\n }\n }\n }\n }\n\n /**\n * Initialization of sandbox is async, especially iframe sandbox are macro tasks\n * when child apps switch quickly, we need to pay attention to the following points:\n * NOTE:\n * 1. unmount app before exec nextAction (especially: iframe sandbox + default mode + remount)\n * this.container is null, this.sandBox will not start\n * 2. remount app of note 1\n * 3. unmount app during exec js\n */\n // TODO: 可优化?\n this.sandBox ? this.sandBox.sandboxReady.then(() => !this.isUnmounted() && 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 const nextAction = () => this.actionsAfterMounted()\n if (isPromise(umdHookMountResult)) {\n umdHookMountResult\n .then(nextAction)\n .catch((e) => {\n logError('An error occurred in window.mount \\n', this.name, e)\n nextAction()\n })\n } else {\n nextAction()\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 actionsAfterMounted (): 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 // 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 * 2. this.container maybe null: Initialization of sandbox is async, child app may unmount before exec nextAction of mount\n * 3. unmount app when loading files (this.container is not null)\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 try {\n this.handleUnmounted(\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n this.umdHookUnmount?.(microApp.getData(this.name, true)),\n )\n } catch (e) {\n logError('An error occurred when unmount \\n', this.name, e)\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: boolean,\n clearData: boolean,\n keepRouteState: boolean,\n unmountcb?: CallableFunction,\n umdHookUnmountResult?: unknown,\n ): void {\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 const nextAction = () => this.actionsAfterUnmounted({\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\n .then(nextAction)\n .catch((e) => {\n logError('An error occurred in window.unmount \\n', this.name, e)\n nextAction()\n })\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 actionsAfterUnmounted ({\n destroy,\n clearData,\n keepRouteState,\n unmountcb,\n }: UnmountParam): void {\n if (this.umdMode && this.container && !destroy) {\n this.cloneContainer(this.source.html, this.container as HTMLElement, false)\n }\n const shouldClearData = this.isReloading ? false : (clearData || destroy)\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: shouldClearData,\n })\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.isPrerender = false\n this.preRenderEvents = null\n this.setKeepAliveState(null)\n if (this.container) {\n this.container.innerHTML = ''\n this.container = null\n } else if (!this.umdMode) {\n /**\n * this.container is null means sandBox.start has not exec, so sandBox.stop won't exec either\n * we should remove iframeElement in default mode manually\n */\n this.sandBox?.deleteIframeElement?.()\n }\n // in iframe sandbox & default mode, delete the sandbox & iframeElement\n /**\n * TODO:\n * 1. with沙箱与iframe沙箱保持一致:with沙箱默认模式下删除 或者 iframe沙箱umd模式下保留\n * 2. 接1.0,this.sandBox置空,还需要注意后续app.sandBox相关操作,比如 scripts.ts --> app.iframe ? app.sandBox!.microBody : app.querySelector('micro-app-body'),如果是fiber或者预加载,会存在卸载后js还在处理的情况\n */\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 // 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,\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 /**\n * NOTE:\n * 1. this.container must set to container(micro-app element) before exec rebuildEffectSnapshot\n * ISSUE: https://github.com/jd-opensource/micro-app/issues/1115\n * 2. rebuildEffectSnapshot must exec before dispatch beforeshow event\n */\n const oldContainer = this.container\n this.container = container\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.cloneContainer(\n this.container,\n oldContainer,\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 // 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 // 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 target Accept cloned elements\n * @param origin Cloned element\n * @param deep deep clone or transfer dom\n */\n private cloneContainer <T extends HTMLElement | ShadowRoot | null> (\n target: T,\n origin: T,\n deep: boolean,\n ): T {\n // 在基座接受到afterhidden方法后立即执行unmount,彻底destroy应用时,因为unmount时同步执行,所以this.container为null后才执行cloneContainer\n if (origin && target) {\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 const iframeOption = {\n attrs: this.attrs,\n container: this.container\n }\n this.sandBox = this.iframe ? new IframeSandbox(this.name, this.url, iframeOption) : 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 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 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 isMicroAppHead,\n isNull,\n getIframeCurrentAppName,\n isDocumentFragment,\n isDocumentShadowRoot,\n isImageElement,\n isVideoElement,\n isAudioElement,\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 updateElementInfo,\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 targetNode target node\n * @param passiveNode second param of insertBefore and replaceChild\n */\nfunction invokePrototypeMethod(\n app: AppInterface,\n rawMethod: Func,\n parent: Node,\n targetNode: Node,\n passiveNode?: Node | null,\n): any {\n const hijackParent = getHijackParent(parent, targetNode, 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/jd-opensource/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(targetNode, 'parentNode')\n if ((!descriptor || descriptor.configurable) && !targetNode.__MICRO_APP_HAS_DPN__) {\n rawDefineProperties(targetNode, {\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(targetNode) &&\n rawMethod === globalEnv.rawAppendChild\n ) {\n fixReactHMRConflict(app)\n }\n\n /**\n * 1. If passiveNode exists, it must be insertBefore or replaceChild\n * 2. When removeChild, targetNode may not be in microAppHead or head\n * NOTE:\n * 1. If passiveNode not in hijackParent, insertBefore replaceChild will be degraded to appendChild\n * E.g: document.head.replaceChild(targetNode, document.scripts[0])\n * 2. If passiveNode 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(targetNode, document.head.childNodes[0])\n * ISSUE: https://github.com/jd-opensource/micro-app/issues/1071\n */\n if (passiveNode && !hijackParent.contains(passiveNode)) {\n if (rawMethod === globalEnv.rawInsertBefore && parent.contains(passiveNode)) {\n const indexOfParent = Array.from(parent.childNodes).indexOf(passiveNode as ChildNode)\n if (hijackParent.childNodes[indexOfParent]) {\n return invokeRawMethod(rawMethod, hijackParent, targetNode, hijackParent.childNodes[indexOfParent], app)\n }\n }\n return globalEnv.rawAppendChild.call(hijackParent, targetNode)\n } else if (rawMethod === globalEnv.rawRemoveChild && !hijackParent.contains(targetNode)) {\n if (parent.contains(targetNode)) {\n return rawMethod.call(targetNode.parentElement, targetNode)\n }\n return targetNode\n }\n\n return invokeRawMethod(rawMethod, hijackParent, targetNode, passiveNode, app)\n }\n\n return invokeRawMethod(rawMethod, parent, targetNode, passiveNode, app)\n}\n\n// head/body map to micro-app-head/micro-app-body\nfunction getHijackParent(\n parent: Node,\n targetNode: Node,\n app: AppInterface,\n): HTMLElement | null | undefined {\n if (app) {\n if (parent === document.head) {\n if (app.iframe && isScriptElement(targetNode)) {\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(targetNode)) {\n return app.sandBox.microBody\n }\n return app.querySelector<HTMLElement>('micro-app-body')\n }\n if (app.iframe && isScriptElement(targetNode)) {\n return app.sandBox.microBody\n }\n }\n return null\n}\n\nfunction invokeRawMethod(\n rawMethod: Func,\n parent: Node,\n targetNode: Node,\n passiveNode?: Node | null,\n app?: AppInterface,\n) {\n if (isPendMethod(rawMethod)) {\n /**\n * In iframe sandbox, script will pend to iframe.body, so we should reset rawMethod, because:\n * Element.prototype.append === DocumentFragment.prototype.append ==> false\n * Element.prototype.prepend === DocumentFragment.prototype.prepend ==> false\n */\n if (app?.iframe && isScriptElement(targetNode)) {\n if (rawMethod === globalEnv.rawFragmentAppend) {\n rawMethod = globalEnv.rawAppend\n } else if (rawMethod === globalEnv.rawFragmentPrepend) {\n rawMethod = globalEnv.rawPrepend\n }\n }\n return rawMethod.call(parent, targetNode)\n }\n\n return rawMethod.call(parent, targetNode, passiveNode)\n}\n\nfunction isPendMethod(method: CallableFunction) {\n return (\n method === globalEnv.rawAppend ||\n method === globalEnv.rawPrepend ||\n method === globalEnv.rawFragmentAppend ||\n method === globalEnv.rawFragmentPrepend\n )\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|image)$/i.test(newChild.tagName) && newChild.hasAttribute('href')) ||\n // If it is the anchor tag,eg. <a href=\"#xxx\"/>, the path will not be completed\n (/^(a)$/i.test(newChild.tagName) && newChild.hasAttribute('href') && !/^#/.test(newChild.getAttribute('href') || ''))\n ) {\n const aHrefResolver = microApp?.options?.aHrefResolver\n const hrefValue = newChild.getAttribute('href')!\n let nextHrefValue\n if ((/^(a)$/i.test(newChild.tagName) && typeof aHrefResolver === 'function')) {\n nextHrefValue = aHrefResolver(hrefValue, app.name, app.url)\n } else {\n nextHrefValue = CompletionPath(hrefValue, app.url)\n }\n globalEnv.rawSetAttribute.call(newChild, 'href', nextHrefValue)\n }\n }\n}\n\n/**\n * method of handle new node\n * @param parent parent node\n * @param newChild new node\n * @param passiveNode passive node\n * @param rawMethod method\n */\nfunction commonElementHandler(\n parent: Node,\n newChild: Node,\n passiveNode: 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 updateElementInfo(newChild, newChild.__MICRO_APP_NAME__ || currentAppName)\n const app = appInstanceMap.get(newChild.__MICRO_APP_NAME__!)\n if (app?.container) {\n if (isStyleElement(newChild)) {\n parent.getRootNode() instanceof ShadowRoot && newChild.setAttribute('ignore', 'true')\n }\n completePathDynamic(app, newChild)\n return invokePrototypeMethod(\n app,\n rawMethod,\n parent,\n handleNewNode(newChild, app),\n passiveNode && getMappingNode(passiveNode),\n )\n }\n }\n\n return invokeRawMethod(rawMethod, parent, newChild, passiveNode)\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 const rawDocumentFragment = globalEnv.rawDocumentFragment\n\n // prototype methods of add element👇\n rawRootNode.prototype.appendChild = function appendChild<T extends Node>(newChild: T): T {\n return commonElementHandler(this, newChild, null, globalEnv.rawAppendChild)\n }\n\n rawRootNode.prototype.insertBefore = function insertBefore<T extends Node>(newChild: T, refChild: Node | null): T {\n return commonElementHandler(this, newChild, refChild, globalEnv.rawInsertBefore)\n }\n\n rawRootNode.prototype.replaceChild = function replaceChild<T extends Node>(newChild: Node, oldChild: T): T {\n return commonElementHandler(this, newChild, oldChild, globalEnv.rawReplaceChild)\n }\n\n // prototype methods of delete element👇\n rawRootNode.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 rawDocumentFragment.prototype.append = 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(\n this,\n markElement(node as Node),\n null,\n isDocumentFragment(this) ? globalEnv.rawFragmentAppend : globalEnv.rawAppend,\n )\n i++\n }\n }\n\n rawDocumentFragment.prototype.prepend = rawRootElement.prototype.prepend = function prepend(...nodes: (Node | string)[]): void {\n let i = nodes.length\n let target = globalEnv.rawPrepend\n if (isDocumentFragment(this) || isDocumentShadowRoot(this)) {\n target = globalEnv.rawFragmentPrepend\n }\n\n while (i > 0) {\n let node = nodes[i - 1]\n node = isNode(node) ? node : globalEnv.rawCreateTextNode.call(globalEnv.rawDocument, node)\n commonElementHandler(\n this,\n markElement(node as Node),\n null,\n target,\n )\n i--\n }\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 /**\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 getElementQueryTarget(targetNode: Node): Node | null {\n const currentAppName = getIframeCurrentAppName() || getCurrentAppName()\n if ((targetNode === document.body || targetNode === document.head) && currentAppName) {\n const app = appInstanceMap.get(currentAppName)\n if (app?.container) {\n if (targetNode === document.body) {\n return app.querySelector<HTMLElement>('micro-app-body')\n } else if (targetNode === document.head) {\n return app.querySelector<HTMLElement>('micro-app-head')\n }\n }\n }\n return targetNode\n }\n\n /**\n * In iframe sandbox, script will render to iframe instead of micro-app-body\n * So when query elements, we need to search both micro-app and iframe\n * @param isEmpty get empty result\n * @param targetNode targetNode element\n * @param result origin result\n * @param selectors selectors\n * @param methodName querySelector or querySelectorAll\n */\n function getElementQueryResult<T>(\n isEmpty: boolean,\n targetNode: Node,\n result: T,\n selectors: string,\n methodName: string,\n ): T {\n if (isEmpty) {\n const currentAppName = getIframeCurrentAppName() || getCurrentAppName()\n if (currentAppName && isIframeSandbox(currentAppName)) {\n const app = appInstanceMap.get(currentAppName)!\n if (isMicroAppHead(targetNode)) {\n return app.sandBox.microHead[methodName](selectors)\n }\n if (isMicroAppBody(targetNode)) {\n return app.sandBox.microBody[methodName](selectors)\n }\n }\n }\n return result\n }\n\n rawRootElement.prototype.querySelector = function querySelector(selectors: string): Node | null {\n const _this = getElementQueryTarget(this) ?? this\n const result = globalEnv.rawElementQuerySelector.call(_this, selectors)\n return getElementQueryResult<Node | null>(\n isNull(result) && _this !== this,\n _this,\n result,\n selectors,\n 'querySelector',\n )\n }\n\n rawRootElement.prototype.querySelectorAll = function querySelectorAll(selectors: string): NodeListOf<Node> {\n const _this = getElementQueryTarget(this) ?? this\n const result = globalEnv.rawElementQuerySelectorAll.call(_this, selectors)\n return getElementQueryResult<NodeListOf<Node>>(\n !result.length && _this !== this,\n _this,\n result,\n selectors,\n 'querySelectorAll',\n )\n }\n\n // rewrite setAttribute, complete resource address\n rawRootElement.prototype.setAttribute = function setAttribute(key: string, value: any): void {\n if (\n /^micro-app(-\\S+)?/i.test(this.tagName) &&\n key === 'data' &&\n this.setAttribute !== rawRootElement.prototype.setAttribute\n ) {\n this.setAttribute(key, value)\n } else {\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|image)$/i.test(this.tagName)) ||\n // If it is the anchor tag,eg. <a href=\"#xxx\"/>, the path will not be completed\n (key === 'href' && /^(a)$/i.test(this.tagName) && !/^#/.test(value))\n )\n\n ) {\n const app = appInstanceMap.get(appName)\n const aHrefResolver = microApp?.options?.aHrefResolver\n if (key === 'href' && /^a$/i.test(this.tagName) && typeof aHrefResolver === 'function') {\n value = aHrefResolver(value, appName, app!.url)\n } else {\n value = CompletionPath(value, app!.url)\n }\n }\n globalEnv.rawSetAttribute.call(this, key, value)\n if (isImageElement(this) || isVideoElement(this) || isAudioElement(this)) {\n let includeCrossOrigin = false\n if (microApp?.options?.includeCrossOrigin && isFunction(microApp.options.includeCrossOrigin)) {\n includeCrossOrigin = microApp.options.includeCrossOrigin(value)\n }\n // @ts-ignore\n includeCrossOrigin && (node.crossOrigin = 'anonymous')\n }\n }\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 = this.__MICRO_APP_NAME__ || 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(rawRootNode.prototype, 'parentNode', {\n configurable: true,\n enumerable: true,\n get() {\n /**\n * hijack parentNode of html for with sandbox\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 = getIframeCurrentAppName() || getCurrentAppName()\n if (currentAppName && this === globalEnv.rawDocument.firstElementChild) {\n const microDocument = appInstanceMap.get(currentAppName)?.sandBox?.proxyWindow?.document\n if (microDocument) return microDocument\n }\n // NOTE: run after hijack html.parentNode\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 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 = this.__MICRO_APP_NAME__ || getIframeCurrentAppName() || getCurrentAppName()\n Array.from(this.children).forEach((child) => {\n if (isElement(child) && currentAppName) {\n updateElementInfo(child, currentAppName)\n }\n })\n }\n })\n\n // patch cloneNode\n rawRootNode.prototype.cloneNode = function cloneNode(deep?: boolean): Node {\n const clonedNode = globalEnv.rawCloneNode.call(this, deep)\n return updateElementInfo(clonedNode, this.__MICRO_APP_NAME__)\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 return updateElementInfo(element, getCurrentAppName())\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/jd-opensource/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(this: Document, 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(this: Document, 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(this: Document, 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(this: Document, 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 rawRootNode.prototype.appendChild = globalEnv.rawAppendChild\n rawRootNode.prototype.insertBefore = globalEnv.rawInsertBefore\n rawRootNode.prototype.replaceChild = globalEnv.rawReplaceChild\n rawRootNode.prototype.removeChild = globalEnv.rawRemoveChild\n rawRootNode.prototype.cloneNode = globalEnv.rawCloneNode\n rawRootElement.prototype.append = globalEnv.rawAppend\n rawRootElement.prototype.prepend = globalEnv.rawPrepend\n rawRootElement.prototype.querySelector = globalEnv.rawElementQuerySelector\n rawRootElement.prototype.querySelectorAll = globalEnv.rawElementQuerySelectorAll\n rawRootElement.prototype.setAttribute = globalEnv.rawSetAttribute\n rawDefineProperty(rawRootNode.prototype, 'parentNode', globalEnv.rawParentNodeDesc)\n rawDefineProperty(rawRootElement.prototype, 'innerHTML', globalEnv.rawInnerHTMLDesc)\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 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'\nimport {\n updateElementInfo,\n} from '../sandbox/adapter'\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 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: any\n rawDocument: any\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 const rawDocumentFragment = rawWindow.DocumentFragment\n\n // save patch raw methods, pay attention to this binding\n const rawAppendChild = rawRootNode.prototype.appendChild\n const rawInsertBefore = rawRootNode.prototype.insertBefore\n const rawReplaceChild = rawRootNode.prototype.replaceChild\n const rawRemoveChild = rawRootNode.prototype.removeChild\n const rawSetAttribute = rawRootElement.prototype.setAttribute\n const rawAppend = rawRootElement.prototype.append\n const rawPrepend = rawRootElement.prototype.prepend\n const rawFragmentAppend = rawDocumentFragment.prototype.append\n const rawFragmentPrepend = rawDocumentFragment.prototype.prepend\n const rawCloneNode = rawRootNode.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 // TODO: 将ImageProxy移出去\n const ImageProxy = new Proxy(rawWindow.Image, {\n construct (Target, args): HTMLImageElement {\n return updateElementInfo(new Target(...args), getCurrentAppName())\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 rawDocumentFragment,\n\n // source/patch\n rawSetAttribute,\n rawAppendChild,\n rawInsertBefore,\n rawReplaceChild,\n rawRemoveChild,\n rawAppend,\n rawPrepend,\n rawFragmentAppend,\n rawFragmentPrepend,\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 MicroAppElementInterface,\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} 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 initRouterMode,\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 HTMLElement implements MicroAppElementInterface {\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 private _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 /**\n * In FireFox, iframe Node.prototype will point to native Node.prototype after insert to document\n * If <micro-app>.prototype is not MicroAppElement.prototype, we should reset it\n */\n if (Object.getPrototypeOf(this) !== MicroAppElement.prototype) {\n Object.setPrototypeOf(this, MicroAppElement.prototype)\n }\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)\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)\n )\n ) {\n const formatNewName = formatAppName(newVal)\n\n if (!formatNewName) {\n return logError(`Invalid attribute name ${newVal}`, this.appName)\n }\n\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 attrs: Record<string, string> = {}\n Array.prototype.slice.call(this.attributes).forEach(({ name, value }: Attr) => {\n if (name.startsWith('data-')) {\n attrs[name] = value\n }\n })\n\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 attrs\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/jd-opensource/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 delete this.__MICRO_APP_NAME__\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 // TODO: 新版本路由系统要重新兼容ssr\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 initRouterMode(\n this.getAttribute('router-mode'),\n // is micro-app element set disable-memory-router, like <micro-app disable-memory-router></micro-app>\n // or <micro-app disable-memory-router='false'></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 * get delay time of router event\n * @returns delay time\n */\n public getRouterEventDelay (): number {\n let delay = parseInt(this.getAttribute('router-event-delay') as string)\n if (isNaN(delay)) {\n delay = parseInt((isFunction(microApp.options['router-event-delay']) ? microApp.options['router-event-delay'](this.appName) : microApp.options['router-event-delay']) as unknown as string)\n }\n return !isNaN(delay) ? delay : 0\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 set appName(value: string) {\n if (value !== this._appName) {\n microApp.changeEventAppName(value, this._appName)\n this._appName = value\n }\n }\n\n get appName(): string {\n return this._appName\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 window.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 isTargetExtension,\n} from './libs/utils'\nimport {\n fetchSource,\n} from './source/fetch'\nimport {\n initRouterMode,\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 * 如果要保留setTimeout,则需要考虑清空定时器的情况\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: initRouterMode(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) && isTargetExtension(path, 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 { 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 when unmountApp`)\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 const currentData = microApp.getData(appName)\n app.isReloading = true\n rootContainer.reload(destroy).then(() => {\n if (currentData) {\n microApp.setData(appName, currentData)\n }\n app.isReloading = false\n resolve(true)\n })\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 when reload app`)\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\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 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 (window.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","isPromise","isConstructor","targetStr","constructor","getOwnPropertyNames","length","test","isURL","URL","href","isElement","Element","tagName","isNode","Node","nodeType","isStyleElement","isScriptElement","isDocumentFragment","isMicroAppBody","toUpperCase","isTargetExtension","path","suffix","createURL","pathname","split","pop","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","Location","base","addProtocol","url","startsWith","location","protocol","formatAppURL","origin","search","port","host","rawWindow","newOrigin","fullPath","e","formatAppName","name","replace","getEffectivePath","pathArr","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","currentAppName","setCurrentAppName","getCurrentAppName","throttleDeferForSetAppName","getPreventSetState","iframeCurrentAppName","setIframeCurrentAppName","getIframeCurrentAppName","throttleDeferForIframeAppName","preventSetState","removeDomScope","force","pureCreateElement","options","element","rawDocument","document","createElement","__MICRO_APP_NAME__","__PURE_ELEMENT__","isInvalidQuerySelectorKey","key","isUniqueElement","getRootContainer","ShadowRoot","isShadowRoot","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","instanceOf","instance","proto","getPrototypeOf","formatEventList","formatEventType","type","dispatchLifecyclesEvent","lifecycleName","detail","container","event","CustomEvent","currentTarget","get","formatEventInfo","microApp","lifeCycles","dispatchEvent","dispatchCustomEventToMicroApp","app","eventName","sandBox","microAppWindow","fetchSource","fetch","text","HTMLLoader","getInstance","this","run","htmlUrl","ssrUrl","cache","htmlStr","onerror","Error","formatHTML","onLoadError","processHtml","plugins","match","code","mergedPlugins","modules","preCode","plugin","rootSelectorREG","bodySelectorREG","CSSParser","createMatcherForRuleWithChildRule","createMatcherForNoneBraceAtRule","exec","cssText","prefix","linkPath","matchRules","decodeURIComponent","reset","scopecssDisable","scopecssDisableNextLine","scopecssDisableSelectors","matchLeadingSpaces","matchComments","charAt","matchAtRule","matchStyleRule","selectors","formatSelector","recordResult","styleDeclarations","printError","skip","m","commonMatch","attributeValues","p1","p2","offset","mock","_","separator","selector","matchOpenBrace","matchAllDeclarations","matchCloseBrace","nesting","cssValue","all","$1","getLinkFileDir","keyframesRule","mediaRule","customMediaRule","supportsRule","importRule","charsetRule","namespaceRule","containerRule","documentRule","pageRule","hostRule","fontFaceRule","layerRule","keyframeRule","r","valList","commonHandlerForAtRuleWithSelfRule","reg","RegExp","matchComment","commentText","rule","matchArray","matchStr","strFragment","encodeURIComponent","reason","filename","parseError","commonAction","styleElement","__MICRO_APP_HAS_SCOPED__","parser","textContent","scopedCSS","scopecss","createPrefix","escapeRegExp","regStr","observer","MutationObserver","escapedPrefix","isPrefixed","disconnect","observe","childList","characterData","hasAttribute","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","GLOBAL_CACHED_KEY","PREFETCH_LEVEL","ROUTER_MODE_STATE","DEFAULT_ROUTER_MODE","ROUTER_MODE_NATIVE","ROUTER_MODE_NATIVE_SCOPE","ROUTER_MODE_PURE","ROUTER_MODE_LIST","BASE_SCOPE_WINDOW_EVENT","SCOPE_WINDOW_EVENT_OF_WITH","SCOPE_WINDOW_EVENT_OF_IFRAME","concat","BASE_SCOPE_WINDOW_ON_EVENT","SCOPE_WINDOW_ON_EVENT_OF_WITH","SCOPE_WINDOW_ON_EVENT_OF_IFRAME","SCOPE_DOCUMENT_EVENT","SCOPE_DOCUMENT_ON_EVENT","GLOBAL_KEY_TO_WINDOW","RAW_GLOBAL_TARGET","HIJACK_LOCATION_KEYS","scriptTypes","isTypeModule","scriptInfo","module","useSandbox","iframe","isInlineMode","inline","isSpecialScript","getEffectWindow","getParsedFunction","currentCode","parsedFunction","getExistParseResult","code2Function","getUniqueNonceSrc","nonceStr","random","substr","isWrapInSandBox","getSandboxType","extractScriptElement","src","checkExcludeUrl","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","throwError","excludeRunScriptFilter","newCode","processCode","usePlugins","configs","config","loader","flatBodyChildren","body","fiberStyleTasks","getElementsByTagName","dom","parentElement","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","changeEventAppName","newAppName","oldAppName","newEventName","oldEventName","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","BaseSandbox","staticScopeProperties","injectReactHMRProperty","CustomWindow","patchElementTree","children","childNodes","child","updateElementInfo","node","props","hrefDescriptor","getOwnPropertyDescriptor","hrefConfigurable","setAttribute","isIframeSandbox","ownerDocument","getIframeParentNodeDesc","rawParentNodeDesc","getRootNode","parentNodeDesc","customParent","getRootElementParentNode","inheritBaseBody","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","setPrototypeOf","createMicroDocument","Document","patchWindow","filter","patchWindowProperty","descriptorTargetMap","scopeProperties","rawWindowScopeKeyList","injectedKeys","descriptor","escapeProperties","staticEscapeProperties","escapeKeys","ownKeys","create","deleteProperty","createProxyWindow","intervalIdMap","timeoutIdMap","rawDispatchEvent","rawSetInterval","rawSetTimeout","rawClearInterval","rawClearTimeout","getEventTarget","setInterval","timeout","intervalId","setTimeoutHander","timeoutId","handlerWithCleanup","clearInterval","clearTimeout","clearTimer","patchWindowEffect","setMicroState","microState","targetLocation","rawState","history","state","additionalState","__MICRO_APP_STATE__","hash","mode","getRouterMode","removeMicroState","getMicroState","getMicroRouterInfoState","ENC_AD_RE","ENC_EQ_RE","DEC_AD_RE","DEC_EQ_RE","encodeMicroPath","commonDecode","decodeMicroPath","decPath","formatQueryAppName","getMicroPathFromURL","rawLocation","isRouterModeSearch","getQueryObjectFromURL","microPath","hashQuery","searchQuery","isRouterModeCustom","setMicroPathToURL","targetFullPath","isAttach2Hash","encodedMicroPath","baseHash","isRouterModeState","isRouterModePure","isEffectiveApp","routerMode","isRouterModeNative","isRouterModeNativeScope","initRouterMode","inlineDisableMemoryRouter","addHistoryListener","popStateHandler","getActiveApps","excludeHiddenApp","excludePreRender","onlyForBrowser","delay","macro","updateMicroLocationWithEvent","getRouterEventDelay","isHashChange","oldHref","oldHash","updateMicroLocation","newPopStateEvent","PopStateEvent","onpopstate","dispatchPopStateEventToMicroApp","newHashChangeEvent","HashChangeEvent","newURL","oldURL","onhashchange","dispatchHashChangeEventToMicroApp","dispatchNativeEvent","dispatchNativePopStateEvent","dispatchNativeHashChangeEvent","createMicroHistory","microLocation","rawHistory","getMicroHistoryMethod","methodName","rests","navigateWithNativeEvent","updateIframeBase","originalHistory","pushState","replaceState","go","delta","nativeHistoryNavigate","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","back","forward","beforeEach","afterEach","attachToURL","attachAllToURL","includeHiddenApp","includePreRender","defaultPageRecord","useMapRecord","setDefaultPage","removeDefaultPage","getDefaultPage","createDefaultPageApi","baseRouterProxy","setBaseAppRouter","baseRouter","getBaseAppRouter","createBaseRouterApi","createRouterApi","guardLocationKeys","createMicroLocation","childStaticLocation","browserHost","childHost","isIframe","withLocation","getTarget","commonHandler","proxyLocation","setMicroPathResult","reload","handleForPathNameAndSearch","targetPath","createLocationMethod","locationMethodName","forcedReload","createGuardLocation","guardLocation","oAssign","newLocation","targetHref","initRouteStateWithURL","defaultPage","removePathFromBrowser","updateBrowserURLWithLocation","autoTriggerNavigationGuard","clearRouteStateFromURL","keepRouteState","hashQueryStr","Number","Boolean","searchQueryStr","removeMicroPathFromURL","createMicroFetch","rawFetch","input","init","createMicroXMLHttpRequest","rawXMLHttpRequest","XMLHttpRequest","MicroXMLHttpRequest","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","clearHijackUmdHooks","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","actionsBeforeExecScripts","handleUmdHooks","hijackUmdHooks","mount","unmount","microAppLibrary","setStaticAppState","UN_PROXY_INSTANCEOF_KEYS","escape2RawWindowKeys","escape2RawWindowRegExpKeys","uniqueDocumentElement","proxy2RawDocOrShadowKeys","proxy2RawDocOrShadowMethods","proxy2RawDocumentKeys","proxy2RawDocumentMethods","EXCLUDE_URL_PROTOCOLS","originalWorker","Worker","WorkerProxy","construct","Target","scriptURL","parsedUrl","hostname","isSameOrigin","workerPath","blob","Blob","blobBuilder","BlobBuilder","WebKitBlobBuilder","MozBlobBuilder","MSBlobBuilder","append","getBlob","webkitURL","createObjectURL","urlFromScript","excludeRewriteIframeConstructor","rawValue","customProperties","escapeSandboxEvent","escapeIframeWindowEvents","microRootDocument","microDocument","rawMicroCreateElement","rawMicroCreateElementNS","rawMicroCreateTextNode","createTextNode","rawMicroCreateDocumentFragment","createDocumentFragment","rawMicroCreateComment","rawMicroQuerySelector","rawMicroQuerySelectorAll","querySelectorAll","rawMicroGetElementById","getElementById","rawMicroGetElementsByClassName","getElementsByClassName","rawMicroGetElementsByTagName","rawMicroGetElementsByName","getElementsByName","rawMicroElementFromPoint","elementFromPoint","rawMicroCaretRangeFromPoint","caretRangeFromPoint","getBindTarget","_this","x","y","range","getElementDocument","isWebComponentElement","patchDocumentPrototype","getCommonDescriptor","getter","createDescriptors","documentElement","scrollingElement","desc","patchDocumentProperty","bindTarget","createSetterHandler","__MICRO_APP_BOUND_FUNCTION__","patchDocumentEffect","disableIframeRootDocument","patchElement","rawRootElement","rawRootNode","microRootNode","microRootElement","microDocumentFragment","DocumentFragment","rawMicroAppendChild","rawMicroInsertBefore","insertBefore","rawMicroReplaceChild","rawMicroRemoveChild","rawMicroAppend","rawMicroPrepend","prepend","rawMicroFragmentAppend","rawMicroFragmentPrepend","rawMicroInsertAdjacentElement","insertAdjacentElement","rawMicroCloneNode","cloneNode","rawInnerHTMLDesc","rawOwnerDocumentDesc","isPureNode","isBaseElement","getRawTarget","microHead","head","oldChild","contains","nodes","hasPureNode","where","deep","elementImage","patchIframeNode","rawMicroSetAttribute","aHrefResolver","_url","excludeAssetFilter","protoAttrList","HTMLImageElement","HTMLScriptElement","HTMLLinkElement","SVGImageElement","patchIframeAttribute","IframeSandbox","baseElement","deleteIframeElement","createIframeElement","contentWindow","patchIframe","createIframeTemplate","childFullPath","scrollRestoration","browserPath","iframeAttrs","id","iframeSrc","style","createIframeBase","oldMicroDocument","iframeLocationReady","$dom","firstChild","clearDOM","innerHTML","CreateApp","CREATED","getInlineModeState","isReloading","loadSourceCode","createSandbox","setAppState","LOADING","loadSourceLevel","isUnmounted","LOAD_FAILED","appState","nextAction","BEFORE_MOUNT","cloneContainer","preRenderEvents","dispatchBeforeMount","BEFOREMOUNT","MOUNTING","handleMounted","umdHookMount","umdHookUnmount","getAppState","MOUNTED","initHook","deferScriptPromise","deferScriptInfo","errorCount","execScripts","umdHookMountResult","dispatchAction","actionsAfterMounted","getMicroAppGlobalHook","ONMOUNT","isHidden","unmountcb","UNMOUNT","handleUnmounted","umdHookUnmountResult","ONUNMOUNT","actionsAfterUnmounted","shouldClearData","clearOptions","setKeepAliveState","actionsForCompletelyDestroy","hiddenKeepAliveApp","KEEP_ALIVE_HIDDEN","AFTERHIDDEN","showKeepAliveApp","oldContainer","BEFORESHOW","KEEP_ALIVE_SHOW","AFTERSHOW","ERROR","htmlString","DOMParser","parseFromString","iframeOption","keepAliveState","getKeepAliveState","rawElementQuerySelectorAll","dynamicElementInMicroAppMap","WeakMap","getMappingNode","handleNewNode","linkReplaceComment","replaceStyle","originLink","handleDynamicLink","formatDynamicLink","originScript","dispatchScriptOnLoadEvent","runDynamicScript","runDynamicRemoteScript","runDynamicInlineScript","invokePrototypeMethod","rawMethod","targetNode","passiveNode","hijackParent","getHijackParent","rawRemoveChild","__MICRO_APP_HAS_DPN__","rawInsertBefore","indexOfParent","invokeRawMethod","rawAppendChild","rawAppend","rawPrepend","rawFragmentAppend","rawFragmentPrepend","commonElementHandler","newChild","hrefValue","nextHrefValue","completePathDynamic","isProxyDocument","rawQuerySelector","rawQuerySelectorAll","markElement","rawCreateDocumentFragment","rawCreateComment","rawGetElementById","rawGetElementsByClassName","rawGetElementsByTagName","rawGetElementsByName","rawDocumentFragment","getElementQueryTarget","getElementQueryResult","isEmpty","refChild","rawReplaceChild","rawCreateTextNode","isDocumentShadowRoot","processedEle","realParent","rawInsertAdjacentElement","isVideoElement","isAudioElement","includeCrossOrigin","crossOrigin","firstElementChild","rawCloneNode","releasePatchDocument","hasRejectMicroAppStyle","initGlobalEnv","rawRootEventTarget","EventTarget","__MICRO_APP_BASE_APPLICATION__","rejectMicroAppStyle","defineElement","MicroAppElement","HTMLElement","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","isNaN","_appName","publicPath","baseRoute","customElements","define","preFetch","apps","delayTime","prefetchDelay","preFetchAction","onLine","disableScopecss","disableSandbox","level","oldOnload","oldOnLoadError","onLoadParam","preFetchInSerial","fetchGlobalResources","resources","sourceHandler","effectiveResource","activeApps","getAllApps","unmountApp","clearAliveState","unmountHandler","afterhiddenHandler","destroyAttrValue","destoryAttrValue","removeAttribute","keepAliveAttrValue","clearDataAttrValue","unmountAllApps","rootContainer","currentData","renderApp","microAppElement","lifeCycleConfig","lifeName","toLowerCase","releaseListener","handleError","MicroApp","assets","hasInit","preFetchApps","globalAssets","js","css","formattedAppName"],"mappings":"sPAYaA,EAAU,QAGVC,EAA8B,o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