diff --git a/dist/index.js b/dist/index.js index 1397c9a..7d992d2 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,14 +1,26 @@ // src/index.ts import { readFileSync } from "node:fs"; -function getViteConfiguration() { +function litHydrationPlugin() { return { + name: "astro-lit-hydration", + transform(code, id, options) { + if (options?.ssr) return; + if (!id.includes("type=script")) return; + if (code.includes("hydration-support")) return; + return `import '@semantic-ui/astro-lit/hydration-support.js'; +` + code; + } + }; +} +function getViteConfiguration(usePlugin) { + return { + plugins: usePlugin ? [litHydrationPlugin()] : [], optimizeDeps: { include: [ "@semantic-ui/astro-lit/dist/client.js", "@semantic-ui/astro-lit/client-shim.js", "@semantic-ui/astro-lit/hydration-support.js", - "@webcomponents/template-shadowroot/template-shadowroot.js", - "@lit-labs/ssr-client/lit-element-hydrate-support.js" + "@webcomponents/template-shadowroot/template-shadowroot.js" ], exclude: ["@semantic-ui/astro-lit/server.js"] }, @@ -17,6 +29,15 @@ function getViteConfiguration() { } }; } +function litHandlesDeferredHydration() { + try { + const resolved = import.meta.resolve("@lit-labs/ssr-client/lit-element-hydrate-support.js"); + const src = readFileSync(new URL(resolved), "utf-8"); + return src.includes("skip-hydration") || src.includes("deferredBySSR"); + } catch { + return false; + } +} function getContainerRenderer() { return { name: "@semantic-ui/astro-lit", @@ -32,14 +53,22 @@ function index_default() { "head-inline", readFileSync(new URL("../client-shim.min.js", import.meta.url), { encoding: "utf-8" }) ); - injectScript("before-hydration", `import '@semantic-ui/astro-lit/hydration-support.js';`); + const litNative = litHandlesDeferredHydration(); + if (litNative) { + injectScript("before-hydration", `import '@lit-labs/ssr-client/lit-element-hydrate-support.js';`); + } else { + injectScript( + "head-inline", + readFileSync(new URL("../hydration-support-global.js", import.meta.url), { encoding: "utf-8" }) + ); + } addRenderer({ name: "@semantic-ui/astro-lit", serverEntrypoint: "@semantic-ui/astro-lit/server.js", clientEntrypoint: "@semantic-ui/astro-lit/dist/client.js" }); updateConfig({ - vite: getViteConfiguration() + vite: getViteConfiguration(!litNative) }); }, "astro:build:setup": ({ vite, target }) => { diff --git a/hydration-support-global.js b/hydration-support-global.js new file mode 100644 index 0000000..b2fcbec --- /dev/null +++ b/hydration-support-global.js @@ -0,0 +1,43 @@ +// Inline script that sets up globalThis.litElementHydrateSupport synchronously. +// This MUST run before any module script that imports 'lit', because LitElement +// checks for this global during class definition and it's a one-shot opportunity. +// +// This sets up the STRUCTURAL patches (shadow root reuse, defer-hydration). +// The RENDER patches (hydrate vs render on update) must be loaded from the same +//