diff --git a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts new file mode 100644 index 000000000..d2bd90373 --- /dev/null +++ b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts @@ -0,0 +1,279 @@ +/** + * 入口 HTML 已将 CSS 转成 style 后,动态再插入同 href 的 link 不应再生成第二份 style。 + * 仍需对原 link 派发 load,避免 Vite preload 一直等待。 + */ + +export {}; + +const { + findStylesByCssHref, + hasStyleSheetContent, + dispatchStyleSheetLoadAsync, + canonicalCssHref, +} = require("../../src/effect"); + +const HREF = "https://cdn.example.com/assets/shared.css"; +const CSS = ".box{width:100%;height:100%}"; + +describe("findStylesByCssHref / 入口 HTML 与动态 preload 同 href 去重", () => { + afterEach(() => { + document.head.innerHTML = ""; + }); + + it("能匹配带 data-wujie-css-href 的入口 style", () => { + document.head.innerHTML = ``; + const [found] = findStylesByCssHref(document, HREF); + expect(found).toBeDefined(); + expect(found.getAttribute("data-wujie-css-href")).toBe(HREF); + }); + + it("没有属性时能匹配注释开头的旧入口 style", () => { + document.head.innerHTML = ``; + const [found] = findStylesByCssHref(document, HREF); + expect(found).toBeDefined(); + expect(found.textContent.indexOf(`/* ${HREF} */`)).toBe(0); + }); + + it("不同 href 不应命中", () => { + document.head.innerHTML = ``; + expect(findStylesByCssHref(document, "https://cdn.example.com/assets/other.css")).toHaveLength(0); + }); + + it("返回同 href 的全部 style", () => { + document.head.innerHTML = ``; + expect(findStylesByCssHref(document, HREF)).toHaveLength(2); + }); + + it("属性值经过 HTML 转义后仍能按原 href 命中", () => { + const href = 'https://cdn.example.com/assets/shared.css?q="a"&b=1'; + const style = document.createElement("style"); + style.setAttribute("data-wujie-css-href", canonicalCssHref(href)); + style.textContent = `/* ${href} */${CSS}`; + document.head.appendChild(style); + document.head.innerHTML = document.head.innerHTML; + + const [found] = findStylesByCssHref(document, href); + expect(found).toBeDefined(); + expect(found.getAttribute("data-wujie-css-href")).toBe(canonicalCssHref(href)); + }); + + it("查询串编码不同的同一绝对地址仍能命中", () => { + const stored = "https://cdn.example.com/assets/shared.css?v=a%20b"; + const lookup = "https://cdn.example.com/assets/shared.css?v=a b"; + document.head.innerHTML = ``; + expect(findStylesByCssHref(document, lookup)).toHaveLength(1); + }); +}); + +describe("hasStyleSheetContent / 是否可复用", () => { + function styleOf(text: string): HTMLStyleElement { + const style = document.createElement("style"); + style.textContent = text; + return style; + } + + it("有规则的样式可复用", () => { + expect(hasStyleSheetContent(styleOf(`/* ${HREF} */${CSS}`))).toBe(true); + expect(hasStyleSheetContent(styleOf(CSS))).toBe(true); + }); + + it("只有入口注释或为空的样式不可复用", () => { + expect(hasStyleSheetContent(styleOf(`/* ${HREF} */`))).toBe(false); + expect(hasStyleSheetContent(styleOf(""))).toBe(false); + expect(hasStyleSheetContent(styleOf(" \n "))).toBe(false); + }); +}); + +describe("命中去重后的 load 派发 / 消费方监听注册晚于 appendChild", () => { + function makeLink(): HTMLLinkElement { + const link = document.createElement("link"); + link.setAttribute("rel", "stylesheet"); + link.setAttribute("href", HREF); + return link; + } + + it("监听在派发之后才注册时仍能收到 load(Vite preload 的顺序)", async () => { + const link = makeLink(); + let loaded = 0; + + // 对应运行时:劫持的 appendChild 内部命中去重后补发 load + dispatchStyleSheetLoadAsync(link); + // Vite preload 是在 appendChild 返回之后才 addEventListener("load") + const loadPromise = new Promise((resolve) => { + link.addEventListener("load", () => { + loaded += 1; + resolve(); + }); + }); + + await expect(loadPromise).resolves.toBeUndefined(); + expect(loaded).toBe(1); + }); + + it("不在调用栈内同步派发", async () => { + const link = makeLink(); + const onLoad = jest.fn(); + link.addEventListener("load", onLoad); + + dispatchStyleSheetLoadAsync(link); + expect(onLoad).not.toHaveBeenCalled(); + + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(onLoad).toHaveBeenCalledTimes(1); + }); + + it("显式 error 时不派发 load", async () => { + const link = makeLink(); + const onLoad = jest.fn(); + const onError = jest.fn(); + link.addEventListener("load", onLoad); + link.addEventListener("error", onError); + + dispatchStyleSheetLoadAsync(link, "error"); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(onLoad).not.toHaveBeenCalled(); + expect(onError).toHaveBeenCalledTimes(1); + }); +}); + +describe("appendChild 劫持 / 同 href 去重的派发时机", () => { + const { patchRenderEffect } = require("../../src/effect"); + const { addSandboxCacheWithWujie, deleteWujieById } = require("../../src/common"); + const { clearAssetsCache } = require("../../src/entry"); + + const WUJIE_ID = "css-href-dedupe-app"; + const HREF = "https://cdn.example.com/assets/shared.css"; + let fetchGate: { resolve: (value: string) => void; reject: (reason?: unknown) => void }; + let sandbox: any; + + function makeLink(): HTMLLinkElement { + const link = document.createElement("link"); + link.rel = "stylesheet"; + link.href = HREF; + return link; + } + + function eventOf(link: HTMLLinkElement, type: "load" | "error"): Promise { + return new Promise((resolve) => link.addEventListener(type, () => resolve())); + } + + beforeEach(() => { + document.head.innerHTML = ""; + document.body.innerHTML = ""; + clearAssetsCache(); + let resolveFetch: (value: string) => void; + let rejectFetch: (reason?: unknown) => void; + const pending = new Promise((resolve, reject) => { + resolveFetch = resolve; + rejectFetch = reject; + }); + fetchGate = { resolve: resolveFetch, reject: rejectFetch }; + sandbox = { + id: WUJIE_ID, + styleSheetElements: [], + replace: null, + plugins: [], + lifecycles: {}, + proxyLocation: { protocol: "https:", host: "cdn.example.com", pathname: "/", href: "https://cdn.example.com/" }, + fiber: false, + degrade: true, + iframe: { contentDocument: document, contentWindow: window }, + fetch: jest.fn(() => pending.then((text) => ({ status: 200, text: () => Promise.resolve(text) }))), + }; + addSandboxCacheWithWujie(WUJIE_ID, sandbox); + patchRenderEffect(document, WUJIE_ID, true); + }); + + afterEach(() => { + deleteWujieById(WUJIE_ID); + clearAssetsCache(); + }); + + it("占位还在拉取时,第二份 link 要等原来的请求结束才收到 load", async () => { + const first = makeLink(); + const second = makeLink(); + const firstLoad = eventOf(first, "load"); + const secondLoad = eventOf(second, "load"); + let secondLoaded = false; + second.addEventListener("load", () => { + secondLoaded = true; + }); + + document.head.appendChild(first); + document.head.appendChild(second); + await Promise.resolve(); + + expect(document.head.querySelectorAll("style")).toHaveLength(1); + expect(document.head.querySelector("style").hasAttribute("data-wujie-css-pending")).toBe(true); + expect(secondLoaded).toBe(false); + + fetchGate.resolve(".box{width:100%}"); + await firstLoad; + await secondLoad; + expect(document.head.querySelector("style").hasAttribute("data-wujie-css-pending")).toBe(false); + expect(document.head.querySelector("style").textContent).toContain(".box{width:100%}"); + }); + + it("入口已有内容时直接复用,不再请求", async () => { + document.head.innerHTML = ``; + + const link = makeLink(); + const onError = jest.fn(); + link.addEventListener("error", onError); + document.head.appendChild(link); + await eventOf(link, "load"); + + expect(onError).not.toHaveBeenCalled(); + expect(sandbox.fetch).not.toHaveBeenCalled(); + expect(document.head.querySelectorAll("style")).toHaveLength(1); + }); + + describe("已有样式为空时不复用", () => { + let warnSpy: jest.SpyInstance; + + beforeEach(() => { + warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {}); + }); + + afterEach(() => { + warnSpy.mockRestore(); + }); + + it("入口请求失败留下的空 style:后来的 link 重新请求,成功后收到 load", async () => { + document.head.innerHTML = ``; + + const link = makeLink(); + const onError = jest.fn(); + link.addEventListener("error", onError); + const linkLoad = eventOf(link, "load"); + document.head.appendChild(link); + fetchGate.resolve(CSS); + await linkLoad; + + expect(onError).not.toHaveBeenCalled(); + expect(sandbox.fetch).toHaveBeenCalledTimes(1); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("内容为空"), HREF); + const styles = document.head.querySelectorAll("style"); + expect(styles).toHaveLength(2); + expect(styles[1].textContent).toContain(CSS); + }); + + it("空 CSS 文件:后来的 link 收到 load 而不是 error", async () => { + const first = makeLink(); + document.head.appendChild(first); + fetchGate.resolve(""); + await eventOf(first, "load"); + + const second = makeLink(); + const secondLoad = eventOf(second, "load"); + const onError = jest.fn(); + second.addEventListener("error", onError); + document.head.appendChild(second); + await secondLoad; + + expect(onError).not.toHaveBeenCalled(); + expect(document.head.querySelectorAll("style")).toHaveLength(2); + }); + }); +}); diff --git a/packages/wujie-core/src/constant.ts b/packages/wujie-core/src/constant.ts index 8ea488986..13c09871f 100644 --- a/packages/wujie-core/src/constant.ts +++ b/packages/wujie-core/src/constant.ts @@ -41,6 +41,7 @@ export const WUJIE_TIPS_NO_FETCH = "window上不存在fetch属性,需要自行 export const WUJIE_TIPS_NOT_SUPPORTED = "当前浏览器不支持无界,子应用将采用iframe方式渲染"; export const WUJIE_TIPS_SCRIPT_ERROR_REQUESTED = "脚本请求出现错误"; export const WUJIE_TIPS_CSS_ERROR_REQUESTED = "样式请求出现错误"; +export const WUJIE_TIPS_CSS_DEDUPE_EMPTY = "已存在同地址样式但内容为空(空文件或此前请求失败),将重新请求"; export const WUJIE_TIPS_HTML_ERROR_REQUESTED = "html请求出现错误"; export const WUJIE_TIPS_REPEAT_RENDER = "无界组件短时间重复渲染了两次,可能存在性能问题请检查代码"; export const WUJIE_TIPS_NO_SCRIPT = "目标Script尚未准备好或已经被移除"; diff --git a/packages/wujie-core/src/effect.ts b/packages/wujie-core/src/effect.ts index de0acdef6..c8ebd8715 100644 --- a/packages/wujie-core/src/effect.ts +++ b/packages/wujie-core/src/effect.ts @@ -33,6 +33,7 @@ import { WUJIE_DATA_FLAG, WUJIE_TIPS_REPEAT_RENDER, WUJIE_TIPS_NO_SCRIPT, + WUJIE_TIPS_CSS_DEDUPE_EMPTY, WUJIE_APP_ID, } from "./constant"; import { ScriptObject, parseTagAttributes } from "./template"; @@ -264,6 +265,77 @@ export function deferStyleSheetByHref(opts: { }, DEFER_STYLE_HREF_TIMEOUT); } +/** + * 去重键用 URL 序列化后的绝对地址。 + * 入口模板走 URL#toString,动态插入走 URL#href;两者在查询串空格等字符上可能不一致,比较前先归一。 + */ +export function canonicalCssHref(href: string): string { + if (!href) return ""; + try { + return new URL(href).href; + } catch { + return href; + } +} + +/** + * 按绝对 href 查找所有已转换的样式。 + * 匹配动态占位和入口 HTML 写入的 data-wujie-css-href; + * 没有该属性时,兼容旧的注释形态:style 文本以 `/* href *\/` 开头。 + * 不用属性选择器:href 里的引号会截断选择器,入口 HTML 又必须先做属性转义。 + */ +export function findStylesByCssHref(doc: Document | null, href: string): HTMLStyleElement[] { + if (!href || !doc) return []; + const target = canonicalCssHref(href); + const styles = doc.querySelectorAll("style"); + const matched: HTMLStyleElement[] = []; + for (let i = 0; i < styles.length; i++) { + const style = styles[i] as HTMLStyleElement; + const marked = style.getAttribute("data-wujie-css-href"); + if (marked && canonicalCssHref(marked) === target) matched.push(style); + else if (!marked && (style.textContent || "").indexOf(`/* ${href} */`) === 0) matched.push(style); + } + return matched; +} + +/** + * 样式是否有可复用的内容(忽略入口 HTML 写入的开头注释 `/* href *\/`)。 + * 样式请求失败时 fetchAssets 也返回空串,空文件与请求失败无法区分,两者都视为不可复用。 + */ +export function hasStyleSheetContent(style: HTMLStyleElement): boolean { + return (style.textContent || "").replace(/^\s*\/\*[\s\S]*?\*\//, "").trim() !== ""; +} + +/** + * 命中去重后对原 link 补发事件。 + * + * 必须异步派发:消费方是在 appendChild 返回之后才 addEventListener, + * 而本函数由劫持的 appendChild 同步调用,在调用栈内同步派发时监听尚未注册,事件会被丢弃。 + */ +export function dispatchStyleSheetLoadAsync(linkElement: HTMLLinkElement, event: "load" | "error" = "load"): void { + setTimeout(() => manualInvokeElementEvent(linkElement, event), 0); +} + +type StyleSheetWaiter = { + linkElement: HTMLLinkElement; +}; + +/** + * 同一 href 还在拉取时,后来的 link 不能立刻收到 load。 + * 登记到占位 style 上,等原来那次请求结束再派发同一个结果。 + */ +function enqueueStyleSheetWaiter(styleElement: HTMLStyleElement, linkElement: HTMLLinkElement): void { + const waiters = ((styleElement as any)._wujieStyleWaiters || []) as StyleSheetWaiter[]; + waiters.push({ linkElement }); + (styleElement as any)._wujieStyleWaiters = waiters; +} + +function flushStyleSheetWaiters(styleElement: HTMLStyleElement, event: "load" | "error"): void { + const waiters = ((styleElement as any)._wujieStyleWaiters || []) as StyleSheetWaiter[]; + (styleElement as any)._wujieStyleWaiters = []; + waiters.forEach(({ linkElement }) => dispatchStyleSheetLoadAsync(linkElement, event)); +} + let dynamicScriptExecStack = Promise.resolve(); function rewriteAppendOrInsertChild(opts: { rawDOMAppendOrInsertBefore: (newChild: T, refChild?: Node | null) => T; @@ -311,12 +383,28 @@ function rewriteAppendOrInsertChild(opts: { const exclude = isMatchUrl(styleHref, getEffectLoaders("cssExcludes", plugins)); if (!styleHref || exclude) return; + // 入口 HTML 已转成 style,或先前动态插入已占位时,不再插第二份。 + // 仍需对原 link 派发事件,避免 Vite preload 一直等待。 + // pending 表示原来那次请求还没结束,此时不能派发 load,否则 preload 后面的 chunk 会提前执行。 + // 已有样式都为空时不复用,按原流程重新请求,请求失败的情况可以借此恢复。 + const existingStyles = findStylesByCssHref(iframeDocument, styleHref); + if (existingStyles.some(hasStyleSheetContent)) { + dispatchStyleSheetLoadAsync(linkElement); + return; + } + const pendingStyle = existingStyles.find((style) => style.hasAttribute("data-wujie-css-pending")); + if (pendingStyle) { + enqueueStyleSheetWaiter(pendingStyle, linkElement); + return; + } + if (existingStyles.length) warn(WUJIE_TIPS_CSS_DEDUPE_EMPTY, styleHref); + // 立即创建占位 ` + : `` ); } else if (content) { embedHTML = embedHTML.replace( @@ -123,6 +132,10 @@ async function getEmbedHTML(template, styleResultList: StyleResultList): Promise const isInlineCode = (code) => code.startsWith("<"); +function escapeHtmlAttr(value: string): string { + return String(value).replace(/&/g, "&").replace(/"/g, """); +} + const fetchAssets = ( src: string, cache: Object,