All files / apps/portfolio/server/plugins deferHydration.ts

37.93% Statements 11/29
0% Branches 0/6
66.66% Functions 6/9
38.46% Lines 10/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 651x 1x                               1x                                                                   1x 24x   1x 48x 12x       12x 12x      
const ENTRY_SCRIPT = /<script(?=[^>]*\stype="module")[^>]*\ssrc="([^"]+)"[^>]*><\/script>/;
const PENDING_CLICK = "__pendingClick";
 
interface EventSource {
    addEventListener(
        type: string,
        listener: (event: { target: unknown }) => void,
        options?: object,
    ): void;
}
 
declare const window: EventSource & Record<string, unknown>;
declare const document: {
    head: { append(node: object): void };
    createElement(tag: "script"): { type: string; crossOrigin: string; src: string };
};
 
const loadEntryOnLoadOrIntent = (src: string, pendingClick: string): void => {
    const controller = new AbortController();
    const once = { capture: true, once: true, passive: true, signal: controller.signal };
 
    const start = (): void => {
        if (controller.signal.aborted) return;
        controller.abort();
 
        const script = document.createElement("script");
 
        script.type = "module";
        script.crossOrigin = "";
        script.src = src;
        document.head.append(script);
    };
 
    window.addEventListener("load", start, { signal: controller.signal });
    for (const type of ["pointerdown", "keydown", "touchstart"]) {
        window.addEventListener(type, start, once);
    }
 
    window.addEventListener(
        "click",
        ({ target }) => {
            const control = (target as { closest?(selector: string): unknown })?.closest?.(
                "button, [role=button], summary",
            );
 
            if (control && window[pendingClick] === undefined) window[pendingClick] = control;
        },
        { capture: true },
    );
};
 
const toInlineScript = (fn: (...args: string[]) => void, ...args: string[]): string =>
    `<script>(${fn.toString()})(${args.map((arg) => JSON.stringify(arg)).join(",")})</script>`;
 
const deferHydration = (headChunk: string): string =>
    headChunk.replace(ENTRY_SCRIPT, (_tag, src: string) =>
        toInlineScript(loadEntryOnLoadOrIntent, src, PENDING_CLICK),
    );
 
export default defineNitroPlugin((nitroApp) => {
    nitroApp.hooks.hook("render:html", (html) => {
        html.head = html.head.map(deferHydration);
    });
});