@xingtukeji/micro 1.1.22 → 1.1.24

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.
Files changed (2) hide show
  1. package/dist/index.js +408 -534
  2. package/package.json +14 -3
package/dist/index.js CHANGED
@@ -1,549 +1,423 @@
1
- (function(){"use strict";try{if(typeof document!="undefined"){var e=document.createElement("style");e.appendChild(document.createTextNode('.xt-micro{width:100%;height:100%;overflow:hidden;background-color:transparent}.xt-micro:before{content:"加载中";position:absolute;inset:0;display:flex;justify-content:center;align-items:center;z-index:-1}.micro-iframe{width:100%;height:100%;border:none;margin:0;padding:0}.micro-iframe:after{content:"加载中";position:absolute;inset:0;display:flex;justify-content:center;align-items:center;background:#fff}')),document.head.appendChild(e)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();
2
- var $ = Object.defineProperty, x = Object.defineProperties;
3
- var X = Object.getOwnPropertyDescriptors;
4
- var O = Object.getOwnPropertySymbols;
5
- var k = Object.prototype.hasOwnProperty, H = Object.prototype.propertyIsEnumerable;
6
- var M = (t, e, n) => e in t ? $(t, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[e] = n, m = (t, e) => {
7
- for (var n in e || (e = {}))
8
- k.call(e, n) && M(t, n, e[n]);
9
- if (O)
10
- for (var n of O(e))
11
- H.call(e, n) && M(t, n, e[n]);
12
- return t;
13
- }, R = (t, e) => x(t, X(e));
14
- var h = (t, e, n) => (M(t, typeof e != "symbol" ? e + "" : e, n), n);
15
- var w = (t, e, n) => new Promise((o, r) => {
16
- var a = (d) => {
17
- try {
18
- c(n.next(d));
19
- } catch (y) {
20
- r(y);
21
- }
22
- }, l = (d) => {
23
- try {
24
- c(n.throw(d));
25
- } catch (y) {
26
- r(y);
27
- }
28
- }, c = (d) => d.done ? o(d.value) : Promise.resolve(d.value).then(a, l);
29
- c((n = n.apply(t, e)).next());
1
+ (function(){try{if(typeof document<`u`){var e=document.createElement(`style`);e.appendChild(document.createTextNode(`.xt-micro{background-color:transparent;width:100%;height:100%;overflow:hidden}.micro-iframe{border:none;width:100%;height:100%;margin:0;padding:0}`)),document.head.appendChild(e)}}catch(e){console.error(`vite-plugin-css-injected-by-js`,e)}})();import { createElementBlock, defineComponent, mergeProps, onMounted, onUnmounted, openBlock, ref, watch } from "vue";
2
+ var __defProp = Object.defineProperty, __export = (h) => {
3
+ let z = {};
4
+ for (var B in h) __defProp(z, B, {
5
+ get: h[B],
6
+ enumerable: !0
7
+ });
8
+ return z;
9
+ };
10
+ const CONSTANT = {
11
+ KEY: "$xtm",
12
+ IS_MICRO: "__XT_MICRO",
13
+ MICRO_NAME: "__XT_MICRO_NAME",
14
+ MICRO_TYPE: "__XT_MICRO_TYPE",
15
+ MICRO_TOKEN: "__XT_MICRO_TOKEN",
16
+ MICRO_APP: "__XT_MICRO_APP",
17
+ DOM_ID_PREFIX: "xt-micro-ifr-",
18
+ URL_PARAM_PREFIX: "__XT_MICRO_",
19
+ MICRO_VERSION: "__XT_MICRO_VERSION"
20
+ }, version = "1.1.23";
21
+ var utils_exports = /* @__PURE__ */ __export({
22
+ ConsoleUtil: () => ConsoleUtil,
23
+ addOrReplaceUrlParam: () => addOrReplaceUrlParam,
24
+ anchorElementGenerator: () => anchorElementGenerator,
25
+ debounce: () => debounce,
26
+ getAbsolutePath: () => getAbsolutePath,
27
+ getAnchorElementQueryMap: () => getAnchorElementQueryMap,
28
+ getQueryParameter: () => getQueryParameter,
29
+ ipcSyncAppInfo: () => ipcSyncAppInfo
30
30
  });
31
- import { ref as b, defineComponent as j, watch as F, onMounted as K, onUnmounted as Y, openBlock as N, createElementBlock as V, mergeProps as B } from "vue";
32
- const s = {
33
- KEY: "$xtm",
34
- // 父应用注入子应用实例的key
35
- IS_MICRO: "__XT_MICRO",
36
- // 是否在微应用中
37
- MICRO_NAME: "__XT_MICRO_NAME",
38
- // 微应用名称
39
- MICRO_TYPE: "__XT_MICRO_TYPE",
40
- // 微应用类型 'parent' | 'child'
41
- MICRO_TOKEN: "__XT_MICRO_TOKEN",
42
- // 微应用token
43
- MICRO_APP: "__XT_MICRO_APP",
44
- // 微应用实例
45
- DOM_ID_PREFIX: "xt-micro-ifr-",
46
- // dom id前缀
47
- URL_PARAM_PREFIX: "__XT_MICRO_",
48
- // 微应用在 url 参数中的前缀
49
- MICRO_VERSION: "__XT_MICRO_VERSION"
50
- // 微应用版本
51
- }, f = "1.1.22";
52
- function _(t, e = window.location.href) {
53
- t = t.replace(/[\[\]]/g, "\\$&");
54
- var n = new RegExp("[?&]" + t + "(=([^&#]*)|&|#|$)"), o = n.exec(e);
55
- return o ? o[2] ? decodeURIComponent(o[2].replace(/\+/g, " ")).trim() : "" : null;
31
+ function getQueryParameter(h, z = window.location.href) {
32
+ h = h.replace(/[\[\]]/g, "\\$&");
33
+ var B = (/* @__PURE__ */ RegExp("[?&]" + h + "(=([^&#]*)|&|#|$)")).exec(z);
34
+ return B ? B[2] ? decodeURIComponent(B[2].replace(/\+/g, " ")).trim() : "" : null;
56
35
  }
57
- function S(t, e, n) {
58
- try {
59
- return t && (n && t.startsWith("#") ? t : new URL(t, e).href);
60
- } catch (o) {
61
- return t;
62
- }
36
+ function getAbsolutePath(h, z, B) {
37
+ try {
38
+ return h && (B && h.startsWith("#") ? h : new URL(h, z).href);
39
+ } catch {
40
+ return h;
41
+ }
63
42
  }
64
- function D(t) {
65
- const e = window.document.createElement("a");
66
- return e.href = t, e.href = e.href, e;
43
+ function anchorElementGenerator(h) {
44
+ let z = window.document.createElement("a");
45
+ return z.href = h, z.href = z.href, z;
67
46
  }
68
- function G(t) {
69
- const e = t.search || "";
70
- return [...new URLSearchParams(e).entries()].reduce((n, o) => (n[o[0]] = o[1], n), {});
47
+ function getAnchorElementQueryMap(h) {
48
+ let z = h.search || "";
49
+ return [...new URLSearchParams(z).entries()].reduce((h, z) => (h[z[0]] = z[1], h), {});
71
50
  }
72
- function W(t, e) {
73
- let n = null;
74
- return function(...o) {
75
- const r = this;
76
- n && clearTimeout(n), n = setTimeout(() => {
77
- t.apply(r, o);
78
- }, e);
79
- };
51
+ function debounce(h, z) {
52
+ let B = null;
53
+ return function(...V) {
54
+ let H = this;
55
+ B && clearTimeout(B), B = setTimeout(() => {
56
+ h.apply(H, V);
57
+ }, z);
58
+ };
80
59
  }
81
- function U(t, e, n) {
82
- const [o, r] = t.split("#"), a = new URL(o), l = a.searchParams;
83
- return e = s.URL_PARAM_PREFIX + e, l.has(e) ? l.set(e, n) : l.append(e, n), r && (a.hash = r), a.search = l.toString(), i.trace("urlObj", a), a.origin + a.pathname + a.search + a.hash;
60
+ function addOrReplaceUrlParam(h, z, B) {
61
+ let [V, H] = h.split("#"), U = new URL(V), W = U.searchParams;
62
+ return z = CONSTANT.URL_PARAM_PREFIX + z, W.has(z) ? W.set(z, B) : W.append(z, B), H && (U.hash = H), U.search = W.toString(), ConsoleUtil.trace("urlObj", U), U.origin + U.pathname + U.search + U.hash;
84
63
  }
85
- const E = (t) => w(void 0, null, function* () {
86
- return new Promise((e) => {
87
- window.addEventListener("message", (n) => {
88
- i.debug("child ipcSyncAppInfo receive message", n.data), n.data.cmd === "$xt/micro/info" && (n.data.data.mainMicroVersion !== f && i.warn(
89
- `子应用版本与主应用版本不一致,${t}子应用版本:${f},主应用版本:${n.data.data.mainMicroVersion}`
90
- ), e(n.data.data));
91
- }), i.debug("child ipcSyncAppInfo send message", t), window.parent.postMessage(
92
- {
93
- cmd: "$xt/micro/info",
94
- data: t
95
- },
96
- "*"
97
- );
98
- });
99
- }), u = class u {
100
- // 日志开关,默认为开启状态
101
- // private static enable = localStorage;
102
- /**
103
- * 从 localStorage 读取开关状态,默认开启
104
- */
105
- static get enable() {
106
- return localStorage.getItem(u.STORAGE_KEY) === "true";
107
- }
108
- /**
109
- * 设置开关状态并同步到 localStorage
110
- * @param status 是否开启日志
111
- */
112
- static setEnable(e) {
113
- localStorage.setItem(u.STORAGE_KEY, e.toString());
114
- }
115
- /**
116
- * 获取当前日志开关状态
117
- * @returns 当前开关状态
118
- */
119
- static getEnable() {
120
- return u.enable;
121
- }
122
- /**
123
- * 提取调用日志的文件路径和行号
124
- * @returns 格式化的位置信息(如 "src/utils/xxx.ts:123")
125
- */
126
- static getCallerInfo() {
127
- try {
128
- const o = (new Error().stack || "").split(`
129
- `).slice(4);
130
- if (o.length === 0)
131
- return "unknown location";
132
- const r = o[0].trim(), a = r.match(/(?:http[s]?:\/\/.*?\/|)([^:]+):(\d+):(\d+)/);
133
- if (a) {
134
- const [, l, c] = a;
135
- return `[${l.split("/").slice(-2).join("/")}:${c}]`;
136
- }
137
- return `[${r}]`;
138
- } catch (e) {
139
- return "[unknown location]";
140
- }
141
- }
142
- /**
143
- * 通用日志输出方法(内部使用)
144
- * @param type 日志类型(log/info/warn/error 等)
145
- * @param args 日志参数
146
- */
147
- static _log(e, ...n) {
148
- if (u.enable && typeof console[e] == "function") {
149
- const o = this.getCallerInfo();
150
- console[e](o, ...n);
151
- }
152
- }
153
- // 以下为常用日志方法封装,与 console 用法一致
154
- static log(...e) {
155
- this._log("log", ...e);
156
- }
157
- static info(...e) {
158
- this._log("info", ...e);
159
- }
160
- static warn(...e) {
161
- this._log("warn", ...e);
162
- }
163
- static error(...e) {
164
- this._log("error", ...e);
165
- }
166
- static debug(...e) {
167
- this._log("debug", ...e);
168
- }
169
- static trace(...e) {
170
- this._log("trace", ...e);
171
- }
172
- static table(e, n) {
173
- this.enable && console.table(e, n);
174
- }
175
- static time(e) {
176
- this.enable && console.time(e);
177
- }
178
- static timeEnd(e) {
179
- this.enable && console.timeEnd(e);
180
- }
181
- };
182
- // 存储在 localStorage 中的键名
183
- h(u, "STORAGE_KEY", "@xt/micro/console/enable");
184
- let i = u;
185
- const de = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
186
- __proto__: null,
187
- ConsoleUtil: i,
188
- addOrReplaceUrlParam: U,
189
- anchorElementGenerator: D,
190
- debounce: W,
191
- getAbsolutePath: S,
192
- getAnchorElementQueryMap: G,
193
- getQueryParameter: _,
194
- ipcSyncAppInfo: E
195
- }, Symbol.toStringTag, { value: "Module" })), C = b(!1);
196
- Object.defineProperty(window, s.IS_MICRO, {
197
- get: function() {
198
- return C.value;
199
- },
200
- set: function(t) {
201
- C.value = t;
202
- }
64
+ const ipcSyncAppInfo = async (h) => new Promise((z) => {
65
+ window.addEventListener("message", (B) => {
66
+ ConsoleUtil.trace("child ipcSyncAppInfo receive message", B.data), B.data.cmd === "$xt/micro/info" && (B.data.data.mainMicroVersion !== "1.1.23" && ConsoleUtil.warn(`子应用版本与主应用版本不一致,${h}子应用版本:${version},主应用版本:${B.data.data.mainMicroVersion}`), z(B.data.data));
67
+ }), ConsoleUtil.trace("child ipcSyncAppInfo send message", h), window.parent.postMessage({
68
+ cmd: "$xt/micro/info",
69
+ data: h
70
+ }, "*");
203
71
  });
204
- const P = (t) => `${s.DOM_ID_PREFIX}${t}`, L = (t, e = !1) => {
205
- function n(c) {
206
- return c !== null && typeof c == "object" && !Array.isArray(c);
207
- }
208
- const o = typeof t.params == "function" ? t.params() : n(t.params) ? t.params : {}, r = typeof t.token == "function" ? t.token() : n(t.token) ? t.token : "", a = new URL(
209
- t.url.indexOf("http") > -1 ? t.url : window.location.origin + t.url
210
- ), l = _(s.URL_PARAM_PREFIX + t.name);
211
- if (!e && l) {
212
- const c = S(l, t.url, !0);
213
- if (c) {
214
- const d = new URL(c, t.url);
215
- d.searchParams.forEach((A, v) => {
216
- a.searchParams.set(v, A);
217
- }), a.hash = d.hash;
218
- }
219
- g(t.name);
220
- }
221
- if (a.searchParams.set(s.IS_MICRO, !0 + ""), a.searchParams.set(s.MICRO_NAME, t.name), r && a.searchParams.set(s.MICRO_TOKEN, r), o)
222
- for (let c of Object.keys(o))
223
- a.searchParams.set(c, o[c]);
224
- return g(t.name), a.href;
225
- }, q = () => {
226
- const t = document.createElement("div");
227
- return t.innerHTML = "应用加载中...", t.style.textAlign = "center", t.style.lineHeight = "100px", t.style.fontSize = "20px", t.style.color = "#999", t.style.position = "absolute", t.style.top = "0", t.style.left = "0", t.style.right = "0", t.style.bottom = "0", t.style.zIndex = "999", t.style.background = "transparent", t.style["mix-blend-mode"] = "difference", t;
228
- }, z = (t) => {
229
- t.style.opacity = "0", setTimeout(() => {
230
- t.remove();
231
- }, 500);
232
- }, Q = (t) => {
233
- const e = document.createElement("iframe");
234
- e.id = P(t.app.name);
235
- const n = L(t.app);
236
- e.src = n, e.style.width = "100%", e.style.height = "100%", e.style.border = "none", e.style.margin = "0", e.style.padding = "0", e.style.backgroundColor = "transparent", e.style["color-scheme"] = "unset", e.style.visibility = "hidden", e.addEventListener("load", (r) => (e.style.visibility = "visible", t.onLoad.call(t, r))), e.addEventListener(
237
- "error",
238
- (r) => t.onError.call(t, r)
239
- ), e.addEventListener(
240
- "unload",
241
- (r) => t.onUnload.call(t, r)
242
- );
243
- const o = new MutationObserver((r) => {
244
- i.log("监听 body 中子节点的变化2", t.panel), r.forEach((a) => {
245
- Array.from(a.removedNodes).includes(e) && (t.onUnload(new Event("unload")), o.disconnect());
246
- });
247
- });
248
- return o.observe(t.panel.parentNode, {
249
- childList: !0,
250
- subtree: !1
251
- }), e;
72
+ var ConsoleUtil = class h {
73
+ static STORAGE_KEY = "@xt/micro/console/enable";
74
+ static get enable() {
75
+ return localStorage.getItem(h.STORAGE_KEY) === "true";
76
+ }
77
+ static setEnable(z) {
78
+ localStorage.setItem(h.STORAGE_KEY, z.toString());
79
+ }
80
+ static getEnable() {
81
+ return h.enable;
82
+ }
83
+ static getCallerInfo() {
84
+ try {
85
+ let h = /* @__PURE__ */ ((/* @__PURE__ */ Error()).stack || "").split("\n").slice(4);
86
+ if (h.length === 0) return "unknown location";
87
+ let z = h[0].trim(), B = z.match(/(?:http[s]?:\/\/.*?\/|)([^:]+):(\d+):(\d+)/);
88
+ if (B) {
89
+ let [, h, z] = B;
90
+ return `[${h.split("/").slice(-2).join("/")}:${z}]`;
91
+ }
92
+ return `[${z}]`;
93
+ } catch {
94
+ return "[unknown location]";
95
+ }
96
+ }
97
+ static _log(z, ...B) {
98
+ if (h.enable && typeof console[z] == "function") {
99
+ let h = this.getCallerInfo();
100
+ console[z](h, ...B);
101
+ }
102
+ }
103
+ static log(...h) {
104
+ this._log("log", ...h);
105
+ }
106
+ static info(...h) {
107
+ this._log("info", ...h);
108
+ }
109
+ static warn(...h) {
110
+ this._log("warn", ...h);
111
+ }
112
+ static error(...h) {
113
+ this._log("error", ...h);
114
+ }
115
+ static debug(...h) {
116
+ this._log("debug", ...h);
117
+ }
118
+ static trace(...h) {
119
+ this._log("trace", ...h);
120
+ }
121
+ static table(h, z) {
122
+ this.enable && console.table(h, z);
123
+ }
124
+ static time(h) {
125
+ this.enable && console.time(h);
126
+ }
127
+ static timeEnd(h) {
128
+ this.enable && console.timeEnd(h);
129
+ }
130
+ }, _isMicro = ref(!1);
131
+ Object.defineProperty(window, CONSTANT.IS_MICRO, {
132
+ get: function() {
133
+ return _isMicro.value;
134
+ },
135
+ set: function(h) {
136
+ _isMicro.value = h;
137
+ }
138
+ });
139
+ var generateId = (h) => `${CONSTANT.DOM_ID_PREFIX}${h}`, generateURL = (h, z = !1) => {
140
+ function B(h) {
141
+ return typeof h == "object" && !!h && !Array.isArray(h);
142
+ }
143
+ let V = typeof h.params == "function" ? h.params() : B(h.params) ? h.params : {}, H = typeof h.token == "function" ? h.token() : B(h.token) ? h.token : "", U = new URL(h.url.indexOf("http") > -1 ? h.url : window.location.origin + h.url), W = getQueryParameter(CONSTANT.URL_PARAM_PREFIX + h.name);
144
+ if (!z && W) {
145
+ let z = getAbsolutePath(W, h.url, !0);
146
+ if (z) {
147
+ let B = new URL(z, h.url);
148
+ B.searchParams.forEach((h, z) => {
149
+ U.searchParams.set(z, h);
150
+ }), U.hash = B.hash;
151
+ }
152
+ clearParentUrl(h.name);
153
+ }
154
+ if (U.searchParams.set(CONSTANT.IS_MICRO, "true"), U.searchParams.set(CONSTANT.MICRO_NAME, h.name), H && U.searchParams.set(CONSTANT.MICRO_TOKEN, H), V) for (let h of Object.keys(V)) U.searchParams.set(h, V[h]);
155
+ return clearParentUrl(h.name), U.href;
156
+ }, generateLoading = (h) => {
157
+ ConsoleUtil.log("generateLoading", h);
158
+ let z = document.createElement("div");
159
+ return z.id = generateId(h) + "-loading", z.innerHTML = "应用加载中...", z.style.textAlign = "center", z.style.lineHeight = "100px", z.style.fontSize = "20px", z.style.color = "#999", z.style.position = "absolute", z.style.top = "0", z.style.left = "0", z.style.right = "0", z.style.bottom = "0", z.style.zIndex = "999", z.style.background = "transparent", z.style["mix-blend-mode"] = "difference", z;
160
+ }, removeLoading = (h) => {
161
+ h.style.opacity = "0", setTimeout(() => {
162
+ document.querySelectorAll("#" + h.id).forEach((h) => {
163
+ h.remove();
164
+ });
165
+ }, 500);
166
+ }, generateIframe = (h) => {
167
+ let z = document.createElement("iframe");
168
+ z.id = generateId(h.app.name), z.src = generateURL(h.app), z.style.width = "100%", z.style.height = "100%", z.style.border = "none", z.style.margin = "0", z.style.padding = "0", z.style.backgroundColor = "transparent", z.style["color-scheme"] = "unset", z.style.visibility = "hidden", z.addEventListener("load", (B) => (z.style.visibility = "visible", h.onLoad.call(h, B))), z.addEventListener("error", (z) => h.onError.call(h, z)), z.addEventListener("unload", (z) => h.onUnload.call(h, z));
169
+ let B = new MutationObserver((V) => {
170
+ ConsoleUtil.trace("监听 body 中子节点的变化2", h.panel), V.forEach((V) => {
171
+ Array.from(V.removedNodes).includes(z) && (h.onUnload(new Event("unload")), B.disconnect());
172
+ });
173
+ });
174
+ return B.observe(h.panel.parentNode, {
175
+ childList: !0,
176
+ subtree: !1
177
+ }), z;
178
+ }, MicroApp = class {
179
+ app;
180
+ dom;
181
+ panel;
182
+ loading;
183
+ loadingTimer;
184
+ constructor(h) {
185
+ return this.app = h, this.dom = void 0, this.panel = void 0, h.preload && this.preload(), this;
186
+ }
187
+ mount(h, z = !1) {
188
+ let B;
189
+ if (h ? (B = typeof h == "string" ? document.querySelector(h) : h, B.innerHTML = "") : B = document.body, B) {
190
+ this.panel = B;
191
+ let h = !0, V = document.getElementById(generateId(this.app.name));
192
+ if (V || (h = !1, V = generateIframe(this), this.dom = V), z ? V.style.display = "none" : V.style.removeProperty("display"), !z) {
193
+ let h = generateLoading(this.app.name);
194
+ this.loading = h, B.appendChild(h);
195
+ }
196
+ ConsoleUtil.trace("micro app", this.app.name, h ? "已加载迁移 dom" : "首次加载"), B.appendChild(V);
197
+ } else throw Error("没有找到转载子元素的父容器");
198
+ }
199
+ unmount() {
200
+ ConsoleUtil.trace("micro unmount app", this.app.name);
201
+ let h = document.getElementById(generateId(this.app.name));
202
+ if (h) this.app.preload ? (h.style.display = "none", document.body.appendChild(h)) : this.panel?.removeChild(h);
203
+ else throw Error("app dom not found");
204
+ }
205
+ preloadRender(h) {
206
+ this.mount(h);
207
+ }
208
+ preload() {
209
+ this.mount(void 0, !0);
210
+ }
211
+ reload(h = !1) {
212
+ let z = this.dom.src;
213
+ h && (z = generateURL(this.app, !0), ConsoleUtil.trace("go home", z)), ConsoleUtil.trace("reload app", this.app, z);
214
+ let B = new URL(z);
215
+ B.searchParams.set("__t", Date.now().toString()), this.dom.style.visibility = "hidden", this.dom.src = B.toString();
216
+ }
217
+ changeOptions(h) {
218
+ ConsoleUtil.trace("changeOptions", this.app, h), this.app = {
219
+ ...this.app,
220
+ ...h
221
+ };
222
+ }
223
+ onLoad(h) {
224
+ ConsoleUtil.trace("app onLoad", this.app.name, this.loadingTimer, this.loading), this.loadingTimer && clearTimeout(this.loadingTimer), this.loading && removeLoading(this.loading), _postMicro(this), ConsoleUtil.trace("this.app.onLoad", this.app.onLoad), this.app.onLoad && this.app.onLoad(h, this);
225
+ }
226
+ onUnload(h) {
227
+ ConsoleUtil.trace("app onUnload", this.app.name), clearParentUrl(this.app.name), this.app.onUnload && this.app.onUnload(h, this);
228
+ }
229
+ onError(h) {
230
+ ConsoleUtil.error("app onError", this.app.name), this.app.onError && this.app.onError(h, this);
231
+ }
232
+ }, _postMicro = (h) => {
233
+ h.dom?.contentWindow?.postMessage({
234
+ cmd: `$xt/micro/${h.app.name}`,
235
+ data: {
236
+ name: h.app.name,
237
+ url: h.app.url,
238
+ preload: h.app.preload,
239
+ sync: h.app.sync || !0
240
+ }
241
+ }, "*");
242
+ };
243
+ const mainMicroInit = () => {
244
+ window[CONSTANT.MICRO_TYPE] = "parent", window.addEventListener("message", (h) => {
245
+ if (h.data.cmd === "$xt/micro/sync") {
246
+ ConsoleUtil.trace("父页面接受子应用同步路由信息", h.data);
247
+ let z = [
248
+ CONSTANT.IS_MICRO,
249
+ CONSTANT.MICRO_NAME,
250
+ CONSTANT.MICRO_TOKEN
251
+ ], B = new URL(window.decodeURIComponent(h.data.data.url), h.origin);
252
+ for (let h of z) B.searchParams.delete(h);
253
+ ConsoleUtil.trace("tempUrl", B);
254
+ let V = clearParentUrl(h.data.data.name), H = new URL(V);
255
+ H.searchParams.forEach((h, z) => {
256
+ z.startsWith(CONSTANT.URL_PARAM_PREFIX) && H.searchParams.delete(z);
257
+ }), ConsoleUtil.trace("mainURL.href", H.href);
258
+ let U = addOrReplaceUrlParam(H.href, h.data.data.name, B.href);
259
+ ConsoleUtil.trace("curUrl", U), window.history.replaceState(null, "", U);
260
+ } else if (h.data.cmd === "$xt/micro/info") {
261
+ ConsoleUtil.trace("parent 「$xt/micro/info」 receive message", h.data);
262
+ let z = getApp(h.data.data);
263
+ h.source.postMessage({
264
+ cmd: "$xt/micro/info",
265
+ data: {
266
+ mainLocation: {
267
+ origin: window.location.origin,
268
+ href: window.location.href,
269
+ pathname: window.location.pathname,
270
+ search: window.location.search,
271
+ hash: window.location.hash,
272
+ host: window.location.host,
273
+ hostname: window.location.hostname,
274
+ port: window.location.port,
275
+ protocol: window.location.protocol
276
+ },
277
+ mainMicroVersion: version,
278
+ name: z.name,
279
+ url: z.url,
280
+ params: z.params,
281
+ sync: z.sync,
282
+ preload: z.preload
283
+ }
284
+ }, { targetOrigin: h.origin });
285
+ }
286
+ });
287
+ }, microInit = async (h = {}) => {
288
+ window[CONSTANT.MICRO_TYPE] = "child";
289
+ let z = getQueryParameter(CONSTANT.IS_MICRO), B = getQueryParameter(CONSTANT.MICRO_NAME);
290
+ if (ConsoleUtil.trace("child microInit", z, B), z && (window[CONSTANT.IS_MICRO] = z === "true", B && await syncAppInfo(B)), window[CONSTANT.IS_MICRO]) {
291
+ function z(h) {
292
+ var z = document.styleSheets[0];
293
+ if (!z) {
294
+ var B = document.createElement("style");
295
+ document.head.appendChild(B), z = B.sheet;
296
+ }
297
+ z.insertRule(h, z.cssRules.length);
298
+ }
299
+ window[CONSTANT.IS_MICRO] && h.hideHeaderCssSelector && (Array.isArray(h.hideHeaderCssSelector) ? h.hideHeaderCssSelector.forEach((h) => {
300
+ z(`${h} { display: none !important; }`);
301
+ }) : z(`${h.hideHeaderCssSelector} { display: none !important; }`)), await patchIframeHistory(B, window), window.addEventListener("message", async (h) => {
302
+ h.data.cmd === `$xt/micro/${B}` && syncUrlToWindow(B);
303
+ });
304
+ let V = getQueryParameter(CONSTANT.MICRO_TOKEN);
305
+ h.authHandler && V && await h.authHandler(V);
306
+ } else ConsoleUtil.warn("当前环境非微应用环境");
252
307
  };
253
- class J {
254
- constructor(e) {
255
- h(this, "app");
256
- h(this, "dom");
257
- h(this, "panel");
258
- h(this, "loading");
259
- h(this, "loadingTimer");
260
- return this.app = e, this.dom = void 0, this.panel = void 0, e.preload && this.preload(), this;
261
- }
262
- mount(e, n = !1) {
263
- let o;
264
- if (e ? (typeof e == "string" ? o = document.querySelector(e) : o = e, o.innerHTML = "") : o = document.body, o) {
265
- this.panel = o;
266
- let r = document.getElementById(P(this.app.name));
267
- r || (r = Q(this), this.dom = r), n ? r.style.display = "none" : r.style.removeProperty("display");
268
- const a = q();
269
- this.loadingTimer = setTimeout(() => {
270
- this.loading = a, o.appendChild(a);
271
- }, 1e3), o.appendChild(r);
272
- } else
273
- throw new Error("el not found");
274
- }
275
- unmount() {
276
- var n;
277
- i.debug("micro unmount app", this.app.name);
278
- const e = document.getElementById(P(this.app.name));
279
- if (e)
280
- this.app.preload ? (e.style.display = "none", document.body.appendChild(e)) : (n = this.panel) == null || n.removeChild(e);
281
- else
282
- throw new Error("app dom not found");
283
- }
284
- /**
285
- * 预加载渲染
286
- * TODO 还差用户切走之后,如何将ifr还原回去,等待下次载入
287
- * @param el 挂载dom对象
288
- */
289
- preloadRender(e) {
290
- this.mount(e);
291
- }
292
- /**
293
- * 预加载app,先放到body,待启动时,挪过来
294
- */
295
- preload() {
296
- this.mount(void 0, !0);
297
- }
298
- reload(e = !1) {
299
- let n = this.dom.src;
300
- e && (n = L(this.app, !0), i.log("go home", n)), i.log("reload app", this.app, n);
301
- const o = new URL(n);
302
- o.searchParams.set("__t", Date.now().toString()), this.dom.style.visibility = "hidden", this.dom.src = o.toString();
303
- }
304
- changeOptions(e) {
305
- i.log("changeOptions", this.app, e), this.app = m(m({}, this.app), e);
306
- }
307
- onLoad(e) {
308
- i.debug("app onLoad", this.app.name), this.loadingTimer && clearTimeout(this.loadingTimer), this.loading && z(this.loading), Z(this), i.log("this.app.onLoad", this.app.onLoad), this.app.onLoad && this.app.onLoad(e, this);
309
- }
310
- onUnload(e) {
311
- i.debug("app onUnload", this.app.name), g(this.app.name), this.app.onUnload && this.app.onUnload(e, this);
312
- }
313
- onError(e) {
314
- i.error("app onError", this.app.name), this.app.onError && this.app.onError(e, this);
315
- }
308
+ function patchIframeHistory(h, z) {
309
+ let B = z.history, V = B.pushState, H = B.replaceState;
310
+ B.pushState = function(z, H, U) {
311
+ let W = {
312
+ ...B.state || {},
313
+ ...z,
314
+ _patchedByParent: !0
315
+ };
316
+ V.call(B, W, H, U), syncUrlToWindow(h);
317
+ }, B.replaceState = function(h, z, V) {
318
+ let U = {
319
+ ...B.state || {},
320
+ ...h,
321
+ _patchedByParent: !0
322
+ };
323
+ H.call(B, U, z, V);
324
+ };
316
325
  }
317
- const Z = (t) => {
318
- var e, n;
319
- (n = (e = t.dom) == null ? void 0 : e.contentWindow) == null || n.postMessage(
320
- {
321
- cmd: `$xt/micro/${t.app.name}`,
322
- data: {
323
- name: t.app.name,
324
- url: t.app.url,
325
- preload: t.app.preload,
326
- sync: t.app.sync || !0
327
- // params: app.params
328
- }
329
- },
330
- "*"
331
- );
332
- }, ee = () => {
333
- window[s.MICRO_TYPE] = "parent", window.addEventListener("message", (t) => {
334
- if (t.data.cmd === "$xt/micro/sync") {
335
- i.log("父页面接受子应用同步路由信息", t.data);
336
- const e = [
337
- s.IS_MICRO,
338
- s.MICRO_NAME,
339
- s.MICRO_TOKEN
340
- ], n = new URL(
341
- window.decodeURIComponent(t.data.data.url),
342
- t.origin
343
- );
344
- for (let l of e)
345
- n.searchParams.delete(l);
346
- i.log("tempUrl", n);
347
- const o = g(t.data.data.name), r = new URL(o);
348
- r.searchParams.forEach((l, c) => {
349
- c.startsWith(s.URL_PARAM_PREFIX) && r.searchParams.delete(c);
350
- }), i.log("mainURL.href", r.href);
351
- const a = U(
352
- r.href,
353
- t.data.data.name,
354
- n.href
355
- // tempUrl.pathname + tempUrl.search + tempUrl.hash
356
- );
357
- i.log("curUrl", a), window.history.replaceState(null, "", a);
358
- } else if (t.data.cmd === "$xt/micro/info") {
359
- i.debug("parent 「$xt/micro/info」 receive message", t.data);
360
- const e = I(t.data.data);
361
- t.source.postMessage(
362
- {
363
- cmd: "$xt/micro/info",
364
- data: {
365
- mainLocation: {
366
- origin: window.location.origin,
367
- href: window.location.href,
368
- pathname: window.location.pathname,
369
- search: window.location.search,
370
- hash: window.location.hash,
371
- host: window.location.host,
372
- hostname: window.location.hostname,
373
- port: window.location.port,
374
- protocol: window.location.protocol
375
- },
376
- mainMicroVersion: f,
377
- name: e.name,
378
- url: e.url,
379
- params: e.params,
380
- sync: e.sync,
381
- preload: e.preload
382
- }
383
- },
384
- { targetOrigin: t.origin }
385
- );
386
- }
387
- });
388
- }, me = (...e) => w(void 0, [...e], function* (t = {}) {
389
- window[s.MICRO_TYPE] = "child";
390
- const n = _(s.IS_MICRO), o = _(s.MICRO_NAME);
391
- if (i.debug("child microInit", n, o), n && (window[s.IS_MICRO] = n === "true"), o && E(o).then((r) => {
392
- window[s.MICRO_APP] = m({
393
- microVersion: f
394
- }, r);
395
- }), window[s.IS_MICRO]) {
396
- let r = function(l) {
397
- var c = document.styleSheets[0];
398
- if (!c) {
399
- var d = document.createElement("style");
400
- document.head.appendChild(d), c = d.sheet;
401
- }
402
- c.insertRule(l, c.cssRules.length);
403
- };
404
- window[s.IS_MICRO] && t.hideHeaderCssSelector && (Array.isArray(t.hideHeaderCssSelector) ? t.hideHeaderCssSelector.forEach((l) => {
405
- r(`${l} { display: none !important; }`);
406
- }) : r(
407
- `${t.hideHeaderCssSelector} { display: none !important; }`
408
- )), yield te(o, window), window.addEventListener("message", (l) => w(void 0, null, function* () {
409
- l.data.cmd === `$xt/micro/${o}` && T(o);
410
- }));
411
- const a = _(s.MICRO_TOKEN);
412
- t.authHandler && a && (yield t.authHandler(a));
413
- } else
414
- i.warn("当前环境非微应用环境");
326
+ var syncAppInfo = async (h) => await ipcSyncAppInfo(h).then((h) => {
327
+ window[CONSTANT.MICRO_APP] = {
328
+ microVersion: version,
329
+ ...h
330
+ };
415
331
  });
416
- function te(t, e) {
417
- const n = e.history, o = n.pushState, r = n.replaceState;
418
- n.pushState = function(a, l, c) {
419
- const d = R(m(m({}, n.state || {}), a), {
420
- // 添加新数据
421
- _patchedByParent: !0
422
- // 可选:标记这是被父窗口修改的状态
423
- });
424
- o.call(n, d, l, c), T(t);
425
- }, n.replaceState = function(a, l, c) {
426
- const d = R(m(m({}, n.state || {}), a), {
427
- // 添加新数据
428
- _patchedByParent: !0
429
- // 可选:标记这是被父窗口修改的状态
430
- });
431
- r.call(n, d, l, c);
432
- };
332
+ async function syncUrlToWindow(h) {
333
+ ConsoleUtil.trace("syncUrlToWindow", h, window[CONSTANT.MICRO_APP]), window[CONSTANT.MICRO_APP] || syncAppInfo(h);
334
+ let { name: z, sync: B, mainLocation: V } = window[CONSTANT.MICRO_APP], H = window.location.pathname + window.location.search + window.location.hash;
335
+ ConsoleUtil.trace("curUrl", H), ConsoleUtil.trace("child", "「$xt/micro/sync」", "send", z, H), window.parent.postMessage({
336
+ cmd: "$xt/micro/sync",
337
+ data: {
338
+ name: z,
339
+ url: window.encodeURIComponent(H)
340
+ }
341
+ }, V.origin);
433
342
  }
434
- function T(t) {
435
- return w(this, null, function* () {
436
- i.log("syncUrlToWindow", t, window[s.MICRO_APP]), window[s.MICRO_APP] || (yield E(t).then((a) => {
437
- window[s.MICRO_APP] = m({
438
- microVersion: f
439
- }, a);
440
- }));
441
- const { name: e, sync: n, mainLocation: o } = window[s.MICRO_APP], r = window.location.pathname + window.location.search + window.location.hash;
442
- i.log("curUrl", r), window.parent.postMessage(
443
- {
444
- cmd: "$xt/micro/sync",
445
- data: {
446
- name: e,
447
- url: window.encodeURIComponent(r)
448
- }
449
- },
450
- o.origin
451
- );
452
- });
453
- }
454
- let p = {};
455
- const ne = {
456
- url: "",
457
- name: "",
458
- sync: !0
459
- }, he = (t) => {
460
- if (!t.url || t.url === "" || t.url === "undefined") {
461
- i.error("app url is required", t);
462
- return;
463
- }
464
- const e = Object.assign({}, ne, t), n = p[t.name];
465
- return n ? p[t.name] = m(m({}, n), e) : p[t.name] = R(m({}, e), {
466
- instance: new J(t)
467
- }), p[t.name];
468
- }, I = (t) => p[t], oe = (t, e) => p[t.name] = m(m({}, t), e), re = (t, e) => new Promise((n, o) => {
469
- let r = I(t);
470
- r ? (e && (r.instance.changeOptions(e), r = oe(r, e)), r.preload ? r.instance.preloadRender(r.el) : r.instance.mount(r.el), n(r)) : o("app not found, please setup app first");
471
- }), ae = (t) => {
472
- let e = I(t);
473
- e && e.instance.unmount();
474
- }, ue = (t, e = !1) => {
475
- let n = I(t);
476
- n && n.instance.reload(e);
477
- }, g = (t) => {
478
- i.log(
479
- "clearParentUrl",
480
- t,
481
- s.URL_PARAM_PREFIX + t
482
- );
483
- const e = window.location.href.split("#");
484
- i.log("url", e);
485
- let n = new URL(e[0]);
486
- n.searchParams.delete(s.URL_PARAM_PREFIX + t);
487
- const o = e.length > 1 ? n.href + "#" + e[1] : n.href;
488
- return window.history.replaceState({}, "", o), o;
489
- }, ie = () => window[s.IS_MICRO] === !0, pe = () => window[s.MICRO_TYPE] === "parent", fe = (t, e = ((n) => (n = window.__XT_MICRO_APP) == null ? void 0 : n.name)()) => {
490
- let o = window.location;
491
- if (ie())
492
- o = window.__XT_MICRO_APP.mainLocation;
493
- else if (!e) {
494
- i.error("在主应用中需要传入应用名称");
495
- return;
496
- }
497
- return `${o.origin}${o.pathname}?__XT_MICRO_${e}=${encodeURIComponent(t)}${o.hash}`;
498
- }, se = /* @__PURE__ */ j({
499
- __name: "XTMicroView",
500
- props: {
501
- appId: String
502
- },
503
- setup(t) {
504
- const e = t, n = b(), o = () => {
505
- e.appId && re(e.appId, {
506
- el: n.value,
507
- onUnload(r, a) {
508
- i.log("on unload", a.app.name);
509
- }
510
- }).then((r) => {
511
- i.debug("app mounted", e.appId);
512
- });
513
- };
514
- return F(() => e.appId, (r, a) => {
515
- r !== a && a && ae(a), o();
516
- }), K(() => {
517
- o();
518
- }), Y(() => {
519
- i.debug("「micro」", "app unmount", e.appId), g(e.appId);
520
- }), (r, a) => (N(), V("div", B({
521
- ref_key: "refPanel",
522
- ref: n
523
- }, r.$attrs, { class: "xt-micro" }), null, 16));
524
- }
525
- });
526
- window[s.MICRO_VERSION] = f;
527
- window.micro_api = {
528
- debug: i.setEnable
343
+ var _apps = {}, defaultAppOption = {
344
+ url: "",
345
+ name: "",
346
+ sync: !0,
347
+ preload: !1
529
348
  };
530
- const we = {
531
- install: (t, e = {}) => {
532
- t.component("xt-micro-view", se), ee();
533
- }
349
+ const setupApp = (h) => {
350
+ if (!h.url || h.url === "" || h.url === "undefined") {
351
+ ConsoleUtil.error("app url is required", h);
352
+ return;
353
+ }
354
+ let z = Object.assign({}, defaultAppOption, h), B = _apps[h.name];
355
+ return B ? _apps[h.name] = {
356
+ ...B,
357
+ ...z
358
+ } : _apps[h.name] = {
359
+ ...z,
360
+ instance: new MicroApp(h)
361
+ }, _apps[h.name];
362
+ }, getApp = (h) => _apps[h];
363
+ var setApp = (h, z) => _apps[h.name] = {
364
+ ...h,
365
+ ...z
534
366
  };
535
- export {
536
- se as XTMicroView,
537
- g as clearParentUrl,
538
- fe as createAppUrl,
539
- we as default,
540
- I as getApp,
541
- ie as isMicro,
542
- pe as isParent,
543
- me as microInit,
544
- ue as reloadApp,
545
- he as setupApp,
546
- re as startApp,
547
- ae as stopApp,
548
- de as utils
367
+ const startApp = (h, z) => new Promise((B, V) => {
368
+ let H = getApp(h);
369
+ H ? (z && (H.instance.changeOptions(z), H = setApp(H, z)), H.preload ? H.instance.preloadRender(H.el) : H.instance.mount(H.el), B(H)) : V("app not found, please setup app first");
370
+ }), stopApp = (h) => {
371
+ let z = getApp(h);
372
+ z && z.instance.unmount();
373
+ }, reloadApp = (h, z = !1) => {
374
+ let B = getApp(h);
375
+ B && B.instance.reload(z);
376
+ }, clearParentUrl = (h) => {
377
+ ConsoleUtil.trace("clearParentUrl", h, CONSTANT.URL_PARAM_PREFIX + h);
378
+ let z = window.location.href.split("#");
379
+ ConsoleUtil.trace("url", z);
380
+ let B = new URL(z[0]);
381
+ B.searchParams.delete(CONSTANT.URL_PARAM_PREFIX + h);
382
+ let V = z.length > 1 ? B.href + "#" + z[1] : B.href;
383
+ return window.history.replaceState({}, "", V), V;
384
+ }, isMicro = () => window[CONSTANT.IS_MICRO] === !0, isParent = () => window[CONSTANT.MICRO_TYPE] === "parent", createAppUrl = (h, z = window.__XT_MICRO_APP?.name) => {
385
+ let B = window.location;
386
+ if (isMicro()) B = window.__XT_MICRO_APP.mainLocation;
387
+ else if (!z) {
388
+ ConsoleUtil.error("在主应用中需要传入应用名称");
389
+ return;
390
+ }
391
+ return `${B.origin}${B.pathname}?__XT_MICRO_${z}=${encodeURIComponent(h)}${B.hash}`;
549
392
  };
393
+ var XTMicroView_default = /* @__PURE__ */ defineComponent({
394
+ __name: "XTMicroView",
395
+ props: { appId: String },
396
+ setup(z) {
397
+ let G = z, K = ref(), q = () => {
398
+ G.appId && startApp(G.appId, {
399
+ el: K.value,
400
+ onUnload(h, z) {
401
+ ConsoleUtil.trace("on unload", z.app.name);
402
+ }
403
+ }).then((h) => {
404
+ ConsoleUtil.trace("app mounted", G.appId);
405
+ });
406
+ };
407
+ return watch(() => G.appId, (h, z) => {
408
+ h !== z && z && stopApp(z), q();
409
+ }), onMounted(() => {
410
+ q();
411
+ }), onUnmounted(() => {
412
+ ConsoleUtil.trace("「micro」", "app unmount", G.appId), clearParentUrl(G.appId);
413
+ }), (z, V) => (openBlock(), createElementBlock("div", mergeProps({
414
+ ref_key: "refPanel",
415
+ ref: K
416
+ }, z.$attrs, { class: "xt-micro" }), null, 16));
417
+ }
418
+ });
419
+ window[CONSTANT.MICRO_VERSION] = version, window.micro_api = { debug: ConsoleUtil.setEnable };
420
+ var src_default = { install: (h, z = {}) => {
421
+ h.component("xt-micro-view", XTMicroView_default), mainMicroInit();
422
+ } };
423
+ export { XTMicroView_default as XTMicroView, clearParentUrl, createAppUrl, src_default as default, getApp, isMicro, isParent, microInit, reloadApp, setupApp, startApp, stopApp, utils_exports as utils };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xingtukeji/micro",
3
- "version": "1.1.22",
3
+ "version": "1.1.24",
4
4
  "private": false,
5
5
  "description": "",
6
6
  "main": "dist/index.js",
@@ -14,10 +14,21 @@
14
14
  "access": "public",
15
15
  "registry": "https://registry.npmjs.org/"
16
16
  },
17
+ "dependencies": {
18
+ "vue": "^3.5.22"
19
+ },
17
20
  "devDependencies": {
18
- "vite-plugin-dts": "^4.5.4"
21
+ "@types/node": "^24.6.0",
22
+ "@vitejs/plugin-vue": "^6.0.1",
23
+ "@vue/tsconfig": "^0.8.1",
24
+ "typescript": "~5.9.3",
25
+ "vite": "npm:rolldown-vite@7.1.14",
26
+ "vue-tsc": "^3.1.0",
27
+ "vite-plugin-dts": "^4.5.4",
28
+ "vite-plugin-css-injected-by-js": "^3.5.2"
19
29
  },
20
30
  "scripts": {
21
- "build": "vite build"
31
+ "build": "vite build",
32
+ "pub": "pnpm publish --no-git-checks"
22
33
  }
23
34
  }