import { modifyResponse } from "https://esm.town/v/andreterron/codeOnVT_modifyResponse?v=9";
import { ribbonElement } from "https://esm.town/v/andreterron/codeOnVT_ribbonElement?v=7";
import { inferRequestVal } from "https://esm.town/v/andreterron/inferRequestVal?v=2";
import { rootValRef } from "https://esm.town/v/andreterron/rootValRef?v=3";
import { ValRef } from "https://esm.town/v/andreterron/ValRef?v=1";
export function modifyHtmlString(
bodyText: string,
{ val, style }: { val?: ValRef; style?: string } = {},
) {
val = val?.handle && val?.name ? val : rootValRef();
if (!val) {
console.error("Failed to infer val. Please set the options.val parameter to the desired `{ handle, name }`");
return bodyText;
}
const element = ribbonElement({ val, style });
const bodyIndex = bodyText.lastIndexOf("</body>");
const htmlIndex = bodyText.lastIndexOf("</html>");
if (bodyIndex !== -1 && (htmlIndex === -1 || bodyIndex < htmlIndex)) {
return bodyText.slice(0, bodyIndex) + element + bodyText.slice(bodyIndex);
} else if (htmlIndex !== -1) {
return bodyText.slice(0, htmlIndex) + element + bodyText.slice(htmlIndex);
} else {
return bodyText + element;
}
}
export function modifyFetchHandler(
handler: (req: Request) => Response | Promise<Response>,
{ val, style }: { val?: ValRef; style?: string } = {},
): (req: Request) => Promise<Response> {
return async (req: Request): Promise<Response> => {
const res = await handler(req);
val = val?.handle && val?.name ? val : inferRequestVal(req);
return modifyResponse(res, { val, style });
};
}
export default modifyFetchHandler;